예제 #1
0
  /**
   * Takes a list of feeds and a writer and writes those into an OPML document.
   *
   * @throws IOException
   * @throws IllegalStateException
   * @throws IllegalArgumentException
   */
  public void writeDocument(List<Feed> feeds, Writer writer)
      throws IllegalArgumentException, IllegalStateException, IOException {
    if (AppConfig.DEBUG) Log.d(TAG, "Starting to write document");
    XmlSerializer xs = Xml.newSerializer();
    xs.setOutput(writer);

    xs.startDocument(ENCODING, false);
    xs.startTag(null, OpmlSymbols.OPML);
    xs.attribute(null, OpmlSymbols.VERSION, OPML_VERSION);

    xs.startTag(null, OpmlSymbols.HEAD);
    xs.startTag(null, OpmlSymbols.TITLE);
    xs.text(OPML_TITLE);
    xs.endTag(null, OpmlSymbols.TITLE);
    xs.endTag(null, OpmlSymbols.HEAD);

    xs.startTag(null, OpmlSymbols.BODY);
    for (Feed feed : feeds) {
      xs.startTag(null, OpmlSymbols.OUTLINE);
      xs.attribute(null, OpmlSymbols.TEXT, feed.getTitle());
      if (feed.getType() != null) {
        xs.attribute(null, OpmlSymbols.TYPE, feed.getType());
      }
      xs.attribute(null, OpmlSymbols.XMLURL, feed.getDownload_url());
      if (feed.getLink() != null) {
        xs.attribute(null, OpmlSymbols.HTMLURL, feed.getLink());
      }
      xs.endTag(null, OpmlSymbols.OUTLINE);
    }
    xs.endTag(null, OpmlSymbols.BODY);
    xs.endTag(null, OpmlSymbols.OPML);
    xs.endDocument();
    if (AppConfig.DEBUG) Log.d(TAG, "Finished writing document");
  }
예제 #2
0
  private void doTasksExport(String output) throws IOException {
    File xmlFile = new File(output);
    xmlFile.createNewFile();
    FileOutputStream fos = new FileOutputStream(xmlFile);
    xml = Xml.newSerializer();
    xml.setOutput(fos, BackupConstants.XML_ENCODING);

    xml.startDocument(null, null);
    xml.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

    xml.startTag(null, BackupConstants.ASTRID_TAG);
    xml.attribute(
        null,
        BackupConstants.ASTRID_ATTR_VERSION,
        Integer.toString(preferences.getLastSetVersion()));
    xml.attribute(null, BackupConstants.ASTRID_ATTR_FORMAT, Integer.toString(FORMAT));

    serializeTasks();
    serializeTagDatas();

    xml.endTag(null, BackupConstants.ASTRID_TAG);
    xml.endDocument();
    xml.flush();
    fos.close();
  }
