Esempio n. 1
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;
	}
    @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;
    }
Esempio n. 3
0
 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);
   }
 }
  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);
    }
  }
  private void writeNode(Node n, EntityInfo i, XmlSerializer ser, long changeSetId, String user)
      throws IllegalArgumentException, IllegalStateException, IOException {
    ser.startTag(null, "node"); // $NON-NLS-1$
    ser.attribute(null, "id", n.getId() + ""); // $NON-NLS-1$ //$NON-NLS-2$
    ser.attribute(null, "lat", n.getLatitude() + ""); // $NON-NLS-1$ //$NON-NLS-2$
    ser.attribute(null, "lon", n.getLongitude() + ""); // $NON-NLS-1$ //$NON-NLS-2$
    if (i != null) {
      // ser.attribute(null, "timestamp", i.getETimestamp());
      // ser.attribute(null, "uid", i.getUid());
      // ser.attribute(null, "user", i.getUser());
      ser.attribute(null, "visible", i.getVisible()); // $NON-NLS-1$
      ser.attribute(null, "version", i.getVersion()); // $NON-NLS-1$
    }
    ser.attribute(null, "changeset", changeSetId + ""); // $NON-NLS-1$ //$NON-NLS-2$

    for (String k : n.getTagKeySet()) {
      String val = n.getTag(k);
      if (val.length() == 0) continue;
      ser.startTag(null, "tag"); // $NON-NLS-1$
      ser.attribute(null, "k", k); // $NON-NLS-1$
      ser.attribute(null, "v", val); // $NON-NLS-1$
      ser.endTag(null, "tag"); // $NON-NLS-1$
    }
    ser.endTag(null, "node"); // $NON-NLS-1$
  }
 private void writeContent(XmlSerializer sz, OsmPoint[] points, Action a)
     throws IllegalArgumentException, IllegalStateException, IOException {
   for (OsmPoint point : points) {
     if (point.getGroup() == OsmPoint.Group.POI) {
       OpenstreetmapPoint p = (OpenstreetmapPoint) point;
       if (p.getAction() == a) {
         sz.startTag("", "node");
         sz.attribute("", "lat", p.getLatitude() + "");
         sz.attribute("", "lon", p.getLongitude() + "");
         sz.attribute("", "id", p.getId() + "");
         for (String tag : p.getEntity().getTagKeySet()) {
           String val = p.getEntity().getTag(tag);
           sz.startTag("", "tag");
           sz.attribute("", "k", tag);
           sz.attribute("", "v", val);
           sz.endTag("", "tag");
         }
         sz.endTag("", "node");
       }
     } else if (point.getGroup() == OsmPoint.Group.BUG) {
       OsmNotesPoint p = (OsmNotesPoint) point;
       if (p.getAction() == a) {
         sz.startTag("", "note");
         sz.attribute("", "lat", p.getLatitude() + "");
         sz.attribute("", "lon", p.getLongitude() + "");
         sz.attribute("", "id", p.getId() + "");
         sz.startTag("", "comment");
         sz.attribute("", "text", p.getText() + "");
         sz.endTag("", "comment");
         sz.endTag("", "note");
       }
     }
   }
 }
  @Override
  public void requestBodyToXml(ProtocolData body, XmlSerializer serializer)
      throws IllegalArgumentException, IllegalStateException, IOException {
    // TODO Auto-generated method stub
    if (body.mChildren != null && body.mChildren.size() > 0) {
      Set<String> keys = body.mChildren.keySet();
      for (String key : keys) {
        List<ProtocolData> rs = body.mChildren.get(key);
        for (ProtocolData data : rs) {
          // 密钥
          if (data.mKey.equals("authorid")) {
            serializer.startTag("", "authorid");
            serializer.text(data.mValue.trim());
            serializer.endTag("", "authorid");

          } else if (data.mKey.equals("paytype")) {
            serializer.startTag("", "paytype");
            serializer.text(data.mValue.trim());
            serializer.endTag("", "paytype");

          } else if (data.mKey.equals("msgstart")) {
            serializer.startTag("", "msgstart");
            serializer.text(data.mValue.trim());
            serializer.endTag("", "msgstart");

          } else if (data.mKey.equals("msgdisplay")) {
            serializer.startTag("", "msgdisplay");
            serializer.text(data.mValue.trim());
            serializer.endTag("", "msgdisplay");
          }
        }
      }
    }
  }
