Java Code Examples for org.xmlpull.v1.XmlSerializer#flush()

The following examples show how to use org.xmlpull.v1.XmlSerializer#flush() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PersistentDataStore.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void save() {
    final FileOutputStream os;
    try {
        os = mAtomicFile.startWrite();
        boolean success = false;
        try {
            XmlSerializer serializer = new FastXmlSerializer();
            serializer.setOutput(new BufferedOutputStream(os), StandardCharsets.UTF_8.name());
            saveToXml(serializer);
            serializer.flush();
            success = true;
        } finally {
            if (success) {
                mAtomicFile.finishWrite(os);
                broadcastChangesIfNeeded();
            } else {
                mAtomicFile.failWrite(os);
            }
        }
    } catch (IOException ex) {
        Slog.w(TAG, "Failed to save tv input manager persistent store data.", ex);
    }
}
 
Example 2
Source File: SliceManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] getBackupPayload(int user) {
    if (Binder.getCallingUid() != SYSTEM_UID) {
        throw new SecurityException("Caller must be system");
    }
    //TODO: http://b/22388012
    if (user != UserHandle.USER_SYSTEM) {
        Slog.w(TAG, "getBackupPayload: cannot backup policy for user " + user);
        return null;
    }
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        XmlSerializer out = XmlPullParserFactory.newInstance().newSerializer();
        out.setOutput(baos, Encoding.UTF_8.name());

        mPermissions.writeBackup(out);

        out.flush();
        return baos.toByteArray();
    } catch (IOException | XmlPullParserException e) {
        Slog.w(TAG, "getBackupPayload: error writing payload for user " + user, e);
    }
    return null;
}
 
Example 3
Source File: TaskPersister.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private StringWriter saveToXml(TaskRecord task) throws IOException, XmlPullParserException {
    if (DEBUG) Slog.d(TAG, "saveToXml: task=" + task);
    final XmlSerializer xmlSerializer = new FastXmlSerializer();
    StringWriter stringWriter = new StringWriter();
    xmlSerializer.setOutput(stringWriter);

    if (DEBUG) xmlSerializer.setFeature(
            "http://xmlpull.org/v1/doc/features.html#indent-output", true);

    // save task
    xmlSerializer.startDocument(null, true);

    xmlSerializer.startTag(null, TAG_TASK);
    task.saveToXml(xmlSerializer);
    xmlSerializer.endTag(null, TAG_TASK);

    xmlSerializer.endDocument();
    xmlSerializer.flush();

    return stringWriter;
}
 
Example 4
Source File: ExtendedSoapSerializationEnvelope.java    From ETSMobile-Android2 with Apache License 2.0 6 votes vote down vote up
public SoapObject GetSoapObject(Element detailElement) {
	try {
		XmlSerializer xmlSerializer = XmlPullParserFactory.newInstance().newSerializer();
		StringWriter writer = new StringWriter();
		xmlSerializer.setOutput(writer);
		detailElement.write(xmlSerializer);
		xmlSerializer.flush();

		XmlPullParser xpp = new KXmlParser();
		xpp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);

		xpp.setInput(new StringReader(writer.toString()));
		xpp.nextTag();
		SoapObject soapObj = new SoapObject(detailElement.getNamespace(), detailElement.getName());
		readSerializable(xpp, soapObj);
		return soapObj;
	} catch (Exception ex) {
		ex.printStackTrace();
	}
	return null;
}
 
