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

The following examples show how to use org.xmlpull.v1.XmlSerializer#startDocument() . 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: XmlUtils.java    From Cangol-appcore with Apache License 2.0 6 votes vote down vote up
/**
 * 转换Object到xml
 *
 * @param obj
 * @param useAnnotation
 * @return
 */
public static String toXml(Object obj, boolean useAnnotation) {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final XmlSerializer serializer = Xml.newSerializer();
    String result = null;
    try {
        serializer.setOutput(baos, UTF_8);
        serializer.startDocument(UTF_8, true);
        toXml(serializer, obj, useAnnotation);
        serializer.endDocument();
        baos.close();
        result = baos.toString(UTF_8);
    } catch (IOException e) {
        Log.d(TAG, e.getMessage());
    }
    return result;
}
 
Example 2
Source File: XulDebugMonitor.java    From starcor.xul with GNU Lesser General Public License v3.0 6 votes vote down vote up
public synchronized boolean dumpGlobalSelector(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);
		XmlContentDumper contentDumper = initContentDumper(request.queries, xmlWriter);
		contentDumper.setNoSelectors(false);
		contentDumper.dumpSelectors(XulManager.getSelectors());
		xmlWriter.endDocument();
		xmlWriter.flush();
		return true;
	} catch (IOException e) {
		XulLog.e(TAG, e);
	}
	return false;
}
 
Example 3
Source File: SerializerExample.java    From exificient with MIT License 6 votes vote down vote up
static void write(XmlSerializer xpp) throws IllegalArgumentException,
		IllegalStateException, IOException {
	xpp.startDocument(null, null);

	xpp.setPrefix("foo", "urn:foo"); // first prefix
	xpp.startTag("", "root");

	xpp.attribute("", "atRoot", "atValue");
	{
		xpp.comment("my comment");

		xpp.startTag("", "el1");
		xpp.text("el1 text");
		xpp.endTag("", "el1");
	}
	xpp.endTag("", "root");
	xpp.endDocument();
}
 
Example 4
Source File: CacheQuotaStrategy.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static void saveToXml(XmlSerializer out,
        List<CacheQuotaHint> requests, long bytesWhenCalculated) throws IOException {
    out.startDocument(null, true);
    out.startTag(null, CACHE_INFO_TAG);
    int requestSize = requests.size();
    out.attribute(null, ATTR_PREVIOUS_BYTES, Long.toString(bytesWhenCalculated));

    for (int i = 0; i < requestSize; i++) {
        CacheQuotaHint request = requests.get(i);
        out.startTag(null, TAG_QUOTA);
        String uuid = request.getVolumeUuid();
        if (uuid != null) {
            out.attribute(null, ATTR_UUID, request.getVolumeUuid());
        }
        out.attribute(null, ATTR_UID, Integer.toString(request.getUid()));
        out.attribute(null, ATTR_QUOTA_IN_BYTES, Long.toString(request.getQuota()));
        out.endTag(null, TAG_QUOTA);
    }
    out.endTag(null, CACHE_INFO_TAG);
    out.endDocument();
}
 
Example 5
Source File: AccessibilityNodeInfoDumper.java    From JsDroidCmd with Mozilla Public License 2.0 6 votes vote down vote up
public static void dumpWindowHierarchy(UiDevice device, OutputStream out)
			throws IOException {
		XmlSerializer serializer = Xml.newSerializer();
		serializer.setFeature(
				"http://xmlpull.org/v1/doc/features.html#indent-output", true);
		serializer.setOutput(out, "UTF-8");

		serializer.startDocument("UTF-8", true);
		serializer.startTag("", "hierarchy"); // TODO(allenhair): Should we use
												// a namespace?
		serializer.attribute("", "rotation",
				Integer.toString(device.getDisplayRotation()));

		 for (AccessibilityNodeInfo root : device.getWindowRoots()) {
			 dumpNodeRec(root, serializer, 0, device.getDisplayWidth(),
			 device.getDisplayHeight());
		 }
//		dumpNodeRec(device.getUiAutomation().getRootInActiveWindow(),
//				serializer, 0, device.getDisplayWidth(),
//				device.getDisplayHeight());

		serializer.endTag("", "hierarchy");
		serializer.endDocument();
	}
 
