Example usage for javax.xml.stream XMLStreamWriter writeStartDocument

List of usage examples for javax.xml.stream XMLStreamWriter writeStartDocument

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamWriter writeStartDocument.

Prototype

public void writeStartDocument() throws XMLStreamException;

Source Link

Document

Write the XML Declaration.

Usage

From source file:com.flexive.shared.media.impl.FxMediaImageMagickEngine.java

/**
 * Parse an identify stdOut result (from in) and convert it to an XML content
 *
 * @param in identify response//from w w w .ja  v  a 2s.com
 * @return XML content
 * @throws XMLStreamException on errors
 * @throws IOException        on errors
 */
public static String parse(InputStream in) throws XMLStreamException, IOException {
    StringWriter sw = new StringWriter(2000);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
    writer.writeStartDocument();

    int lastLevel = 0, level, lastNonValueLevel = 1;
    boolean valueEntry;
    String curr = null;
    String[] entry;
    try {
        while ((curr = br.readLine()) != null) {
            level = getLevel(curr);
            if (level == 0 && curr.startsWith("Image:")) {
                writer.writeStartElement("Image");
                entry = curr.split(": ");
                if (entry.length >= 2)
                    writer.writeAttribute("source", entry[1]);
                lastLevel = level;
                continue;
            }
            if (!(valueEntry = pNumeric.matcher(curr).matches())) {
                while (level < lastLevel--)
                    writer.writeEndElement();
                lastNonValueLevel = level;
            } else
                level = lastNonValueLevel + 1;
            if (curr.endsWith(":")) {
                writer.writeStartElement(
                        curr.substring(0, curr.lastIndexOf(':')).trim().replaceAll("[ :]", "-"));
                lastLevel = level + 1;
                continue;
            } else if (pColormap.matcher(curr).matches()) {
                writer.writeStartElement(
                        curr.substring(0, curr.lastIndexOf(':')).trim().replaceAll("[ :]", "-"));
                writer.writeAttribute("colors", curr.split(": ")[1].trim());
                lastLevel = level + 1;
                continue;
            }
            entry = curr.split(": ");
            if (entry.length == 2) {
                if (!valueEntry) {
                    writer.writeStartElement(entry[0].trim().replaceAll("[ :]", "-"));
                    writer.writeCharacters(entry[1]);
                    writer.writeEndElement();
                } else {
                    writer.writeEmptyElement("value");
                    writer.writeAttribute("key", entry[0].trim().replaceAll("[ :]", "-"));
                    writer.writeAttribute("data", entry[1]);
                    //                        writer.writeEndElement();
                }
            } else {
                //                    System.out.println("unknown line: "+curr);
            }
            lastLevel = level;
        }
    } catch (Exception e) {
        LOG.error("Error at [" + curr + "]:" + e.getMessage(), e);
    }
    writer.writeEndDocument();
    writer.flush();
    writer.close();
    return sw.getBuffer().toString();
}

From source file:microsoft.exchange.webservices.data.core.EwsServiceXmlWriter.java

/**
 * @param document XML document//from w  ww  .j a va  2s  .  c  o  m
 * @param xmlStreamWriter XML stream writer
 * @throws XMLStreamException the XML stream exception
 */
public static void writeToDocument(Document document, XMLStreamWriter xmlStreamWriter)
        throws XMLStreamException {

    xmlStreamWriter.writeStartDocument();
    Element rootElement = document.getDocumentElement();
    addElement(rootElement, xmlStreamWriter);
    xmlStreamWriter.writeEndDocument();
}

From source file:com.predic8.membrane.core.config.AbstractXmlElement.java

public String toXml() throws Exception {
    StringWriter sw = new StringWriter();
    XMLStreamWriter w = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
    w.writeStartDocument();
    write(w);//w w w.ja v  a 2s.c om
    w.writeEndDocument();
    return sw.toString();
}

From source file:com.pocketsoap.salesforce.soap.SoapRequestEntity.java

public final void writeRequest(OutputStream out) throws IOException {
    XMLOutputFactory f = XMLOutputFactory.newInstance();
    try {/*from w w  w.  jav a 2 s.co  m*/
        XMLStreamWriter w = f.createXMLStreamWriter(new BufferedOutputStream(out, 1024), "UTF-8");
        w.writeStartDocument();
        w.writeStartElement("s", "Envelope", SOAP_NS);
        w.writeNamespace("s", SOAP_NS);
        w.writeNamespace("p", PARTNER_NS);
        w.setPrefix("p", PARTNER_NS);
        w.setPrefix("s", SOAP_NS);
        if (hasHeaders()) {
            w.writeStartElement(SOAP_NS, "Header");
            writeHeaders(w);
            w.writeEndElement();
        }
        w.writeStartElement(SOAP_NS, "Body");
        writeBody(w);
        w.writeEndElement();//body
        w.writeEndElement();//envelope
        w.writeEndDocument();
        w.close();
    } catch (XMLStreamException e) {
        throw new IOException("Error generating request xml", e);
    }
}