Example 5
Source File: ApplicationListParser.java    From Stringlate with MIT License 5 votes vote down vote up
static boolean parseToXml(ApplicationList applications, OutputStream out) {
    XmlSerializer serializer = Xml.newSerializer();
    try {
        serializer.setOutput(out, "UTF-8");
        serializer.startTag(ns, "fdroid");

        for (ApplicationDetails app : applications) {
            serializer.startTag(ns, "application");

            writeTag(serializer, ID, app.getPackageName());
            writeTag(serializer, LAST_UPDATED, app.getLastUpdatedDateString());
            writeTag(serializer, NAME, app.getProjectName());
            writeTag(serializer, DESCRIPTION, app.getDescription());
            writeTag(serializer, ICON_URL, app.getIconUrl());
            writeTag(serializer, SOURCE_URL, app.getSourceCodeUrl());
            writeTag(serializer, WEB, app.getProjectWebUrl());
            writeTag(serializer, MAIL, app.getProjectMail());

            serializer.endTag(ns, "application");
        }
        serializer.endTag(ns, "fdroid");
        serializer.flush();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 6
Source File: PackageStatusStorage.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@GuardedBy("this")
private void writePackageStatusLocked(Integer status, int optimisticLockId,
        PackageVersions packageVersions) throws IOException {
    if ((status == null) != (packageVersions == null)) {
        throw new IllegalArgumentException(
                "Provide both status and packageVersions, or neither.");
    }

    FileOutputStream fos = null;
    try {
        fos = mPackageStatusFile.startWrite();
        XmlSerializer serializer = new FastXmlSerializer();
        serializer.setOutput(fos, StandardCharsets.UTF_8.name());
        serializer.startDocument(null /* encoding */, true /* standalone */);
        final String namespace = null;
        serializer.startTag(namespace, TAG_PACKAGE_STATUS);
        String statusAttributeValue = status == null ? "" : Integer.toString(status);
        serializer.attribute(namespace, ATTRIBUTE_CHECK_STATUS, statusAttributeValue);
        serializer.attribute(namespace, ATTRIBUTE_OPTIMISTIC_LOCK_ID,
                Integer.toString(optimisticLockId));
        long updateAppVersion = status == null
                ? UNKNOWN_PACKAGE_VERSION : packageVersions.mUpdateAppVersion;
        serializer.attribute(namespace, ATTRIBUTE_UPDATE_APP_VERSION,
                Long.toString(updateAppVersion));
        long dataAppVersion = status == null
                ? UNKNOWN_PACKAGE_VERSION : packageVersions.mDataAppVersion;
        serializer.attribute(namespace, ATTRIBUTE_DATA_APP_VERSION,
                Long.toString(dataAppVersion));
        serializer.endTag(namespace, TAG_PACKAGE_STATUS);
        serializer.endDocument();
        serializer.flush();
        mPackageStatusFile.finishWrite(fos);
    } catch (IOException e) {
        if (fos != null) {
            mPackageStatusFile.failWrite(fos);
        }
        throw e;
    }

}
 
Example 7
Source File: XulDataNode.java    From starcor.xul with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
	try {
		XmlSerializer writer = XmlPullParserFactory.newInstance().newSerializer();
		writer.setOutput(out, "utf-8");
		writer.startDocument("utf-8", true);
		dumpXulDataNode(this, writer);
		writer.endDocument();
		writer.flush();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 8
Source File: ActivityDns.java    From tracker-control-android with GNU General Public License v3.0 5 votes vote down vote up
private void xmlExport(OutputStream out) throws 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);
    serializer.startTag(null, "netguard");

    DateFormat df = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss Z", Locale.US); // RFC 822

    try (Cursor cursor = DatabaseHelper.getInstance(this).getDns()) {
        int colTime = cursor.getColumnIndex("time");
        int colQName = cursor.getColumnIndex("qname");
        int colAName = cursor.getColumnIndex("aname");
        int colResource = cursor.getColumnIndex("resource");
        int colTTL = cursor.getColumnIndex("ttl");
        while (cursor.moveToNext()) {
            long time = cursor.getLong(colTime);
            String qname = cursor.getString(colQName);
            String aname = cursor.getString(colAName);
            String resource = cursor.getString(colResource);
            int ttl = cursor.getInt(colTTL);

            serializer.startTag(null, "dns");
            serializer.attribute(null, "time", df.format(time));
            serializer.attribute(null, "qname", qname);
            serializer.attribute(null, "aname", aname);
            serializer.attribute(null, "resource", resource);
            serializer.attribute(null, "ttl", Integer.toString(ttl));
            serializer.endTag(null, "dns");
        }
    }

    serializer.endTag(null, "netguard");
    serializer.endDocument();
    serializer.flush();
}
 
Example 9
Source File: ConfigurationFile.java    From ImapNote2 with GNU General Public License v3.0 5 votes vote down vote up
public void SaveConfigurationToXML() throws IllegalArgumentException, IllegalStateException, IOException{
    FileOutputStream configurationFile = this.applicationContext.openFileOutput("ImapNotes2.conf", Context.MODE_PRIVATE);
    XmlSerializer serializer = Xml.newSerializer();
    serializer.setOutput(configurationFile, "UTF-8");
    serializer.startDocument(null, Boolean.valueOf(true)); 
    serializer.startTag(null, "Configuration"); 
    serializer.startTag(null, "username");
    serializer.text(this.username);
    serializer.endTag(null, "username");
    serializer.startTag(null, "password");
    serializer.text(this.password);
    serializer.endTag(null, "password");
    serializer.startTag(null, "server");
    serializer.text(this.server);
    serializer.endTag(null, "server");
    serializer.startTag(null, "portnum");
    serializer.text(this.portnum);
    serializer.endTag(null, "portnum");
    serializer.startTag(null, "security");
    serializer.text(this.security);
    serializer.endTag(null, "security");
    serializer.startTag(null,"imapfolder");
    serializer.text(this.imapfolder);
    serializer.endTag(null, "imapfolder");
    serializer.startTag(null, "usesticky");
    serializer.text(this.usesticky);
    serializer.endTag(null, "usesticky");
    serializer.endTag(null, "Configuration"); 
    serializer.endDocument();
    serializer.flush();
    configurationFile.close();
}
 
Example 10
Source File: ActivityDns.java    From NetGuard with GNU General Public License v3.0 5 votes vote down vote up
private void xmlExport(OutputStream out) throws 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);
    serializer.startTag(null, "netguard");

    DateFormat df = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss Z", Locale.US); // RFC 822

    try (Cursor cursor = DatabaseHelper.getInstance(this).getDns()) {
        int colTime = cursor.getColumnIndex("time");
        int colQName = cursor.getColumnIndex("qname");
        int colAName = cursor.getColumnIndex("aname");
        int colResource = cursor.getColumnIndex("resource");
        int colTTL = cursor.getColumnIndex("ttl");
        while (cursor.moveToNext()) {
            long time = cursor.getLong(colTime);
            String qname = cursor.getString(colQName);
            String aname = cursor.getString(colAName);
            String resource = cursor.getString(colResource);
            int ttl = cursor.getInt(colTTL);

            serializer.startTag(null, "dns");
            serializer.attribute(null, "time", df.format(time));
            serializer.attribute(null, "qname", qname);
            serializer.attribute(null, "aname", aname);
            serializer.attribute(null, "resource", resource);
            serializer.attribute(null, "ttl", Integer.toString(ttl));
            serializer.endTag(null, "dns");
        }
    }

    serializer.endTag(null, "netguard");
    serializer.endDocument();
    serializer.flush();
}
 