Example 6
Source File: QueueMessageSerializer.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Generates the message request body from a string containing the message.
 * The message must be encodable as UTF-8. To be included in a web request,
 * this message request body must be written to the output stream of the web
 * request.
 * 
 * @param message
 *            A <code>String<code> containing the message to wrap in a message request body.
 * 
 * @return An array of <code>byte</code> containing the message request body
 *         encoded as UTF-8.
 * @throws IOException
 *             if there is an error writing the queue message.
 * @throws IllegalStateException
 *             if there is an error writing the queue message.
 * @throws IllegalArgumentException
 *             if there is an error writing the queue message.
 */
public static byte[] generateMessageRequestBody(final String message) throws IllegalArgumentException,
        IllegalStateException, IOException {
    final StringWriter outWriter = new StringWriter();
    final XmlSerializer xmlw = Utility.getXmlSerializer(outWriter);

    // default is UTF8
    xmlw.startDocument(Constants.UTF8_CHARSET, true);
    xmlw.startTag(Constants.EMPTY_STRING, QueueConstants.QUEUE_MESSAGE_ELEMENT);

    Utility.serializeElement(xmlw, QueueConstants.MESSAGE_TEXT_ELEMENT, message);

    // end QueueMessage_ELEMENT
    xmlw.endTag(Constants.EMPTY_STRING, QueueConstants.QUEUE_MESSAGE_ELEMENT);

    // end doc
    xmlw.endDocument();

    return outWriter.toString().getBytes(Constants.UTF8_CHARSET);
}
 
Example 7
Source File: ShortcutService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@GuardedBy("mLock")
private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
        boolean forBackup) throws IOException, XmlPullParserException {

    final BufferedOutputStream bos = new BufferedOutputStream(os);

    // Write to XML
    XmlSerializer out = new FastXmlSerializer();
    out.setOutput(bos, StandardCharsets.UTF_8.name());
    out.startDocument(null, true);

    getUserShortcutsLocked(userId).saveToXml(out, forBackup);

    out.endDocument();

    bos.flush();
    os.flush();
}
 
Example 8
Source File: PackageInstallerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@GuardedBy("mSessions")
private void writeSessionsLocked() {
    if (LOGD) Slog.v(TAG, "writeSessionsLocked()");

    FileOutputStream fos = null;
    try {
        fos = mSessionsFile.startWrite();

        XmlSerializer out = new FastXmlSerializer();
        out.setOutput(fos, StandardCharsets.UTF_8.name());
        out.startDocument(null, true);
        out.startTag(null, TAG_SESSIONS);
        final int size = mSessions.size();
        for (int i = 0; i < size; i++) {
            final PackageInstallerSession session = mSessions.valueAt(i);
            session.write(out, mSessionsDir);
        }
        out.endTag(null, TAG_SESSIONS);
        out.endDocument();

        mSessionsFile.finishWrite(fos);
    } catch (IOException e) {
        if (fos != null) {
            mSessionsFile.failWrite(fos);
        }
    }
}
 
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: XmlNamespaceDictionary.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
private ElementSerializer startDoc(
    XmlSerializer serializer, Object element, boolean errorOnUnknown, String elementAlias)
    throws IOException {
  serializer.startDocument(null, null);
  SortedSet<String> aliases = new TreeSet<String>();
  computeAliases(element, aliases);
  if (elementAlias != null) {
    aliases.add(elementAlias);
  }
  for (String alias : aliases) {
    String uri = getNamespaceUriForAliasHandlingUnknown(errorOnUnknown, alias);
    serializer.setPrefix(alias, uri);
  }
  return new ElementSerializer(element, errorOnUnknown);
}
 