Esempio n. 8
0
  /**
   * Flatten an int[] into an XmlSerializer. The list can later be read back with
   * readThisIntArrayXml().
   *
   * @param val The int array to be flattened.
   * @param name Name attribute to include with this array's tag, or null for none.
   * @param out XmlSerializer to write the array into.
   * @see #writeMapXml
   * @see #writeValueXml
   * @see #readThisIntArrayXml
   */
  public static final void writeIntArrayXml(int[] val, String name, XmlSerializer out)
      throws XmlPullParserException, java.io.IOException {

    if (val == null) {
      out.startTag(null, "null");
      out.endTag(null, "null");
      return;
    }

    out.startTag(null, "int-array");
    if (name != null) {
      out.attribute(null, "name", name);
    }

    final int N = val.length;
    out.attribute(null, "num", Integer.toString(N));

    for (int i = 0; i < N; i++) {
      out.startTag(null, "item");
      out.attribute(null, "value", Integer.toString(val[i]));
      out.endTag(null, "item");
    }

    out.endTag(null, "int-array");
  }
Esempio n. 9
0
 @Override
 public void serializeContent(XmlSerializer serializer) throws IOException {
   if (isEmpty()) return;
   SerializerUtils.addTextTag(serializer, VCardProperty.FN.toString(), getFormattedName());
   serializer.startTag(null, N_NAME);
   for (Entry<NameProperty, String> entry : name.entrySet())
     SerializerUtils.addTextTag(serializer, entry.getKey().toString(), entry.getValue());
   serializer.endTag(null, N_NAME);
   for (Entry<VCardProperty, String> entry : properties.entrySet())
     if (entry.getKey() != VCardProperty.FN)
       SerializerUtils.addTextTag(serializer, entry.getKey().toString(), entry.getValue());
   for (Photo photo : photos) photo.serialize(serializer);
   for (Address address : addresses) address.serialize(serializer);
   for (Label label : labels) label.serialize(serializer);
   for (Telephone telephone : telephones) telephone.serialize(serializer);
   for (Email email : emails) email.serialize(serializer);
   for (Logo logo : logos) logo.serialize(serializer);
   for (Sound sound : sounds) sound.serialize(serializer);
   for (Geo geo : geos) geo.serialize(serializer);
   for (Organization organization : organizations) organization.serialize(serializer);
   if (!categories.isEmpty()) {
     serializer.startTag(null, CATEGORIES_NAME);
     for (String keyword : categories)
       SerializerUtils.addTextTag(serializer, KEYWORD_NAME, keyword);
     serializer.endTag(null, CATEGORIES_NAME);
   }
   if (classification != null)
     SerializerUtils.addTextTag(serializer, CLASS_NAME, classification.toString());
   for (Key key : keys) key.serialize(serializer);
 }
Esempio n. 10
0
  /**
   * Flatten a byte[] into an XmlSerializer. The list can later be read back with
   * readThisByteArrayXml().
   *
   * @param val The byte array to be flattened.
   * @param name Name attribute to include with this array's tag, or null for none.
   * @param out XmlSerializer to write the array into.
   * @see #writeMapXml
   * @see #writeValueXml
   */
  public static final void writeByteArrayXml(byte[] val, String name, XmlSerializer out)
      throws XmlPullParserException, java.io.IOException {

    if (val == null) {
      out.startTag(null, "null");
      out.endTag(null, "null");
      return;
    }

    out.startTag(null, "byte-array");
    if (name != null) {
      out.attribute(null, "name", name);
    }

    final int N = val.length;
    out.attribute(null, "num", Integer.toString(N));

    StringBuilder sb = new StringBuilder(val.length * 2);
    for (int i = 0; i < N; i++) {
      int b = val[i];
      int h = b >> 4;
      sb.append(h >= 10 ? ('a' + h - 10) : ('0' + h));
      h = b & 0xff;
      sb.append(h >= 10 ? ('a' + h - 10) : ('0' + h));
    }

    out.text(sb.toString());

    out.endTag(null, "byte-array");
  }
Esempio n. 11
0
  /**
   * Flatten a String[] into an XmlSerializer. The list can later be read back with
   * readThisStringArrayXml().
   *
   * @param val The long array to be flattened.
   * @param name Name attribute to include with this array's tag, or null for none.
   * @param out XmlSerializer to write the array into.
   * @see #writeMapXml
   * @see #writeValueXml
   * @see #readThisIntArrayXml
   */
  public static void writeStringArrayXml(String[] val, String name, XmlSerializer out)
      throws java.io.IOException {

    if (val == null) {
      out.startTag(null, "null");
      out.endTag(null, "null");
      return;
    }

    out.startTag(null, "string-array");
    if (name != null) {
      out.attribute(null, "name", name);
    }

    final int N = val.length;
    out.attribute(null, "num", Integer.toString(N));

    for (String aVal : val) {
      out.startTag(null, "item");
      out.attribute(null, "value", aVal);
      out.endTag(null, "item");
    }

    out.endTag(null, "string-array");
  }