예제 #3
0
  public String buildFormSubmissionXMLString(String formName, Long recordId) {
    try {
      Document document = getXMLModelTemplateForFormName(formName);

      XmlSerializer serializer = Xml.newSerializer();
      StringWriter writer = new StringWriter();
      serializer.setOutput(writer);
      serializer.startDocument("UTF-8", true);

      // <model><instance>
      Element el = (Element) document.getElementsByTagName("model").item(0).getFirstChild();
      NodeList entries = el.getChildNodes();
      int num = entries.getLength();
      for (int i = 0; i < num; i++) {
        Element node = (Element) entries.item(i);
        writeXML(node, serializer, recordId);
      }

      serializer.endDocument();

      String xml = writer.toString();
      // xml = xml.replaceAll("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>","");//56
      // !!!this ain't working
      xml = xml.substring(56);
      System.out.println(xml);

      return xml;

    } catch (Exception e) {
      e.printStackTrace();
    }

    return "";
  }
  public byte[] encode(int offset, int count) throws UnsupportedEncodingException {
    StringWriter sw = new StringWriter();
    XmlSerializer xmlMsgElement = Xml.newSerializer();
    int i, stopIndex;
    if (offset > subFolders.size())
      throw new IllegalArgumentException("FolderListingEncode: offset > subFolders.size()");

    stopIndex = offset + count;
    if (stopIndex > subFolders.size()) stopIndex = subFolders.size();

    try {
      xmlMsgElement.setOutput(sw);
      xmlMsgElement.startDocument(null, null);
      xmlMsgElement.text("\n");
      xmlMsgElement.startTag("", "folder-listing");
      xmlMsgElement.attribute("", "version", "1.0");
      for (i = offset; i < stopIndex; i++) {
        xmlMsgElement.startTag("", "folder");
        xmlMsgElement.attribute("", "name", subFolders.get(i).getName());
        xmlMsgElement.endTag("", "folder");
      }
      xmlMsgElement.endTag("", "folder-listing");
      xmlMsgElement.endDocument();
    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalStateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return sw.toString().getBytes("UTF-8");
  }
예제 #5
0
 /**
  * Creates a new DomElement object.
  *
  * @param contentType_QNAME the content type_ qname
  * @param class1 the class1
  * @param object the object
  * @param value the value
  * @return the element
  */
 private String createElement(
     String contentType_QNAME, Class<?> class1, Object object, Object value) {
   if (value != null) {
     StringWriter writer = new StringWriter();
     try {
       XmlSerializer serializer = XML_SERIALIZER_FACTORY.newSerializer();
       serializer.setOutput(writer);
       serializer = serializer.startTag(null, contentType_QNAME);
       if (class1.equals(InviteConnectType.class)) {
         XppUtils.setElementValue(serializer, ((InviteConnectType) value).value());
       } else if (class1.equals(NetworkUpdateReturnType.class)) {
         XppUtils.setElementValue(serializer, ((NetworkUpdateReturnType) value).value());
       } else if (class1.equals(NetworkUpdateContentType.class)) {
         XppUtils.setElementValue(serializer, ((NetworkUpdateContentType) value).value());
       } else {
         XppUtils.setElementValue(serializer, String.valueOf(value));
       }
       serializer.endTag(null, contentType_QNAME);
       serializer.flush();
     } catch (Exception e) {
       LOG.log(Level.SEVERE, "An error occurred while creating xml content.", e);
     }
     return writer.toString();
   } else {
     return null;
   }
 }
예제 #6
0
  protected String getEnrolmentBodyXml(SIP5060ProvisioningRequest req) {

    SharedPreferences settings =
        getSharedPreferences(RegisterAccount.PREFS_FILE, Context.MODE_PRIVATE);

    String enrolmentNum = settings.getString(RegisterAccount.PREF_PHONE_NUMBER, "");

    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    try {
      serializer.setOutput(writer);
      serializer.startDocument("UTF-8", true);
      String ns = RegistrationUtil.NS;
      serializer.startTag(ns, "enrolment");

      RegistrationUtil.serializeProperty(serializer, ns, "phoneNumber", enrolmentNum);
      RegistrationUtil.serializeProperty(serializer, ns, "secret", req.getAuthPassword());
      RegistrationUtil.serializeProperty(serializer, ns, "firstName", "");
      RegistrationUtil.serializeProperty(serializer, ns, "lastName", "");
      RegistrationUtil.serializeProperty(serializer, ns, "emailAddress", "");
      RegistrationUtil.serializeProperty(serializer, ns, "language", getLanguage());

      serializer.endTag(ns, "enrolment");
      serializer.endDocument();
      return writer.toString();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
예제 #7
0
  public String createNewUserXML(
      String login,
      String firstName,
      String lastName,
      String email,
      String timezone,
      boolean admin,
      String password)
      throws IllegalArgumentException, IllegalStateException, IOException {

    serializer = Xml.newSerializer();
    writer = new StringWriter();
    serializer.setOutput(writer);

    serializer.startDocument("UTF-8", null);
    serializer.startTag("", "user");

    addLogin(login);
    addFirstName(firstName);
    addLastName(lastName);
    addEmail(email);
    addTimezone(timezone);
    addAdmin(admin ? "1" : "");
    addPassword(password);

    serializer.endTag("", "user");
    serializer.endDocument();
    return writer.toString();
  }
예제 #8
0
  public String createModifyServerXML(Server server)
      throws IllegalArgumentException, IllegalStateException, IOException {
    serializer = Xml.newSerializer();
    writer = new StringWriter();
    serializer.setOutput(writer);

    serializer.startDocument("UTF-8", null);
    serializer.startTag("", "release_server");

    // TODO refactor for better performance
    addName(server.getName());
    addLocalPath(server.getLocalPath());
    addRemotePath(server.getRemotePath());
    addRemoteAddr(server.getRemoteAddr());
    addProtocol(server.getProtocol());
    addPort(server.getPort());
    addLogin(server.getLogin());
    addPassword(server.getPassword());
    addUseActiveMode(server.isUseActiveMode());
    addAuthenticateByKey(server.isAuthenticateByKey());
    addUseFeat(server.isUseFeat());
    addPreReleaseHook(server.getPreReleaseHook());
    addPostReleaseHook(server.getPostReleaseHook());

    serializer.endTag("", "release_server");
    serializer.endDocument();
    return writer.toString();
  }
예제 #9
0
    @Override
    protected String doInBackground(OsmPoint... points) {
      FileOutputStream out = null;
      try {
        out = new FileOutputStream(osmchange);
        XmlSerializer sz = Xml.newSerializer();

        sz.setOutput(out, "UTF-8");
        sz.startDocument("UTF-8", true);
        sz.startTag("", "osmChange");
        sz.attribute("", "generator", "OsmAnd");
        sz.attribute("", "version", "0.6");
        sz.startTag("", "create");
        writeContent(sz, points, OsmPoint.Action.CREATE);
        sz.endTag("", "create");
        sz.startTag("", "modify");
        writeContent(sz, points, OsmPoint.Action.MODIFY);
        sz.endTag("", "modify");
        sz.startTag("", "delete");
        writeContent(sz, points, OsmPoint.Action.DELETE);
        sz.endTag("", "delete");
        sz.endTag("", "osmChange");
        sz.endDocument();
      } catch (Exception e) {
        return e.getMessage();
      } finally {
        try {
          if (out != null) out.close();
        } catch (IOException e) {
        }
      }

      return null;
    }
예제 #10
0
  private void openIfRequired() throws IOException {
    String state = Environment.getExternalStorageState();
    if (mSerializer == null) {
      String fileName = mReportFile;
      if (mMultiFile) {
        fileName = fileName.replace("$(suite)", "test");
      }
      if (mReportDir == null) {
        if (Environment.MEDIA_MOUNTED.equals(state)
            && !Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
          File f = mContext.getExternalFilesDir("testng");
          mOutputStream = new FileOutputStream(new File(f, fileName));
        } else {
          mOutputStream = mTargetContext.openFileOutput(fileName, 0);
        }
      } else {
        mOutputStream = new FileOutputStream(new File(mReportDir, fileName));
      }

      mSerializer = Xml.newSerializer();
      mSerializer.setOutput(mOutputStream, ENCODING_UTF_8);
      mSerializer.startDocument(ENCODING_UTF_8, true);
      if (!mMultiFile) {
        mSerializer.startTag("", TAG_SUITES);
      }
    }
  }
예제 #11
0
	public static String XMLContent(List<Book> books, Writer writer)
	{
		XmlSerializer serializer = Xml.newSerializer();
		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);
			serializer.startTag("", "books");
			for (Book book : books) {
				serializer.startTag("", "book");
				serializer.attribute("", "id", String.valueOf(book.getId()));
				serializer.startTag("", "name");
				serializer.text(book.getName());
				serializer.endTag("", "name");
				serializer.startTag("", "price");
				serializer.text(String.valueOf(book.getPrice()));
				serializer.endTag("", "price");
				serializer.endTag("", "book");
			}
			serializer.endTag("", "books");
			serializer.endDocument();
			return writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
예제 #12
0
파일: MessageList.java 프로젝트: anwell/HLN
 private String writeXml() {
   XmlSerializer serializer = Xml.newSerializer();
   StringWriter writer = new StringWriter();
   try {
     serializer.setOutput(writer);
     serializer.startDocument("UTF-8", true);
     serializer.startTag("", "messages");
     serializer.attribute("", "number", String.valueOf(messages.size()));
     for (Message msg : messages) {
       serializer.startTag("", "message");
       serializer.attribute("", "date", msg.getDate());
       serializer.startTag("", "title");
       serializer.text(msg.getTitle());
       serializer.endTag("", "title");
       serializer.startTag("", "url");
       serializer.text(msg.getLink().toExternalForm());
       serializer.endTag("", "url");
       serializer.startTag("", "body");
       serializer.text(msg.getDescription());
       serializer.endTag("", "body");
       serializer.endTag("", "message");
     }
     serializer.endTag("", "messages");
     serializer.endDocument();
     return writer.toString();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
예제 #13
0
  /*
   * Writes the user list file in this format:
   *
   * <users nextSerialNumber="3">
   *   <user id="0"></user>
   *   <user id="2"></user>
   * </users>
   */
  private void writeUserListLocked() {
    FileOutputStream fos = null;
    AtomicFile userListFile = new AtomicFile(mUserListFile);
    try {
      fos = userListFile.startWrite();
      final BufferedOutputStream bos = new BufferedOutputStream(fos);

      // XmlSerializer serializer = XmlUtils.serializerInstance();
      final XmlSerializer serializer = new FastXmlSerializer();
      serializer.setOutput(bos, "utf-8");
      serializer.startDocument(null, true);
      serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

      serializer.startTag(null, TAG_USERS);
      serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
      serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));

      for (int i = 0; i < mUsers.size(); i++) {
        UserInfo user = mUsers.valueAt(i);
        serializer.startTag(null, TAG_USER);
        serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
        serializer.endTag(null, TAG_USER);
      }

      serializer.endTag(null, TAG_USERS);

      serializer.endDocument();
      userListFile.finishWrite(fos);
    } catch (Exception e) {
      userListFile.failWrite(fos);
      Slog.e(LOG_TAG, "Error writing user list");
    }
  }
  /** Make sure we won't pass invalid characters to XML serializer. */
  public void testWriteReadNoCrash() throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    XmlSerializer serializer = Xml.newSerializer();
    serializer.setOutput(os, StandardCharsets.UTF_8.name());
    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    serializer.startDocument(null, true);

    for (int ch = 0; ch < 0x10000; ch++) {
      checkWriteSingleSetting(
          "char=0x" + Integer.toString(ch, 16), serializer, "key", String.valueOf((char) ch));
    }
    checkWriteSingleSetting(serializer, "k", "");
    checkWriteSingleSetting(serializer, "x", "abc");
    checkWriteSingleSetting(serializer, "abc", CRAZY_STRING);
    checkWriteSingleSetting(serializer, "def", null);

    // Invlid input, but shouoldn't crash.
    checkWriteSingleSetting(serializer, null, null);
    checkWriteSingleSetting(serializer, CRAZY_STRING, null);
    SettingsState.writeSingleSetting(
        SettingsState.SETTINGS_VERSOIN_NEW_ENCODING, serializer, null, "k", "v", "package");
    SettingsState.writeSingleSetting(
        SettingsState.SETTINGS_VERSOIN_NEW_ENCODING, serializer, "1", "k", "v", null);
  }
예제 #15
0
  private void writeDataElements(Writer out, HashTree sorted) throws IOException {
    XmlSerializer xml = null;
    try {
      XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
      xml = factory.newSerializer();
    } catch (XmlPullParserException xppe) {
      throw new RuntimeException("Couldn't obtain xml serializer", xppe);
    }

    // we need to write our header manually, because we need to specify
    // XML version 1.1
    out.write(DATA_XML_HEADER + NEWLINE + NEWLINE);

    xml.setOutput(out);
    xml.startTag(null, DATA_ELEM);
    xml.ignorableWhitespace(NEWLINE);

    writeDataElementsForNode(xml, sorted, 0);

    xml.endTag(null, DATA_ELEM);
    xml.ignorableWhitespace(NEWLINE);
    xml.endDocument();

    out.flush();
  }
 private String createSoapRequest(HashMap<String, String> requestFields) {
   XmlSerializer serializer = Xml.newSerializer();
   StringWriter writer = new StringWriter();
   try {
     serializer.setOutput(writer);
     serializer.setPrefix(SOAPENV, ENV);
     serializer.setPrefix(URN_STRING, URN);
     serializer.startTag(ENV, ENVELOPE);
     serializer.startTag(ENV, HEADER);
     serializer.startTag(URN, SESSION_HEADER);
     serializer.startTag(URN, SESSION_ID);
     serializer.text(requestFields.get(SESSION_ID));
     serializer.endTag(URN, SESSION_ID);
     serializer.endTag(URN, SESSION_HEADER);
     serializer.startTag(ENV, CALLOPTIONS);
     serializer.startTag(URN, CLIENT);
     serializer.text(requestFields.get(CLIENT));
     serializer.endTag(URN, CLIENT);
     serializer.endTag(ENV, CALLOPTIONS);
     serializer.endTag(ENV, HEADER);
     serializer.startTag(ENV, BODY);
     serializer.startTag(URN, LOGOUT);
     serializer.endTag(URN, LOGOUT);
     serializer.endTag(ENV, BODY);
     serializer.endTag(ENV, ENVELOPE);
     serializer.endDocument();
     return writer.toString();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
  public static synchronized String createXMLContentPathList(List<String> paths) {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();

    try {
      serializer.setOutput(writer);
      serializer.startDocument("UTF-8", false);

      final String nns = null; // no namespace
      final String ns = "urn:schemas-upnp-org:dm:cms";

      serializer.setPrefix("xsi", "http://www.w3.org/2001/XMLSchema-instance");
      serializer.setPrefix("cms", ns);

      serializer.startTag(ns, XMLCONTENTPATHLIST);
      serializer.attribute(
          "http://www.w3.org/2001/XMLSchema-instance",
          "schemaLocation",
          "urn:schemas-upnp-org:dm:cms http://www.upnp.org/schemas/dm/cms.xsd");

      for (String path : paths) {
        serializer.startTag(nns, XMLCONTENTPATH);
        serializer.text(path);
        serializer.endTag(nns, XMLCONTENTPATH);
      }

      serializer.endTag(ns, XMLCONTENTPATHLIST);

      serializer.endDocument();
      return writer.toString();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  public static String createXMLSensorRecordInfo(List<String> fields) {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();

    try {
      serializer.setOutput(writer);
      serializer.startDocument("UTF-8", false);

      final String nns = null; // no namespace
      final String ns = "urn:schemas-upnp-org:smgt:srecinfo";

      serializer.setPrefix("xsi", "http://www.w3.org/2001/XMLSchema-instance");
      serializer.setPrefix("", ns);
      serializer.startTag(ns, XMLSENSORRECORDINFO);
      serializer.attribute(
          "http://www.w3.org/2001/XMLSchema-instance",
          "schemaLocation",
          "urn:schemas-upnp-org:smgt:srecinfo http://www.upnp.org/schemas/ds/drecs-v1.xsd");

      serializer.startTag(nns, XMLSENSORRECORD);
      for (String field : fields) {

        serializer.startTag(nns, XMLFIELD);
        serializer.attribute(nns, XMLNAME, field);
        serializer.endTag(nns, XMLFIELD);
      }
      serializer.endTag(nns, XMLSENSORRECORD);
      serializer.endTag(ns, XMLSENSORRECORDINFO);
      serializer.endDocument();
      return writer.toString();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
예제 #19
0
  private void generatePublicXml(ResPackage pkg, Directory out, XmlSerializer serial)
      throws AndrolibException {
    try {
      OutputStream outStream = out.getFileOutput("values/public.xml");
      serial.setOutput(outStream, null);
      serial.startDocument(null, null);
      serial.startTag(null, "resources");

      for (ResResSpec spec : pkg.listResSpecs()) {
        serial.startTag(null, "public");
        serial.attribute(null, "type", spec.getType().getName());
        serial.attribute(null, "name", spec.getName());
        serial.attribute(null, "id", String.format("0x%08x", spec.getId().id));
        serial.endTag(null, "public");
      }

      serial.endTag(null, "resources");
      serial.endDocument();
      serial.flush();
      outStream.close();
    } catch (IOException ex) {
      throw new AndrolibException("Could not generate public.xml file", ex);
    } catch (DirectoryException ex) {
      throw new AndrolibException("Could not generate public.xml file", ex);
    }
  }
예제 #20
0
  public void onClick1(View v) {
    try {
      String filename = "file.txt";

      FileOutputStream fos;
      fos = openFileOutput(filename, MODE_PRIVATE);

      XmlSerializer serializer = Xml.newSerializer();
      serializer.setOutput(fos, "UTF-8");
      serializer.startDocument(null, Boolean.valueOf(true));
      serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

      serializer.startTag(null, "root");

      for (int j = 0; j < 3; j++) {

        serializer.startTag(null, "record");

        serializer.text(String.valueOf(j));

        serializer.endTag(null, "record");
      }
      serializer.endTag(null, "root");
      serializer.endDocument();

      serializer.flush();

      fos.close();

      // display file saved message
      Toast.makeText(getBaseContext(), "File xml saved successfully!", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public String WriteXmlString(List<Employee> employees) throws IOException {

    String Tag_employees = "employees";
    String Tag_employee = "employee";
    String Tag_id = "id";
    String Tag_name = "name";
    String Tag_department = "department";
    String Tag_type = "type";
    String Tag_email = "email";

    // order of Tags: employees , employee, id, name, department, email

    XmlSerializer xmlSerializer = Xml.newSerializer();
    StringWriter stringWriter = new StringWriter();

    xmlSerializer.setOutput(stringWriter);

    // start Document
    xmlSerializer.startDocument("UTF-8", true);
    // tag: employees
    xmlSerializer.startTag("", Tag_employees);

    for (int i = 0; i < employees.size(); i++) {

      // tag: employee
      xmlSerializer.startTag("", Tag_employee);

      // tag: id
      xmlSerializer.startTag("", Tag_id);
      xmlSerializer.text(Integer.toString(employees.get(i).getId()));
      xmlSerializer.endTag("", Tag_id);

      // tag: name
      xmlSerializer.startTag("", Tag_name);
      xmlSerializer.text(employees.get(i).getName());
      xmlSerializer.endTag("", Tag_name);

      // tag: department
      xmlSerializer.startTag("", Tag_department);
      xmlSerializer.text(employees.get(i).getDepartment());
      xmlSerializer.endTag("", Tag_department);

      // tag: type
      xmlSerializer.startTag("", Tag_type);
      xmlSerializer.text(employees.get(i).getType());
      xmlSerializer.endTag("", Tag_type);

      // tag: email
      xmlSerializer.startTag("", Tag_email);
      xmlSerializer.text(employees.get(i).getEmail());
      xmlSerializer.endTag("", Tag_email);

      xmlSerializer.endTag("", Tag_employee);
    }

    // end Document
    xmlSerializer.endDocument();

    return stringWriter.toString();
  }
예제 #22
0
  private String serialize(Element e, int intent) {

    try {

      XmlSerializer s = Xml.newSerializer();
      StringWriter sw = new StringWriter();

      s.setOutput(sw);
      s.startDocument("utf-8", null);

      String spaces = null;
      if (intent > 0) {
        char[] chars = new char[intent];
        Arrays.fill(chars, ' ');
        spaces = new String(chars);
      }

      serialize(root, s, 0, spaces);
      s.endDocument();

      return sw.toString();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return null;
  }
예제 #23
0
    @Override
    @SuppressWarnings("unchecked")
    public Void doInBackground(Object... args) {
      List<HistoricalRecord> historicalRecords = (List<HistoricalRecord>) args[0];
      String hostoryFileName = (String) args[1];

      FileOutputStream fos = null;

      try {
        fos = mContext.openFileOutput(hostoryFileName, Context.MODE_PRIVATE);
      } catch (FileNotFoundException fnfe) {
        Log.e(LOG_TAG, "Error writing historical recrod file: " + hostoryFileName, fnfe);
        return null;
      }

      XmlSerializer serializer = Xml.newSerializer();

      try {
        serializer.setOutput(fos, null);
        serializer.startDocument("UTF-8", true);
        serializer.startTag(null, TAG_HISTORICAL_RECORDS);

        final int recordCount = historicalRecords.size();
        for (int i = 0; i < recordCount; i++) {
          HistoricalRecord record = historicalRecords.remove(0);
          serializer.startTag(null, TAG_HISTORICAL_RECORD);
          serializer.attribute(null, ATTRIBUTE_ACTIVITY, record.activity.flattenToString());
          serializer.attribute(null, ATTRIBUTE_TIME, String.valueOf(record.time));
          serializer.attribute(null, ATTRIBUTE_WEIGHT, String.valueOf(record.weight));
          serializer.endTag(null, TAG_HISTORICAL_RECORD);
          if (DEBUG) {
            Log.i(LOG_TAG, "Wrote " + record.toString());
          }
        }

        serializer.endTag(null, TAG_HISTORICAL_RECORDS);
        serializer.endDocument();

        if (DEBUG) {
          Log.i(LOG_TAG, "Wrote " + recordCount + " historical records.");
        }
      } catch (IllegalArgumentException iae) {
        Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, iae);
      } catch (IllegalStateException ise) {
        Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ise);
      } catch (IOException ioe) {
        Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ioe);
      } finally {
        mCanReadHistoricalData = true;
        if (fos != null) {
          try {
            fos.close();
          } catch (IOException e) {
            /* ignore */
          }
        }
      }
      return null;
    }
예제 #24
0
  /**
   * * Crea una cadena XML lista para ser utilizada. El origen es una lista de tipo Registro.
   *
   * @param lista La lista de Registro a ser transformada. Permite que haya una mezcla de registros
   *     de acelerometro, GPS, etc.
   * @return Una cadena en formato XML representando la lista de registros. Null en caso de
   *     encontrarse un error
   */
  public static String crearXml(List<Registro> lista) {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Log.i("Cinvestav Utilerias CrearXml", "Intentando crear Xml de " + lista.size() + " elementos");
    try {
      serializer.setOutput(writer);

      serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
      serializer.startDocument("UTF-8", true);

      serializer.startTag("", "raiz");
      for (Registro registro : lista) {
        serializer.startTag("", "registro");

        // serializer.attribute("", "timestamp",
        // String.valueOf(registro.getTimestamp().getTime()));
        serializer.attribute("", "timestamp", sdf.format(registro.getTimestamp()));
        if (registro instanceof RegistroAcelerometro) {
          serializer.attribute("", "tipo", TIPO_ACELEROMETRO);
          serializer.startTag("", "ejeX");
          serializer.text(String.valueOf(((RegistroAcelerometro) registro).getEjeX()));
          serializer.endTag("", "ejeX");

          serializer.startTag("", "ejeY");
          serializer.text(String.valueOf(((RegistroAcelerometro) registro).getEjeY()));
          serializer.endTag("", "ejeY");

          serializer.startTag("", "ejeZ");
          serializer.text(String.valueOf(((RegistroAcelerometro) registro).getEjeZ()));
          serializer.endTag("", "ejeZ");
        } else if (registro instanceof RegistroGPS) {
          serializer.attribute("", "tipo", TIPO_GPS);
          serializer.startTag("", "latitud");
          serializer.text(String.valueOf(((RegistroGPS) registro).getLatitud()));
          serializer.endTag("", "latitud");

          serializer.startTag("", "longitud");
          serializer.text(String.valueOf(((RegistroGPS) registro).getLongitud()));
          serializer.endTag("", "longitud");

          serializer.startTag("", "precision");
          serializer.text(String.valueOf(((RegistroGPS) registro).getPrecision()));
          serializer.endTag("", "precision");
        }

        serializer.endTag("", "registro");
      }
      serializer.endTag("", "raiz");
      serializer.endDocument();
      Log.i("Cinvestav Utilerias crearXML", "La cadena XML ha sido creada");
      return writer.toString();

    } catch (IOException e) {
      Log.e("Cinvestav Utilerias crearXml", "No se pudo crear la cadena XML " + e.getMessage());
      return null;
    }
  }
예제 #25
0
 /**
  * Flatten a List into an output stream as XML. The list can later be read back with
  * readListXml().
  *
  * @param val The list to be flattened.
  * @param out Where to write the XML data.
  * @see #writeListXml(List, String, XmlSerializer)
  * @see #writeMapXml
  * @see #writeValueXml
  * @see #readListXml
  */
 public static final void writeListXml(List val, OutputStream out)
     throws XmlPullParserException, java.io.IOException {
   XmlSerializer serializer = Xml.newSerializer();
   serializer.setOutput(out, "utf-8");
   serializer.startDocument(null, true);
   serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
   writeListXml(val, null, serializer);
   serializer.endDocument();
 }
 private XmlSerializer newSerializer(Writer writer) {
   try {
     XmlPullParserFactory pf = XmlPullParserFactory.newInstance();
     XmlSerializer serializer = pf.newSerializer();
     serializer.setOutput(writer);
     return serializer;
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
  public static String createXMLDataStoreTableInfo(DataTableInfo datatable, boolean omitID) {

    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    if (datatable != null) {
      try {
        serializer.setOutput(writer);
        serializer.startDocument("UTF-8", false);
        final String nns = null; // no namespace
        final String ns = "urn:schemas-upnp-org:ds:dtinfo";

        serializer.setPrefix("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        serializer.setPrefix("", ns);
        serializer.startTag(ns, XMLDATATABLEINFO);
        serializer.attribute(
            "http://www.w3.org/2001/XMLSchema-instance",
            "schemaLocation",
            "urn:schemas-upnp-org:ds:dtinfo http://www.upnp.org/schemas/ds/dtinfo.xsd");

        if (omitID) {
          serializer.attribute(nns, XMLTABLEGUID, "");
          serializer.attribute(nns, XMLTABLEUPDATEID, "");
        } else {
          serializer.attribute(nns, XMLTABLEGUID, Integer.toString(datatable.getTableID()));
          serializer.attribute(nns, XMLTABLEUPDATEID, Integer.toString(datatable.getUpdateID()));
        }
        serializer.attribute(nns, XMLTABLEGRN, datatable.getURN());

        DataItemInfo[] di = datatable.getDataItemInfoList();
        if (di.length != 0) serializer.startTag(nns, XMLDATARECORD);
        for (int i = 0; i < di.length; i++) {
          serializer.startTag(nns, XMLFIELD);

          serializer.attribute(nns, XMLFNAME, di[i].getFieldName());
          serializer.attribute(nns, XMLFTYPE, di[i].getFieldType());
          serializer.attribute(nns, XMLFENCODING, di[i].getEncoding());
          // serializer.attribute(nns, XMLFREQUIRED, Boolean.toString((di[i].isRequired())));
          serializer.attribute(nns, XMLFREQUIRED, (di[i].isRequired()) ? "1" : "0");
          serializer.attribute(nns, XMLFNAMESPACE, di[i].getNamespace());
          // serializer.attribute(nns, XMLFTABLEPROP, Boolean.toString((di[i].isTableProp())));
          serializer.attribute(nns, XMLFTABLEPROP, (di[i].isTableProp()) ? "1" : "0");

          serializer.endTag(nns, XMLFIELD);
        }
        if (di.length != 0) serializer.endTag(nns, XMLDATARECORD);

        serializer.endTag(ns, XMLDATATABLEINFO);
        serializer.endDocument();
        return writer.toString();
      } catch (Exception e) {
        Log.e(TAG, "Error generating XML in createXMLDataStoreTableInfo: " + e);
      }
    }
    return "";
  }
예제 #28
0
  private void writeDeviceState(List<KMMDDeviceItem> deviceState) {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    try {
      serializer.setOutput(writer);
      serializer.startDocument("UTF-8", true);
      serializer.startTag("", "DeviceState");
      for (KMMDDeviceItem item : deviceState) {
        serializer.startTag("", "item");
        serializer.startTag("", "type");
        serializer.text(item.getType());
        serializer.endTag("", "type");
        serializer.startTag("", "name");
        serializer.text(item.getName());
        serializer.endTag("", "name");
        serializer.startTag("", "path");
        serializer.text(item.getPath());
        serializer.endTag("", "path");
        serializer.startTag("", "dirtyservices");
        serializer.attribute(
            "", "Dropbox", String.valueOf(item.getIsDirty(KMMDDropboxService.CLOUD_DROPBOX)));
        serializer.attribute(
            "",
            "GoogleDrive",
            String.valueOf(item.getIsDirty(KMMDDropboxService.CLOUD_GOOGLEDRIVE)));
        serializer.attribute(
            "", "UbutntoOne", String.valueOf(item.getIsDirty(KMMDDropboxService.CLOUD_UBUNTUONE)));
        serializer.endTag("", "dirtyservices");
        serializer.startTag("", "revcodes");
        serializer.attribute("", "Dropbox", item.getRevCode(KMMDDropboxService.CLOUD_DROPBOX));
        serializer.attribute(
            "", "GoogleDrive", item.getRevCode(KMMDDropboxService.CLOUD_GOOGLEDRIVE));
        serializer.attribute("", "UbuntuOne", item.getRevCode(KMMDDropboxService.CLOUD_UBUNTUONE));
        serializer.endTag("", "revcodes");
        serializer.endTag("", "item");
      }
      serializer.endTag("", "DeviceState");
      serializer.endDocument();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    // Attempt to write the state file to the private storage area.
    String FILENAME = DEVICE_STATE_FILE;
    try {
      FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
      fos.write(writer.toString().getBytes());
      fos.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #29
0
 /**
  * Note : {@link #close()} must be called from the caller side.
  *
  * <p>The method will close the XML document by close tags.
  */
 public MozcTestListener(Writer writer, String suitesName) {
   serializer = Xml.newSerializer();
   try {
     serializer.setOutput(writer);
     serializer.startDocument("UTF-8", true);
     serializer.startTag(NS_DEFAULT, TAG_TESTSUITES);
     serializer.attribute(NS_DEFAULT, ATTR_NAME, suitesName);
   } catch (IOException e) {
     MozcLog.e(e.getMessage(), e);
   }
 }
예제 #30
0
 protected String readElement(boolean includeOuterTag)
     throws XmlParseException, XmlPullParserException, IOException {
   XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
   XmlSerializer out = factory.newSerializer();
   StringWriter sw = new StringWriter();
   out.setOutput(sw);
   // out.startDocument("UTF-8", true);
   readElement(out, includeOuterTag);
   return sw.toString();
   // IOUtils.copy(tpis, new OutputStreamWriter(System.out), "UTF-8");
 }