Example 11
Source File: SettingsStateTest.java    From Study_Android_Demo with Apache License 2.0 5 votes vote down vote up
/** 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_VERSION_NEW_ENCODING,
            serializer, null, "k", "v", null, "package", null, false);
    SettingsState.writeSingleSetting(
            SettingsState.SETTINGS_VERSION_NEW_ENCODING,
            serializer, "1", "k", "v", null, null, null, false);
}
 
Example 12
Source File: BlockEntryListSerializer.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Writes a Block List and returns the corresponding UTF8 bytes.
 * 
 * @param blockList
 *            the Iterable of BlockEntry to write
 * @param opContext
 *            a tracking object for the request
 * @return a byte array of the UTF8 bytes representing the serialized block list.
 * @throws IOException
 *             if there is an error writing the block list.
 * @throws IllegalStateException
 *             if there is an error writing the block list.
 * @throws IllegalArgumentException
 *             if there is an error writing the block list.
 */
public static byte[] writeBlockListToStream(final Iterable<BlockEntry> blockList, final OperationContext opContext)
        throws IllegalArgumentException, IllegalStateException, IOException {

    final StringWriter outWriter = new StringWriter();
    final XmlSerializer xmlw = Utility.getXmlSerializer(outWriter);

    // default is UTF8
    xmlw.startDocument(Constants.UTF8_CHARSET, true);
    xmlw.startTag(Constants.EMPTY_STRING, BlobConstants.BLOCK_LIST_ELEMENT);

    for (final BlockEntry block : blockList) {

        if (block.getSearchMode() == BlockSearchMode.COMMITTED) {
            Utility.serializeElement(xmlw, BlobConstants.COMMITTED_ELEMENT, block.getId());
        }
        else if (block.getSearchMode() == BlockSearchMode.UNCOMMITTED) {
            Utility.serializeElement(xmlw, BlobConstants.UNCOMMITTED_ELEMENT, block.getId());
        }
        else if (block.getSearchMode() == BlockSearchMode.LATEST) {
            Utility.serializeElement(xmlw, BlobConstants.LATEST_ELEMENT, block.getId());
        }
    }

    // end BlockListElement
    xmlw.endTag(Constants.EMPTY_STRING, BlobConstants.BLOCK_LIST_ELEMENT);

    // end doc
    xmlw.endDocument();

    return outWriter.toString().getBytes(Constants.UTF8_CHARSET);
}
 
Example 13
Source File: AppWarnings.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Writes the configuration file.
 * <p>
 * <strong>Note:</strong> Should be called from the ActivityManagerService thread unless you
 * don't care where you're doing I/O operations. But you <i>do</i> care, don't you?
 */
private void writeConfigToFileAmsThread() {
    // Create a shallow copy so that we don't have to synchronize on config.
    final HashMap<String, Integer> packageFlags;
    synchronized (mPackageFlags) {
        packageFlags = new HashMap<>(mPackageFlags);
    }

    FileOutputStream fos = null;
    try {
        fos = mConfigFile.startWrite();

        final XmlSerializer out = new FastXmlSerializer();
        out.setOutput(fos, StandardCharsets.UTF_8.name());
        out.startDocument(null, true);
        out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        out.startTag(null, "packages");

        for (Map.Entry<String, Integer> entry : packageFlags.entrySet()) {
            String pkg = entry.getKey();
            int mode = entry.getValue();
            if (mode == 0) {
                continue;
            }
            out.startTag(null, "package");
            out.attribute(null, "name", pkg);
            out.attribute(null, "flags", Integer.toString(mode));
            out.endTag(null, "package");
        }

        out.endTag(null, "packages");
        out.endDocument();

        mConfigFile.finishWrite(fos);
    } catch (java.io.IOException e1) {
        Slog.w(TAG, "Error writing package metadata", e1);
        if (fos != null) {
            mConfigFile.failWrite(fos);
        }
    }
}
 
Example 14
Source File: DashManifestParser.java    From Telegram 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 15
Source File: AccessibilityNodeInfoDumper.java    From android-uiautomator-server with MIT License 4 votes vote down vote up
/**
 * Using {@link AccessibilityNodeInfo} this method will walk the layout hierarchy and return
 * String object of xml hierarchy
 *
 * @param root The root accessibility node.
 */