Esempio n. 12
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();
    }
  }
  /*
   * 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");
    }
  }
  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");
  }
Esempio n. 15
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");
  }
  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);
    }
  }
Esempio n. 17
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);
    }
  }
  private void exportSlots(
      XmlSerializer xmlSerializer,
      List<String> slotKey,
      List<String> slotType,
      List<String> slotValue)
      throws IOException {
    if (slotKey == null
        || slotType == null
        || slotValue == null
        || slotKey.size() == 0
        || slotType.size() != slotKey.size()
        || slotValue.size() != slotKey.size()) {
      return;
    }

    for (int i = 0; i < slotKey.size(); i++) {
      xmlSerializer.startTag(null, GncXmlHelper.TAG_SLOT);
      xmlSerializer.startTag(null, GncXmlHelper.TAG_SLOT_KEY);
      xmlSerializer.text(slotKey.get(i));
      xmlSerializer.endTag(null, GncXmlHelper.TAG_SLOT_KEY);
      xmlSerializer.startTag(null, GncXmlHelper.TAG_SLOT_VALUE);
      xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_TYPE, slotType.get(i));
      xmlSerializer.text(slotValue.get(i));
      xmlSerializer.endTag(null, GncXmlHelper.TAG_SLOT_VALUE);
      xmlSerializer.endTag(null, GncXmlHelper.TAG_SLOT);
    }
  }
    @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;
    }
 /**
  * Serializes a date as a {@code tag} which has a nested {@link GncXmlHelper#TAG_GDATE} which has
  * the date as a text element formatted using {@link GncXmlHelper#DATE_FORMATTER}
  *
  * @param xmlSerializer XML serializer
  * @param tag Enclosing tag
  * @param timeMillis Date to be formatted and output
  * @throws IOException
  */
 private void serializeDate(XmlSerializer xmlSerializer, String tag, long timeMillis)
     throws IOException {
   xmlSerializer.startTag(null, tag);
   xmlSerializer.startTag(null, GncXmlHelper.TAG_GDATE);
   xmlSerializer.text(GncXmlHelper.DATE_FORMATTER.format(timeMillis));
   xmlSerializer.endTag(null, GncXmlHelper.TAG_GDATE);
   xmlSerializer.endTag(null, tag);
 }
Esempio n. 21
0
 /**
  * SYNC transaction xml
  *
  * @param xmlSerializer
  * @param syncTransaction
  */
 public static void toXmlWriter(XmlSerializer xmlSerializer, SyncTransaction syncTransaction)
     throws IOException, EwpException {
   // Start Root tag
   xmlSerializer.startTag("", "SyncTransaction");
   xmlSerializer.startTag("", "SyncTransactionId");
   xmlSerializer.text(syncTransaction.syncTransactionId);
   xmlSerializer.endTag("", "SyncTransactionId");
   SyncOp.listToXmlWriter(syncTransaction.syncOpList, xmlSerializer);
   xmlSerializer.endTag("", "SyncTransaction");
 }
  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 "";
  }
 protected void serializeParams(Object... params)
     throws IllegalArgumentException, IllegalStateException, IOException {
   if (params != null && params.length != 0) {
     // set method params
     serializer.startTag(null, Tag.PARAMS);
     for (Object param : params) {
       serializer.startTag(null, Tag.PARAM).startTag(null, IXMLRPCSerializer.TAG_VALUE);
       iXMLRPCSerializer.serialize(serializer, param);
       serializer.endTag(null, IXMLRPCSerializer.TAG_VALUE).endTag(null, Tag.PARAM);
     }
     serializer.endTag(null, Tag.PARAMS);
   }
 }
  void writeLPr() {
    if (mVendorSettingsFilename.exists()) {
      if (!mVendorBackupSettingsFilename.exists()) {
        if (!mVendorSettingsFilename.renameTo(mVendorBackupSettingsFilename)) {
          Slog.e(
              PackageManagerService.TAG,
              "Unable to backup package manager vendor settings, "
                  + " current changes will be lost at reboot");
          return;
        }
      } else {
        mVendorSettingsFilename.delete();
        Slog.w(PackageManagerService.TAG, "Preserving older vendor settings backup");
      }
    }
    try {
      FileOutputStream fstr = new FileOutputStream(mVendorSettingsFilename);
      XmlSerializer serializer = new FastXmlSerializer();
      // XmlSerializer serializer = Xml.newSerializer()
      BufferedOutputStream str = new BufferedOutputStream(fstr);
      serializer.setOutput(str, "utf-8");
      serializer.startDocument(null, true);
      serializer.startTag(null, TAG_ROOT);

      for (VendorPackageSetting ps : mVendorPackages.values()) {
        serializer.startTag(null, TAG_PACKAGE);
        serializer.attribute(null, ATTR_PACKAGE_NAME, ps.getPackageName());
        serializer.attribute(
            null, ATTR_INSTALL_STATUS, ps.getIntallStatus() ? VAL_INSTALLED : VAL_UNINSTALLED);
        serializer.endTag(null, TAG_PACKAGE);
      }
      serializer.endTag(null, TAG_ROOT);
      serializer.endDocument();
      str.flush();
      FileUtils.sync(fstr);
      str.close();

      mVendorBackupSettingsFilename.delete();
      FileUtils.setPermissions(
          mVendorSettingsFilename.toString(),
          FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP | FileUtils.S_IWGRP,
          -1,
          -1);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 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);
   }
 }
 private void exportCommodity(XmlSerializer xmlSerializer, List<Currency> currencies)
     throws IOException {
   for (Currency currency : currencies) {
     xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY);
     xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_VERSION, "2.0.0");
     xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
     xmlSerializer.text("ISO4217");
     xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
     xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_ID);
     xmlSerializer.text(currency.getCurrencyCode());
     xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_ID);
     xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY);
   }
 }