From source file:XMLWriteTest.java

/**
 * Writers an SVG document of the current drawing.
 * @param writer the document destination
 *///from   w w  w . java2  s .c  o  m
public void writeDocument(XMLStreamWriter writer) throws XMLStreamException {
    writer.writeStartDocument();
    writer.writeDTD("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 20000802//EN\" "
            + "\"http://www.w3.org/TR/2000/CR-SVG-20000802/DTD/svg-20000802.dtd\">");
    writer.writeStartElement("svg");
    writer.writeAttribute("width", "" + getWidth());
    writer.writeAttribute("height", "" + getHeight());
    for (int i = 0; i < rects.size(); i++) {
        Color c = colors.get(i);
        Rectangle2D r = rects.get(i);
        writer.writeEmptyElement("rect");
        writer.writeAttribute("x", "" + r.getX());
        writer.writeAttribute("y", "" + r.getY());
        writer.writeAttribute("width", "" + r.getWidth());
        writer.writeAttribute("height", "" + r.getHeight());
        writer.writeAttribute("fill", colorToString(c));
    }
    writer.writeEndDocument(); // closes svg element
}

From source file:com.flexive.shared.media.FxMetadata.java

/**
 * Get this metadata object as XML document
 *
 * @return XML document//from w w w.ja  v a  2 s. co  m
 * @throws FxApplicationException on errors
 */
public String toXML() throws FxApplicationException {
    StringWriter sw = new StringWriter(2000);
    try {
        XMLStreamWriter writer = getXmlOutputFactory().createXMLStreamWriter(sw);
        writer.writeStartDocument();
        writer.writeStartElement("metadata");
        writer.writeAttribute("mediatype", getMediaType().name());
        writer.writeAttribute("mimetype", getMimeType());
        writer.writeAttribute("filename", getFilename());
        writeXMLTags(writer);
        for (FxMetadataItem mdi : getMetadata()) {
            final String value = mdi.getValue().replaceAll("[\\x00-\\x1F]", ""); //filter out control characters
            if (StringUtils.isEmpty(value))
                continue;
            writer.writeStartElement("meta");
            writer.writeAttribute("key", mdi.getKey());
            writer.writeCData(value);
            writer.writeEndElement();
        }
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new FxApplicationException(e, "ex.general.xml", e.getMessage());
    }
    return sw.getBuffer().toString();
}

From source file:org.elasticsearch.discovery.ec2.AmazonEC2Fixture.java

/**
 * Generates a XML response that describe the EC2 instances
 *///from  w ww .  ja v  a2 s.  c  o  m