Example 11
Source File: XmlMapsGDataSerializer.java    From mytracks with Apache License 2.0 4 votes vote down vote up
@Override
public void serialize(OutputStream out, int format)
    throws IOException, ParseException {
  XmlSerializer serializer = null;
  try {
    serializer = factory.createSerializer();
  } catch (XmlPullParserException e) {
    throw new ParseException("Unable to create XmlSerializer.", e);
  }

  ByteArrayOutputStream printStream;

  if (MapsClient.LOG_COMMUNICATION) {
    printStream = new ByteArrayOutputStream();

    serializer.setOutput(printStream, "UTF-8");
  } else {
    serializer.setOutput(out, "UTF-8");
  }

  serializer.startDocument("UTF-8", Boolean.FALSE);

  declareEntryNamespaces(serializer);
  serializer.startTag(XmlGDataParser.NAMESPACE_ATOM_URI, "entry");

  if (MapsClient.LOG_COMMUNICATION) {
    stream = printStream;
  } else {
    stream = out;
  }
  serializeEntryContents(serializer, format);

  serializer.endTag(XmlGDataParser.NAMESPACE_ATOM_URI, "entry");
  serializer.endDocument();
  serializer.flush();

  if (MapsClient.LOG_COMMUNICATION) {
    Log.d("Request", printStream.toString());
    out.write(printStream.toByteArray());
    stream = out;
  }
}
 