Esempio n. 27
0
  @Override
  public void serializeToResValuesXml(XmlSerializer serializer, ResResource res)
      throws IOException, AndrolibException {
    serializer.startTag(null, "style");
    serializer.attribute(null, "name", res.getResSpec().getName());
    if (!mParent.isNull() && !mParent.referentIsNull()) {
      serializer.attribute(null, "parent", mParent.encodeAsResXmlAttr());
    } else if (res.getResSpec().getName().indexOf('.') != -1) {
      serializer.attribute(null, "parent", "");
    }
    for (int i = 0; i < mItems.length; i++) {
      ResResSpec spec = mItems[i].m1.getReferent();

      if (spec == null) {
        continue;
      }

      String name = null;
      String value = null;

      String resource = spec.getDefaultResource().getValue().toString();
      // hacky-fix remove bad ReferenceVars
      if (resource.contains("ResReferenceValue@")) {
        continue;
      } else if (resource.contains("ResStringValue@")
          || resource.contains("ResStyleValue@")
          || resource.contains("ResBoolValue@")) {
        name = "@" + spec.getFullName(res.getResSpec().getPackage(), false);
      } else {
        ResAttr attr = (ResAttr) spec.getDefaultResource().getValue();
        value = attr.convertToResXmlFormat(mItems[i].m2);
        name = spec.getFullName(res.getResSpec().getPackage(), true);
      }

      if (value == null) {
        value = mItems[i].m2.encodeAsResXmlValue();
      }

      if (value == null) {
        continue;
      }

      serializer.startTag(null, "item");
      serializer.attribute(null, "name", name);
      serializer.text(value);
      serializer.endTag(null, "item");
    }
    serializer.endTag(null, "style");
  }
Esempio n. 28
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;
    }
  }
Esempio n. 29
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();
  }
    private void tagRepo() throws IOException, LocalRepoKeyStore.InitException {

      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

      // max age is an EditTextPreference, which is always a String
      int repoMaxAge =
          Float.valueOf(prefs.getString("max_repo_age_days", DEFAULT_REPO_MAX_AGE_DAYS)).intValue();

      serializer.startTag("", "repo");

      serializer.attribute("", "icon", "blah.png");
      serializer.attribute("", "maxage", String.valueOf(repoMaxAge));
      serializer.attribute(
          "", "name", Preferences.get().getLocalRepoName() + " on " + FDroidApp.ipAddressString);
      serializer.attribute(
          "", "pubkey", Hasher.hex(LocalRepoKeyStore.get(context).getCertificate()));
      long timestamp = System.currentTimeMillis() / 1000L;
      serializer.attribute("", "timestamp", String.valueOf(timestamp));

      tag(
          "description",
          "A local FDroid repo generated from apps installed on "
              + Preferences.get().getLocalRepoName());

      serializer.endTag("", "repo");
    }