private byte[] generateDescribeInstancesResponse() {
    final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
    xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

    final StringWriter out = new StringWriter();
    XMLStreamWriter sw;
    try {
        sw = xmlOutputFactory.createXMLStreamWriter(out);
        sw.writeStartDocument();

        String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/";
        sw.setDefaultNamespace(namespace);
        sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace);
        {
            sw.writeStartElement("requestId");
            sw.writeCharacters(UUID.randomUUID().toString());
            sw.writeEndElement();

            sw.writeStartElement("reservationSet");
            {
                if (Files.exists(nodes)) {
                    for (String address : Files.readAllLines(nodes)) {

                        sw.writeStartElement("item");
                        {
                            sw.writeStartElement("reservationId");
                            sw.writeCharacters(UUID.randomUUID().toString());
                            sw.writeEndElement();

                            sw.writeStartElement("instancesSet");
                            {
                                sw.writeStartElement("item");
                                {
                                    sw.writeStartElement("instanceId");
                                    sw.writeCharacters(UUID.randomUUID().toString());
                                    sw.writeEndElement();

                                    sw.writeStartElement("imageId");
                                    sw.writeCharacters(UUID.randomUUID().toString());
                                    sw.writeEndElement();

                                    sw.writeStartElement("instanceState");
                                    {
                                        sw.writeStartElement("code");
                                        sw.writeCharacters("16");
                                        sw.writeEndElement();

                                        sw.writeStartElement("name");
                                        sw.writeCharacters("running");
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();

                                    sw.writeStartElement("privateDnsName");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();

                                    sw.writeStartElement("dnsName");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();

                                    sw.writeStartElement("instanceType");
                                    sw.writeCharacters("m1.medium");
                                    sw.writeEndElement();

                                    sw.writeStartElement("placement");
                                    {
                                        sw.writeStartElement("availabilityZone");
                                        sw.writeCharacters("use-east-1e");
                                        sw.writeEndElement();

                                        sw.writeEmptyElement("groupName");

                                        sw.writeStartElement("tenancy");
                                        sw.writeCharacters("default");
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();

                                    sw.writeStartElement("privateIpAddress");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();

                                    sw.writeStartElement("ipAddress");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                        sw.writeEndElement();
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();

            sw.writeEndDocument();
            sw.flush();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return out.toString().getBytes(UTF_8);
}

From source file:com.tamingtext.tagrecommender.ExtractStackOverflowData.java

/** Extract as many as <code>limit</code> questions from the <code>reader</code>
 *  provided, writing them to <code>writer</code>.
 * @param reader/*from ww w. j a  v  a  2s  .  c om*/
 * @param writer
 * @param limit
 * @return
 * @throws XMLStreamException
 */
protected int extractXMLData(XMLStreamReader reader, XMLStreamWriter writer, int limit)
        throws XMLStreamException {

    int questionCount = 0;
    int attrCount;
    boolean copyElement = false;

    writer.writeStartDocument();
    writer.writeStartElement("posts");
    writer.writeCharacters("\n");
    while (reader.hasNext() && questionCount < limit) {
        switch (reader.next()) {
        case XMLEvent.START_ELEMENT:
            if (reader.getLocalName().equals("row")) {
                attrCount = reader.getAttributeCount();
                for (int i = 0; i < attrCount; i++) {
                    // copy only the questions.
                    if (reader.getAttributeName(i).getLocalPart().equals("PostTypeId")
                            && reader.getAttributeValue(i).equals("1")) {
                        copyElement = true;
                        break;
                    }
                }

                if (copyElement) {
                    writer.writeCharacters("  ");
                    writer.writeStartElement("row");
                    for (int i = 0; i < attrCount; i++) {
                        writer.writeAttribute(reader.getAttributeName(i).getLocalPart(),
                                reader.getAttributeValue(i));
                    }
                    writer.writeEndElement();
                    writer.writeCharacters("\n");
                    copyElement = false;
                    questionCount++;
                }
            }
            break;
        }
    }
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    writer.close();

    return questionCount;
}

From source file:com.concursive.connect.web.modules.api.services.BackupService.java

public boolean process(TransactionItem transactionItem, Connection db) throws Exception {

    LOG.debug("Backup requested...");

    // TODO: Fix cyclical/endless backups; need to keep an array of ids already archived
    // TODO: Fix if lookup value is -1, then a lookup is not needed

    DataRecordFactory factory = DataRecordFactory.INSTANCE;

    // Override the default response packet so that the returned data records
    // can be replayed using the RestoreService; stream the output
    PacketContext packetContext = transactionItem.getPacketContext();
    packetContext.setReturnType(PacketContext.RETURN_DATARECORDS);

    // Start with the original record(s) being backed up
    LOG.debug("Performing buildList query");
    Object object = transactionItem.getObject();
    if (object instanceof java.util.AbstractList || object instanceof java.util.AbstractMap) {
        Object result = TransactionItem.doExecute(transactionItem.getObject(), db, TransactionItem.SELECT,
                packetContext, "buildList");
        // TODO: check result
    } else {//w  ww  . j a  va 2s .  c  om
        Object newObject = ObjectUtils.constructObject(object.getClass(), db, ObjectUtils.getParamAsInt(object,
                factory.retrieveUniqueField(transactionItem.getName() + "List")));
        transactionItem.setObject(newObject);
    }

    // Start backup recursion...
    //   Consider lower-memory options to stream records without holding in memory
    //   option 1: use pagedList to get x record(s) at a time
    //   option 2: consider queue for limiting backup requests and asynchronous backups

    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    OutputStream outputStream = null;
    if (packetContext.getOutputStream() == null) {
        outputStream = packetContext.getResponse().getOutputStream();
    } else {
        outputStream = packetContext.getOutputStream();
    }
    XMLStreamWriter writer = outputFactory.createXMLStreamWriter(outputStream, "utf-8");
    writer.writeStartDocument();
    writer.writeCharacters(System.getProperty("line.separator"));
    writer.writeStartElement("concursive");
    writer.writeCharacters(System.getProperty("line.separator"));

    ArrayList<String> addedRecords = new ArrayList<String>();
    addRecords(writer, transactionItem.getObject(), transactionItem, packetContext, db, addedRecords);
    writer.writeEndElement();
    writer.writeCharacters(System.getProperty("line.separator"));
    writer.flush();
    writer.close();

    return true;
}

From source file:org.xmlsh.internal.commands.http.java

private void writeHeaders(String outv, StatusLine statusLine, Header[] allHeaders)
        throws XMLStreamException, SaxonApiException, CoreException, IOException {
    OutputPort out = mShell.getEnv().getOutputPort(outv);

    XMLStreamWriter sw = out.asXMLStreamWriter(getSerializeOpts());
    sw.writeStartDocument();
    sw.writeStartElement("status");
    sw.writeAttribute("status-code", String.valueOf(statusLine.getStatusCode()));
    sw.writeAttribute("reason", statusLine.getReasonPhrase());
    sw.writeAttribute("protocol-version", statusLine.getProtocolVersion().toString());

    sw.writeEndElement();//from  ww w  . j  a  va 2s  . c  om

    sw.writeStartElement("headers");
    for (Header header : allHeaders) {
        sw.writeStartElement("header");
        sw.writeAttribute("name", header.getName());
        sw.writeAttribute("value", header.getValue());
        sw.writeEndElement();
    }
    sw.writeEndElement();
    sw.writeEndDocument();
    sw.close();

}