Example 12
Source File: XulDebugMonitor.java    From starcor.xul with GNU Lesser General Public License v3.0 4 votes vote down vote up
public synchronized boolean dumpPageList(final XulHttpServer.XulHttpServerRequest request, final XulHttpServer.XulHttpServerResponse response) {
	XmlSerializer xmlWriter = obtainXmlSerializer(response.getBodyStream());
	if (xmlWriter == null) {
		return false;
	}

	try {
		xmlWriter.startDocument("utf-8", Boolean.TRUE);
		xmlWriter.startTag(null, "pages");
		for (Map.Entry<Integer, PageInfo> page : _pagesById.entrySet()) {
			PageInfo value = page.getValue();
			Object pageObj = value.page.get();
			if (pageObj == null) {
				continue;
			}

			xmlWriter.startTag(null, "page");
			xmlWriter.attribute(null, "id", Integer.toString(value.id));

			XulDebugAdapter.writePageSpecifiedAttribute(pageObj, xmlWriter);

			xmlWriter.attribute(null, "status", value.status);


			if (value.firstResumedTime >= value.createTime) {
				xmlWriter.attribute(null, "resumeTime", Long.toString(value.firstResumedTime - value.createTime));
			}

			if (value.renderIsReadyTime >= value.createTime) {
				xmlWriter.attribute(null, "readyTime", Long.toString(value.renderIsReadyTime - value.createTime));
			}

			if (value.refreshCount > 0) {
				xmlWriter.attribute(null, "drawing",
					String.format(
						"frames:%d, avg:%.2f, min:%.2f, max:%.2f",
						value.refreshCount,
						(((double) value.totalDrawingDuration) / value.refreshCount / 1000.0),
						((double) value.minDrawingDuration / 1000.0),
						((double) value.maxDrawingDuration / 1000.0)
					)
				);
			}
			xmlWriter.endTag(null, "page");
		}
		xmlWriter.endTag(null, "pages");
		xmlWriter.endDocument();
		xmlWriter.flush();
		return true;
	} catch (IOException e) {
		XulLog.e(TAG, e);
	}
	return false;
}
 
Example 13
Source File: KmlFiles.java    From Androzic with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Saves track to file.
 * 
 * @param file valid <code>File</code>
 * @param track <code>Track</code> object containing the list of track points to save
 * @throws IOException
 */
public static void saveTrackToFile(final File file, final Track track) throws IOException
{
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
	XmlSerializer serializer = Xml.newSerializer();
	serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
	BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false)));
	serializer.setOutput(writer);
	serializer.startDocument("UTF-8", null);
	serializer.setPrefix("", KML_NAMESPACE);
	serializer.startTag(KML_NAMESPACE, KmlParser.KML);
	serializer.startTag(KML_NAMESPACE, KmlParser.DOCUMENT);
	serializer.startTag(KML_NAMESPACE, KmlParser.STYLE);
	serializer.attribute("", KmlParser.ID, "trackStyle");
	serializer.startTag(KML_NAMESPACE, KmlParser.LINESTYLE);
	serializer.startTag(KML_NAMESPACE, KmlParser.COLOR);
	serializer.text(String.format("%08X", KmlParser.reverseColor(track.color)));
	serializer.endTag(KML_NAMESPACE, KmlParser.COLOR);
	serializer.startTag(KML_NAMESPACE, KmlParser.WIDTH);
	serializer.text(String.valueOf(track.width));
	serializer.endTag(KML_NAMESPACE, KmlParser.WIDTH);
	serializer.endTag(KML_NAMESPACE, KmlParser.LINESTYLE);
	serializer.endTag(KML_NAMESPACE, KmlParser.STYLE);
	serializer.startTag(KML_NAMESPACE, KmlParser.FOLDER);
	serializer.startTag(KML_NAMESPACE, KmlParser.NAME);
	serializer.text(track.name);
	serializer.endTag(KML_NAMESPACE, KmlParser.NAME);
	serializer.startTag(KML_NAMESPACE, KmlParser.OPEN);
	serializer.text("0");
	serializer.endTag(KML_NAMESPACE, KmlParser.OPEN);
	serializer.startTag(KML_NAMESPACE, KmlParser.TIMESPAN);
	serializer.startTag(KML_NAMESPACE, KmlParser.BEGIN);
	serializer.text(sdf.format(new Date(track.getPoint(0).time)));
	serializer.endTag(KML_NAMESPACE, KmlParser.BEGIN);
	serializer.startTag(KML_NAMESPACE, KmlParser.END);
	serializer.text(sdf.format(new Date(track.getLastPoint().time)));
	serializer.endTag(KML_NAMESPACE, KmlParser.END);
	serializer.endTag(KML_NAMESPACE, KmlParser.TIMESPAN);
	serializer.startTag(KML_NAMESPACE, KmlParser.STYLE);
	serializer.startTag(KML_NAMESPACE, KmlParser.LISTSTYLE);
	serializer.startTag(KML_NAMESPACE, KmlParser.LISTITEMTYPE);
	serializer.text("checkHideChildren");
	serializer.endTag(KML_NAMESPACE, KmlParser.LISTITEMTYPE);
	serializer.endTag(KML_NAMESPACE, KmlParser.LISTSTYLE);
	serializer.endTag(KML_NAMESPACE, KmlParser.STYLE);
	
	int part = 1;
	boolean first = true;
	startTrackPart(serializer, part, track.name);
	List<TrackPoint> trackPoints = track.getAllPoints();
	synchronized (trackPoints)
	{
		for (TrackPoint tp : trackPoints)
		{
			if (!tp.continous && !first)
			{
				stopTrackPart(serializer);
				part++;
				startTrackPart(serializer, part, track.name);
			}
			serializer.text(String.format("%f,%f,%f ", tp.longitude, tp.latitude, tp.elevation));
			first = false;
		}
	}
	stopTrackPart(serializer);
	serializer.endTag(KML_NAMESPACE, KmlParser.FOLDER);
	serializer.endTag(KML_NAMESPACE, KmlParser.DOCUMENT);
	serializer.endTag(KML_NAMESPACE, KmlParser.KML);
	serializer.endDocument();
	serializer.flush();
	writer.close();
}
 