public static String getWindowXMLHierarchy(AccessibilityNodeInfo root) throws UiAutomator2Exception {
    final long startTime = SystemClock.uptimeMillis();
    StringWriter xmlDump = new StringWriter();
    try {

        XmlSerializer serializer = Xml.newSerializer();
        serializer.setOutput(xmlDump);
        serializer.startDocument("UTF-8", true);
        serializer.startTag("", "hierarchy");

        if (root != null) {
            int width = -1;
            int height = -1;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                // getDefaultDisplay method available since API level 18
                Display display = Device.getInstance().getDefaultDisplay();
                Point size = new Point();
                display.getSize(size);
                width = size.x;
                height = size.y;

                serializer.attribute("", "rotation", Integer.toString(display.getRotation()));
            }

            dumpNodeRec(root, serializer, 0, width, height);
        }

        serializer.endTag("", "hierarchy");
        serializer.endDocument();

        /*FileWriter writer = new FileWriter(dumpFile);
        writer.write(stringWriter.toString());
        writer.close();*/
    } catch (IOException e) {
        Log.e("failed to dump window to file", e);
    }
    final long endTime = SystemClock.uptimeMillis();
    Log.i("Fetch time: " + (endTime - startTime) + "ms");
    return xmlDump.toString();
}
 
Example 16
Source File: XmlUtils.java    From Android-PreferencesManager with Apache License 2.0 3 votes vote down vote up
/**
 * Flatten a Map into an output stream as XML. The map can later be read
 * back with readMapXml().
 *
 * @param val The map to be flattened.
 * @param out Where to write the XML data.
 * @see #writeMapXml(Map, String, XmlSerializer)
 * @see #writeListXml
 * @see #writeValueXml
 * @see #readMapXml
 */
public static final void writeMapXml(Map val, OutputStream out) throws XmlPullParserException, java.io.IOException {
    XmlSerializer serializer = new FastXmlSerializer();
    serializer.setOutput(out, "utf-8");
    serializer.startDocument(null, true);
    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    writeMapXml(val, null, serializer);
    serializer.endDocument();
}
 
Example 17
Source File: XmlUtils.java    From TowerCollector with Mozilla Public License 2.0 3 votes vote down vote up
/**
 * Flatten a Map into an output stream as XML.  The map can later be
 * read back with readMapXml().
 *
 * @param val The map to be flattened.
 * @param out Where to write the XML data.
 *
 * @see #writeMapXml(Map, String, XmlSerializer)
 * @see #writeListXml
 * @see #writeValueXml
 * @see #readMapXml
 */
public static final void writeMapXml(Map val, OutputStream out)
        throws XmlPullParserException, java.io.IOException {
    XmlSerializer serializer = new FastXmlSerializer();
    serializer.setOutput(out, "utf-8");
    serializer.startDocument(null, true);
    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    writeMapXml(val, null, serializer);
    serializer.endDocument();
}
 
Example 18
Source File: XmlUtils.java    From HtmlCompat with Apache License 2.0 3 votes vote down vote up
/**
 * 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();
}
 
Example 19
Source File: XmlUtils.java    From AcDisplay with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 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 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();
}
 
Example 20
Source File: XmlUtils.java    From AcDisplay with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Flatten a Map into an output stream as XML.  The map can later be
 * read back with readMapXml().
 *
 * @param val The map to be flattened.
 * @param out Where to write the XML data.
 * @see #writeMapXml(Map, String, XmlSerializer)
 * @see #writeListXml
 * @see #writeValueXml
 * @see #readMapXml
 */
public static void writeMapXml(Map val, OutputStream out)
        throws XmlPullParserException, java.io.IOException {
    XmlSerializer serializer = new FastXmlSerializer();
    serializer.setOutput(out, "utf-8");
    serializer.startDocument(null, true);
    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    writeMapXml(val, null, serializer);
    serializer.endDocument();
}