Example 14
Source File: DashManifestParser.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses an event object.
 *
 * @param xpp The current xml parser.
 * @param scratchOutputStream A {@link ByteArrayOutputStream} that's used when parsing the object.
 * @return The serialized byte array.
 * @throws XmlPullParserException If there is any error parsing this node.
 * @throws IOException If there is any error reading from the underlying input stream.
 */
protected byte[] parseEventObject(XmlPullParser xpp, ByteArrayOutputStream scratchOutputStream)
    throws XmlPullParserException, IOException {
  scratchOutputStream.reset();
  XmlSerializer xmlSerializer = Xml.newSerializer();
  xmlSerializer.setOutput(scratchOutputStream, null);
  // Start reading everything between <Event> and </Event>, and serialize them into an Xml
  // byte array.
  xpp.nextToken();
  while (!XmlPullParserUtil.isEndTag(xpp, "Event")) {
    switch (xpp.getEventType()) {
      case (XmlPullParser.START_DOCUMENT):
        xmlSerializer.startDocument(null, false);
        break;
      case (XmlPullParser.END_DOCUMENT):
        xmlSerializer.endDocument();
        break;
      case (XmlPullParser.START_TAG):
        xmlSerializer.startTag(xpp.getNamespace(), xpp.getName());
        for (int i = 0; i < xpp.getAttributeCount(); i++) {
          xmlSerializer.attribute(xpp.getAttributeNamespace(i), xpp.getAttributeName(i),
              xpp.getAttributeValue(i));
        }
        break;
      case (XmlPullParser.END_TAG):
        xmlSerializer.endTag(xpp.getNamespace(), xpp.getName());
        break;
      case (XmlPullParser.TEXT):
        xmlSerializer.text(xpp.getText());
        break;
      case (XmlPullParser.CDSECT):
        xmlSerializer.cdsect(xpp.getText());
        break;
      case (XmlPullParser.ENTITY_REF):
        xmlSerializer.entityRef(xpp.getText());
        break;
      case (XmlPullParser.IGNORABLE_WHITESPACE):
        xmlSerializer.ignorableWhitespace(xpp.getText());
        break;
      case (XmlPullParser.PROCESSING_INSTRUCTION):
        xmlSerializer.processingInstruction(xpp.getText());
        break;
      case (XmlPullParser.COMMENT):
        xmlSerializer.comment(xpp.getText());
        break;
      case (XmlPullParser.DOCDECL):
        xmlSerializer.docdecl(xpp.getText());
        break;
      default: // fall out
    }
    xpp.nextToken();
  }
  xmlSerializer.flush();
  return scratchOutputStream.toByteArray();
}
 
Example 15
Source File: DashManifestParser.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses an event object.
 *
 * @param xpp The current xml parser.
 * @param scratchOutputStream A {@link ByteArrayOutputStream} that's used when parsing the object.
 * @return The serialized byte array.
 * @throws XmlPullParserException If there is any error parsing this node.
 * @throws IOException If there is any error reading from the underlying input stream.
 */
protected byte[] parseEventObject(XmlPullParser xpp, ByteArrayOutputStream scratchOutputStream)
    throws XmlPullParserException, IOException {
  scratchOutputStream.reset();
  XmlSerializer xmlSerializer = Xml.newSerializer();
  xmlSerializer.setOutput(scratchOutputStream, C.UTF8_NAME);
  // Start reading everything between <Event> and </Event>, and serialize them into an Xml
  // byte array.
  xpp.nextToken();
  while (!XmlPullParserUtil.isEndTag(xpp, "Event")) {
    switch (xpp.getEventType()) {
      case (XmlPullParser.START_DOCUMENT):
        xmlSerializer.startDocument(null, false);
        break;
      case (XmlPullParser.END_DOCUMENT):
        xmlSerializer.endDocument();
        break;
      case (XmlPullParser.START_TAG):
        xmlSerializer.startTag(xpp.getNamespace(), xpp.getName());
        for (int i = 0; i < xpp.getAttributeCount(); i++) {
          xmlSerializer.attribute(xpp.getAttributeNamespace(i), xpp.getAttributeName(i),
              xpp.getAttributeValue(i));
        }
        break;
      case (XmlPullParser.END_TAG):
        xmlSerializer.endTag(xpp.getNamespace(), xpp.getName());
        break;
      case (XmlPullParser.TEXT):
        xmlSerializer.text(xpp.getText());
        break;
      case (XmlPullParser.CDSECT):
        xmlSerializer.cdsect(xpp.getText());
        break;
      case (XmlPullParser.ENTITY_REF):
        xmlSerializer.entityRef(xpp.getText());
        break;
      case (XmlPullParser.IGNORABLE_WHITESPACE):
        xmlSerializer.ignorableWhitespace(xpp.getText());
        break;
      case (XmlPullParser.PROCESSING_INSTRUCTION):
        xmlSerializer.processingInstruction(xpp.getText());
        break;
      case (XmlPullParser.COMMENT):
        xmlSerializer.comment(xpp.getText());
        break;
      case (XmlPullParser.DOCDECL):
        xmlSerializer.docdecl(xpp.getText());
        break;
      default: // fall out
    }
    xpp.nextToken();
  }
  xmlSerializer.flush();
  return scratchOutputStream.toByteArray();
}
 
Example 16
Source File: DashManifestParser.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
/**
 * Parses an event object.
 *
 * @param xpp The current xml parser.
 * @param scratchOutputStream A {@link ByteArrayOutputStream} that's used when parsing the object.
 * @return The serialized byte array.
 * @throws XmlPullParserException If there is any error parsing this node.
 * @throws IOException If there is any error reading from the underlying input stream.
 */
protected byte[] parseEventObject(XmlPullParser xpp, ByteArrayOutputStream scratchOutputStream)
    throws XmlPullParserException, IOException {
  scratchOutputStream.reset();
  XmlSerializer xmlSerializer = Xml.newSerializer();
  xmlSerializer.setOutput(scratchOutputStream, C.UTF8_NAME);
  // Start reading everything between <Event> and </Event>, and serialize them into an Xml
  // byte array.
  xpp.nextToken();
  while (!XmlPullParserUtil.isEndTag(xpp, "Event")) {
    switch (xpp.getEventType()) {
      case (XmlPullParser.START_DOCUMENT):
        xmlSerializer.startDocument(null, false);
        break;
      case (XmlPullParser.END_DOCUMENT):
        xmlSerializer.endDocument();
        break;
      case (XmlPullParser.START_TAG):
        xmlSerializer.startTag(xpp.getNamespace(), xpp.getName());
        for (int i = 0; i < xpp.getAttributeCount(); i++) {
          xmlSerializer.attribute(xpp.getAttributeNamespace(i), xpp.getAttributeName(i),
              xpp.getAttributeValue(i));
        }
        break;
      case (XmlPullParser.END_TAG):
        xmlSerializer.endTag(xpp.getNamespace(), xpp.getName());
        break;
      case (XmlPullParser.TEXT):
        xmlSerializer.text(xpp.getText());
        break;
      case (XmlPullParser.CDSECT):
        xmlSerializer.cdsect(xpp.getText());
        break;
      case (XmlPullParser.ENTITY_REF):
        xmlSerializer.entityRef(xpp.getText());
        break;
      case (XmlPullParser.IGNORABLE_WHITESPACE):
        xmlSerializer.ignorableWhitespace(xpp.getText());
        break;
      case (XmlPullParser.PROCESSING_INSTRUCTION):
        xmlSerializer.processingInstruction(xpp.getText());
        break;
      case (XmlPullParser.COMMENT):
        xmlSerializer.comment(xpp.getText());
        break;
      case (XmlPullParser.DOCDECL):
        xmlSerializer.docdecl(xpp.getText());
        break;
      default: // fall out
    }
    xpp.nextToken();
  }
  xmlSerializer.flush();
  return scratchOutputStream.toByteArray();
}
 
Example 17
Source File: DashManifestParser.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses an event object.
 *
 * @param xpp The current xml parser.
 * @param scratchOutputStream A {@link ByteArrayOutputStream} that's used when parsing the object.
 * @return The serialized byte array.
 * @throws XmlPullParserException If there is any error parsing this node.
 * @throws IOException If there is any error reading from the underlying input stream.
 */
protected byte[] parseEventObject(XmlPullParser xpp, ByteArrayOutputStream scratchOutputStream)
    throws XmlPullParserException, IOException {
  scratchOutputStream.reset();
  XmlSerializer xmlSerializer = Xml.newSerializer();
  xmlSerializer.setOutput(scratchOutputStream, null);
  // Start reading everything between <Event> and </Event>, and serialize them into an Xml
  // byte array.
  xpp.nextToken();
  while (!XmlPullParserUtil.isEndTag(xpp, "Event")) {
    switch (xpp.getEventType()) {
      case (XmlPullParser.START_DOCUMENT):
        xmlSerializer.startDocument(null, false);
        break;
      case (XmlPullParser.END_DOCUMENT):
        xmlSerializer.endDocument();
        break;
      case (XmlPullParser.START_TAG):
        xmlSerializer.startTag(xpp.getNamespace(), xpp.getName());
        for (int i = 0; i < xpp.getAttributeCount(); i++) {
          xmlSerializer.attribute(xpp.getAttributeNamespace(i), xpp.getAttributeName(i),
              xpp.getAttributeValue(i));
        }
        break;
      case (XmlPullParser.END_TAG):
        xmlSerializer.endTag(xpp.getNamespace(), xpp.getName());
        break;
      case (XmlPullParser.TEXT):
        xmlSerializer.text(xpp.getText());
        break;
      case (XmlPullParser.CDSECT):
        xmlSerializer.cdsect(xpp.getText());
        break;
      case (XmlPullParser.ENTITY_REF):
        xmlSerializer.entityRef(xpp.getText());
        break;
      case (XmlPullParser.IGNORABLE_WHITESPACE):
        xmlSerializer.ignorableWhitespace(xpp.getText());
        break;
      case (XmlPullParser.PROCESSING_INSTRUCTION):
        xmlSerializer.processingInstruction(xpp.getText());
        break;
      case (XmlPullParser.COMMENT):
        xmlSerializer.comment(xpp.getText());
        break;
      case (XmlPullParser.DOCDECL):
        xmlSerializer.docdecl(xpp.getText());
        break;
      default: // fall out
    }
    xpp.nextToken();
  }
  xmlSerializer.flush();
  return scratchOutputStream.toByteArray();
}
 
Example 18
Source File: ActivitySettings.java    From tracker-control-android with GNU General Public License v3.0 4 votes vote down vote up
private void xmlExport(OutputStream out) throws 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);
    serializer.startTag(null, "trackercontrol");

    serializer.startTag(null, "application");
    xmlExport(PreferenceManager.getDefaultSharedPreferences(this), serializer);
    serializer.endTag(null, "application");

    serializer.startTag(null, "wifi");
    xmlExport(getSharedPreferences("wifi", Context.MODE_PRIVATE), serializer);
    serializer.endTag(null, "wifi");

    serializer.startTag(null, "mobile");
    xmlExport(getSharedPreferences("other", Context.MODE_PRIVATE), serializer);
    serializer.endTag(null, "mobile");

    serializer.startTag(null, "screen_wifi");
    xmlExport(getSharedPreferences("screen_wifi", Context.MODE_PRIVATE), serializer);
    serializer.endTag(null, "screen_wifi");

    serializer.startTag(null, "screen_other");
    xmlExport(getSharedPreferences("screen_other", Context.MODE_PRIVATE), serializer);
    serializer.endTag(null, "screen_other");

    serializer.startTag(null, "roaming");
    xmlExport(getSharedPreferences("roaming", Context.MODE_PRIVATE), serializer);
    serializer.endTag(null, "roaming");

    serializer.startTag(null, "lockdown");
    xmlExport(getSharedPreferences("lockdown", Context.MODE_PRIVATE), serializer);
    serializer.endTag(null, "lockdown");

    serializer.startTag(null, "apply");
    xmlExport(getSharedPreferences("apply", Context.MODE_PRIVATE), serializer);
    serializer.endTag(null, "apply");

    serializer.startTag(null, "notify");
    xmlExport(getSharedPreferences("notify", Context.MODE_PRIVATE), serializer);
    serializer.endTag(null, "notify");

    serializer.startTag(null, "filter");
    filterExport(serializer);
    serializer.endTag(null, "filter");

    serializer.startTag(null, "forward");
    forwardExport(serializer);
    serializer.endTag(null, "forward");

    serializer.startTag(null, "blocklist");
    xmlExport(getSharedPreferences(PREF_BLOCKLIST, Context.MODE_PRIVATE), serializer);
    serializer.endTag(null, "blocklist");

    serializer.endTag(null, "trackercontrol");
    serializer.endDocument();
    serializer.flush();
}
 
Example 19
Source File: XmlPullCreateXML.java    From maven-framework-project with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception{
    XmlSerializer xmlSerializer=new KXmlSerializer();
    xmlSerializer.setOutput(new FileOutputStream(new File("target/student.xml")), "utf-8");
    xmlSerializer.startDocument(null, true);
    xmlSerializer.startTag(null, "data");
    for (int i = 0; i < 10; i++) {
        xmlSerializer.startTag(null, "student");
        xmlSerializer.attribute(null, "id", ""+(i+1));
        
        xmlSerializer.startTag(null, "name");
        xmlSerializer.text("student"+i);
        xmlSerializer.endTag(null, "name");
        
        xmlSerializer.startTag(null, "age");
        xmlSerializer.text((i+10)+"");
        xmlSerializer.endTag(null, "age");
        
        
        xmlSerializer.startTag(null, "sex");
        if(i%2==0){
            xmlSerializer.text("女");
        }else{
            xmlSerializer.text("男");
        }
        xmlSerializer.endTag(null, "sex");
        
        
        xmlSerializer.startTag(null, "address");
        xmlSerializer.text("陕西西安");
        xmlSerializer.endTag(null, "address");
        
        xmlSerializer.endTag(null, "student");
    }
    
    xmlSerializer.endTag(null, "data");
    
    xmlSerializer.endDocument();
    
    xmlSerializer.flush();
    
}
 
Example 20
Source File: GpxFiles.java    From Androzic with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Saves track to file.
 * 
 * @param file valid <code>File</code>
 * @param track <code>Track</code> object containing the list of track points to save
 * @throws IOException
 */
public static void saveTrackToFile(final File file, final Track track) throws IOException
{
	XmlSerializer serializer = Xml.newSerializer();
	serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
	BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false)));
	serializer.setOutput(writer);
	serializer.startDocument("UTF-8", null);
	serializer.setPrefix("", GPX_NAMESPACE);
	serializer.startTag(GPX_NAMESPACE, GpxParser.GPX);
	serializer.attribute("", "creator", "Androzic http://androzic.com");
	serializer.startTag(GPX_NAMESPACE, GpxParser.TRK);
	serializer.startTag(GPX_NAMESPACE, GpxParser.NAME);
	serializer.text(track.name);
	serializer.endTag(GPX_NAMESPACE, GpxParser.NAME);
	serializer.startTag(GPX_NAMESPACE, GpxParser.SRC);
	serializer.text(Androzic.getDeviceName());
	serializer.endTag(GPX_NAMESPACE, GpxParser.SRC);
	
	boolean first = true;
	serializer.startTag(GPX_NAMESPACE, GpxParser.TRKSEG);
	List<TrackPoint> trackPoints = track.getAllPoints();
	for (TrackPoint tp : trackPoints)
	{
		if (!tp.continous && !first)
		{
			serializer.endTag(GPX_NAMESPACE, GpxParser.TRKSEG);
			serializer.startTag(GPX_NAMESPACE, GpxParser.TRKSEG);
		}
		serializer.startTag(GPX_NAMESPACE, GpxParser.TRKPT);
		serializer.attribute("", GpxParser.LAT, String.valueOf(tp.latitude));
		serializer.attribute("", GpxParser.LON, String.valueOf(tp.longitude));
		serializer.startTag(GPX_NAMESPACE, GpxParser.ELE);
		serializer.text(String.valueOf(tp.elevation));
		serializer.endTag(GPX_NAMESPACE, GpxParser.ELE);
		serializer.startTag(GPX_NAMESPACE, GpxParser.TIME);
		serializer.text(GpxParser.trktime.format(new Date(tp.time)));
		serializer.endTag(GPX_NAMESPACE, GpxParser.TIME);
		serializer.endTag(GPX_NAMESPACE, GpxParser.TRKPT);
		first = false;
	}
	serializer.endTag(GPX_NAMESPACE, GpxParser.TRKSEG);
	serializer.endTag(GPX_NAMESPACE, GpxParser.TRK);
	serializer.endTag(GPX_NAMESPACE, GpxParser.GPX);
	serializer.endDocument();
	serializer.flush();
	writer.close();
}