Example usage for javax.xml.stream XMLStreamWriter writeCharacters

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

Introduction

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

Prototype

public void writeCharacters(String text) throws XMLStreamException;

Source Link

Document

Write text to the output

Usage

From source file:de.codesourcery.eve.skills.dao.impl.FileShoppingListDAO.java

protected void writeToFile() {

    XMLStreamWriter writer = null;
    try {/*from  www.j a  v  a  2 s . c  o m*/

        if (!dataFile.exists()) {
            final File parent = dataFile.getParentFile();
            if (parent != null && !parent.exists()) {
                if (!parent.mkdirs()) {
                    log.error("writeToFile(): Failed to create parent directory " + parent.getAbsolutePath());
                } else {
                    log.info("writeToFile(): Created parent directory " + parent.getAbsolutePath());
                }
            }
        }

        final XMLOutputFactory factory = XMLOutputFactory.newInstance();

        log.info("writeToFile(): Writing to " + dataFile.getAbsolutePath());
        final FileOutputStream outStream = new FileOutputStream(dataFile);
        writer = factory.createXMLStreamWriter(outStream, OUTPUT_ENCODING);

        writer.writeStartDocument(OUTPUT_ENCODING, "1.0");
        writer.writeStartElement("shoppinglists"); // <shoppinglists>
        synchronized (this.entries) {
            for (ShoppingList list : this.entries) {
                writer.writeStartElement("shoppinglist");
                writer.writeAttribute("title", list.getTitle());
                if (!StringUtils.isBlank(list.getDescription())) {
                    writer.writeStartElement("description");
                    writer.writeCharacters(list.getDescription());
                    writer.writeEndElement(); // </description>
                }

                writer.writeStartElement("entries");
                for (ShoppingListEntry entry : list.getEntries()) {
                    writer.writeStartElement("entry");
                    writer.writeAttribute("itemId", Long.toString(entry.getType().getId()));
                    writer.writeAttribute("totalQuantity", Long.toString(entry.getQuantity()));
                    writer.writeAttribute("purchasedQuantity", Long.toString(entry.getPurchasedQuantity()));

                    writer.writeEndElement(); // </entry>
                }
                writer.writeEndElement(); // </entries>
                writer.writeEndElement(); // </shoppinglist>
            }
        }
        writer.writeEndElement(); // </shoppinglists>
        writer.writeEndDocument();

        writer.flush();
        writer.close();
    } catch (FileNotFoundException e) {
        log.error("writeToFile(): Caught ", e);
        throw new RuntimeException("Unable to save shopping list to " + dataFile, e);
    } catch (XMLStreamException e) {
        log.error("writeToFile(): Caught ", e);
        throw new RuntimeException("Unable to save shopping list to " + dataFile, e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (XMLStreamException e) {
                log.error("writeToFile(): Caught ", e);
            }
        }
    }
}

From source file:de.escidoc.core.common.util.xml.XmlUtility.java

/**
 * Adds a new element to the provided {@code XMLStreamWriter} object containing a {@code String} value.
 *
 * @param writer         The {@code XMLStreamWriter} object to add the element to.
 * @param elementName    The name of the new element.
 * @param elementContent The {@code String} that shall be set as the value of the new element.
 * @param namespaceUri   The namespace URI of the new element.
 * @param createEmpty    Flag indicating if a an empty element shall be created if the provided data is
 *                       {@code null} ( {@code true} ), or if the element shall not be created (
 *                       {@code false} ).
 * @throws XMLStreamException Thrown in case of an xml stream error.
 *///from w ww.j  a  va  2 s.  co  m
public static void addElement(final XMLStreamWriter writer, final String elementName,
        final String elementContent, final String namespaceUri, final boolean createEmpty)
        throws XMLStreamException {
    if (elementContent == null) {
        if (createEmpty) {
            writer.writeEmptyElement(namespaceUri, elementName);
        }
    } else {
        writer.writeStartElement(namespaceUri, elementName);
        writer.writeCharacters(elementContent);
        writer.writeEndElement();
    }
}

From source file:de.escidoc.core.common.util.xml.XmlUtility.java

/**
 * Adds a new element to the provided {@code XMLStreamWriter} object containing a date value.
 *
 * @param writer         The {@code XMLStreamWriter} object to add the element to.
 * @param elementName    The name of the new element.
 * @param elementContent The {@code Date} that shall be set as the value of the new element.
 * @param namespaceUri   The namespace URI of the new element.
 * @param createEmpty    Flag indicating if a an empty element shall be created if the provided data is
 *                       {@code null} ( {@code true} ), or if the element shall not be created (
 *                       {@code false} ).
 * @throws XMLStreamException Thrown in case of an xml stream error.
 *///from  w w  w.  ja v  a  2  s  .  c om
public static void addElement(final XMLStreamWriter writer, final String elementName,
        final DateTime elementContent, final String namespaceUri, final boolean createEmpty)
        throws XMLStreamException {

    if (elementContent == null) {
        if (createEmpty) {
            writer.writeEmptyElement(namespaceUri, elementName);
        }
    } else {
        writer.writeStartElement(namespaceUri, elementName);
        writer.writeCharacters(elementContent.withZone(DateTimeZone.UTC).toString(Constants.TIMESTAMP_FORMAT));
        writer.writeEndElement();
    }
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Writes an entity to the stream as an AtomPub Entry Resource, leaving the stream open
 * for additional writing.//from  ww  w.  ja v a2  s  .c  o m
 * 
 * @param entity
 *            The instance implementing {@link TableEntity} to write to the output stream.
 * @param isTableEntry
 *            A flag indicating the entity is a reference to a table at the top level of the storage service when
 *            <code>true<code> and a reference to an entity within a table when <code>false</code>.
 * @param xmlw
 *            The <code>XMLStreamWriter</code> to write the entity to.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @throws XMLStreamException
 *             if an error occurs accessing the stream.
 * @throws StorageException
 *             if a Storage service error occurs.
 */
private static void writeAtomEntity(final TableEntity entity, final boolean isTableEntry,
        final XMLStreamWriter xmlw, final OperationContext opContext)
        throws XMLStreamException, StorageException {
    HashMap<String, EntityProperty> properties = entity.writeEntity(opContext);
    if (properties == null) {
        properties = new HashMap<String, EntityProperty>();
    }

    if (!isTableEntry) {
        Utility.assertNotNull(TableConstants.PARTITION_KEY, entity.getPartitionKey());
        Utility.assertNotNull(TableConstants.ROW_KEY, entity.getRowKey());
        Utility.assertNotNull(TableConstants.TIMESTAMP, entity.getTimestamp());
    }

    // Begin entry
    xmlw.writeStartElement("entry");
    xmlw.writeNamespace("d", ODataConstants.DATA_SERVICES_NS);
    xmlw.writeNamespace("m", ODataConstants.DATA_SERVICES_METADATA_NS);

    // default namespace
    xmlw.writeNamespace(null, ODataConstants.ATOM_NS);

    // Content
    xmlw.writeStartElement(ODataConstants.CONTENT);
    xmlw.writeAttribute(ODataConstants.TYPE, ODataConstants.ODATA_CONTENT_TYPE);

    // m:properties
    xmlw.writeStartElement("m", ODataConstants.PROPERTIES, ODataConstants.DATA_SERVICES_METADATA_NS);

    if (!isTableEntry) {
        // d:PartitionKey
        xmlw.writeStartElement("d", TableConstants.PARTITION_KEY, ODataConstants.DATA_SERVICES_NS);
        xmlw.writeAttribute("xml", "xml", "space", "preserve");
        xmlw.writeCharacters(entity.getPartitionKey());
        xmlw.writeEndElement();

        // d:RowKey
        xmlw.writeStartElement("d", TableConstants.ROW_KEY, ODataConstants.DATA_SERVICES_NS);
        xmlw.writeAttribute("xml", "xml", "space", "preserve");
        xmlw.writeCharacters(entity.getRowKey());
        xmlw.writeEndElement();

        // d:Timestamp
        if (entity.getTimestamp() == null) {
            entity.setTimestamp(new Date());
        }

        xmlw.writeStartElement("d", TableConstants.TIMESTAMP, ODataConstants.DATA_SERVICES_NS);
        xmlw.writeAttribute("m", ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE,
                EdmType.DATE_TIME.toString());
        xmlw.writeCharacters(Utility.getTimeByZoneAndFormat(entity.getTimestamp(), Utility.UTC_ZONE,
                Utility.ISO8061_LONG_PATTERN));
        xmlw.writeEndElement();
    }

    for (final Entry<String, EntityProperty> ent : properties.entrySet()) {
        if (ent.getKey().equals(TableConstants.PARTITION_KEY) || ent.getKey().equals(TableConstants.ROW_KEY)
                || ent.getKey().equals(TableConstants.TIMESTAMP) || ent.getKey().equals("Etag")) {
            continue;
        }

        EntityProperty currProp = ent.getValue();

        // d:PropName
        xmlw.writeStartElement("d", ent.getKey(), ODataConstants.DATA_SERVICES_NS);

        if (currProp.getEdmType() == EdmType.STRING) {
            xmlw.writeAttribute("xml", "xml", "space", "preserve");
        } else if (currProp.getEdmType().toString().length() != 0) {
            String edmTypeString = currProp.getEdmType().toString();
            if (edmTypeString.length() != 0) {
                xmlw.writeAttribute("m", ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE,
                        edmTypeString);
            }
        }

        if (currProp.getIsNull()) {
            xmlw.writeAttribute("m", ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.NULL,
                    Constants.TRUE);
        }

        // Write Value
        xmlw.writeCharacters(currProp.getValueAsString());
        // End d:PropName
        xmlw.writeEndElement();
    }

    // End m:properties
    xmlw.writeEndElement();

    // End content
    xmlw.writeEndElement();

    // End entry
    xmlw.writeEndElement();
}

From source file:edu.jhu.pha.vospace.node.Node.java

public String getXmlMetadata(Detail detail) {

    StringWriter jobWriter = new StringWriter();
    try {// w  ww.  j  a  va  2 s.  co  m
        XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(jobWriter);
        xsw.writeStartDocument();

        xsw.setDefaultNamespace(VOS_NAMESPACE);

        xsw.writeStartElement("node");
        xsw.writeNamespace("xsi", XSI_NAMESPACE);
        xsw.writeNamespace(null, VOS_NAMESPACE);
        xsw.writeAttribute("xsi:type", this.getType().getTypeName());
        xsw.writeAttribute("uri", this.getUri().toString());

        if (detail == Detail.max) {
            xsw.writeStartElement("properties");
            Map<String, String> properties = this.getMetastore().getProperties(this.getUri());
            properties.put(LENGTH_PROPERTY, Long.toString(getNodeInfo().getSize()));
            properties.put(DATE_PROPERTY, dropboxDateFormat.format(getNodeInfo().getMtime()));
            if (this.getType() == NodeType.DATA_NODE || this.getType() == NodeType.STRUCTURED_DATA_NODE
                    || this.getType() == NodeType.UNSTRUCTURED_DATA_NODE) {
                properties.put(CONTENTTYPE_PROPERTY, getNodeInfo().getContentType());
            }

            for (String propUri : properties.keySet()) {
                xsw.writeStartElement("property");
                xsw.writeAttribute("uri", propUri);
                xsw.writeCharacters(properties.get(propUri));
                xsw.writeEndElement();
            }

            xsw.writeEndElement();

            xsw.writeStartElement("accepts");
            xsw.writeEndElement();

            xsw.writeStartElement("provides");
            xsw.writeEndElement();

            xsw.writeStartElement("capabilities");
            xsw.writeEndElement();

            if (this.getType() == NodeType.CONTAINER_NODE) {
                NodesList childrenList = ((ContainerNode) this).getDirectChildren(false, 0, -1);
                List<Node> children = childrenList.getNodesList();

                xsw.writeStartElement("nodes");
                for (Node childNode : children) {
                    xsw.writeStartElement("node");
                    xsw.writeAttribute("uri", childNode.getUri().getId().toString());
                    xsw.writeEndElement();
                }
                xsw.writeEndElement();

            }

        }

        xsw.writeEndElement();

        xsw.writeEndDocument();
        xsw.close();
    } catch (XMLStreamException e) {
        e.printStackTrace();
        throw new InternalServerErrorException(e);
    }
    return jobWriter.getBuffer().toString();
}

From source file:com.liferay.portal.util.LocalizationImpl.java

private void _copyNonExempt(XMLStreamReader xmlStreamReader, XMLStreamWriter xmlStreamWriter,
        String exemptLanguageId, String defaultLanguageId, boolean cdata) throws XMLStreamException {

    while (xmlStreamReader.hasNext()) {
        int event = xmlStreamReader.next();

        if (event == XMLStreamConstants.START_ELEMENT) {
            String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID);

            if (Validator.isNull(languageId)) {
                languageId = defaultLanguageId;
            }/*from ww w .j av  a2 s.  c o  m*/

            if (!languageId.equals(exemptLanguageId)) {
                xmlStreamWriter.writeStartElement(xmlStreamReader.getLocalName());
                xmlStreamWriter.writeAttribute(_LANGUAGE_ID, languageId);

                while (xmlStreamReader.hasNext()) {
                    event = xmlStreamReader.next();

                    if ((event == XMLStreamConstants.CHARACTERS) || (event == XMLStreamConstants.CDATA)) {

                        String text = xmlStreamReader.getText();

                        if (cdata) {
                            xmlStreamWriter.writeCData(text);
                        } else {
                            xmlStreamWriter.writeCharacters(xmlStreamReader.getText());
                        }

                        break;
                    } else if (event == XMLStreamConstants.END_ELEMENT) {
                        break;
                    }
                }

                xmlStreamWriter.writeEndElement();
            }
        } else if (event == XMLStreamConstants.END_DOCUMENT) {
            break;
        }
    }
}

From source file:de.shadowhunt.subversion.internal.MergeOperation.java

@Override
protected HttpUriRequest createRequest() {
    final DavTemplateRequest request = new DavTemplateRequest("MERGE", repository);
    request.addHeader("X-SVN-Options", "release-locks");

    final Writer body = new StringBuilderWriter();
    try {//from w w  w .  j  a  v  a2  s . c om
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("merge");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        writer.writeStartElement("source");
        writer.writeStartElement("href");
        writer.writeCData(repository.getPath() + resource.getValue());
        writer.writeEndElement(); // href
        writer.writeEndElement(); // source
        writer.writeEmptyElement("no-auto-merge");
        writer.writeEmptyElement("no-checkout");
        writer.writeStartElement("prop");
        writer.writeEmptyElement("checked-in");
        writer.writeEmptyElement("version-name");
        writer.writeEmptyElement("resourcetype");
        writer.writeEmptyElement("creationdate");
        writer.writeEmptyElement("creator-displayname");
        writer.writeEndElement(); // prop
        if (!infoSet.isEmpty()) {
            writer.setPrefix(XmlConstants.SVN_PREFIX, XmlConstants.SVN_NAMESPACE);
            writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-token-list");
            writer.writeNamespace(XmlConstants.SVN_PREFIX, XmlConstants.SVN_NAMESPACE);
            for (final Info info : infoSet) {
                final String lockToken = info.getLockToken();
                assert (lockToken != null) : "must not be null";
                final Resource infoResource = info.getResource();

                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock");
                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-path");
                writer.writeCData(infoResource.getValueWithoutLeadingSeparator());
                writer.writeEndElement(); // lock-path
                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-token");
                writer.writeCharacters(lockToken);
                writer.writeEndElement(); // lock-token
                writer.writeEndElement(); // lock
            }
            writer.writeEndElement(); // lock-token-list
        }
        writer.writeEndElement(); // merge
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:de.uni_koblenz.jgralab.utilities.rsa2tg.SchemaGraph2XMI.java

/**
 * Creates the representation of one comment.
 * //  www. j av a  2 s . co m
 * @param writer
 *            {@link XMLStreamWriter} of the current XMI file
 * @param comment
 *            {@link Comment} which should be represented
 * @param id
 *            {@link String} the id of the created <code>ownedComment</code>
 *            tag, which represents <code>comment</code>
 * @param annotatedElement
 *            {@link String} qualified name of the {@link NamedElement}
 *            which is commented
 * @throws XMLStreamException
 */
private void createComment(XMLStreamWriter writer, Comment comment, String id, String annotatedElement)
        throws XMLStreamException {
    // start ownedComment
    writer.writeStartElement(XMIConstants4SchemaGraph2XMI.TAG_OWNEDCOMMENT);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
            XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_TYPE,
            XMIConstants4SchemaGraph2XMI.OWNEDCOMMENT_TYPE_VALUE);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.NAMESPACE_XMI,
            XMIConstants4SchemaGraph2XMI.XMI_ATTRIBUTE_ID, id);
    writer.writeAttribute(XMIConstants4SchemaGraph2XMI.OWNEDCOMMENT_ATTRIBUTE_ANNOTATEDELEMENT,
            annotatedElement);

    // start body
    writer.writeStartElement(XMIConstants4SchemaGraph2XMI.TAG_BODY);

    // write content
    writer.writeCharacters(XMIConstants4SchemaGraph2XMI.COMMENT_START
            + comment.get_text().replaceAll(Pattern.quote("\n"), XMIConstants4SchemaGraph2XMI.COMMENT_NEWLINE)
            + XMIConstants4SchemaGraph2XMI.COMMENT_END);

    // end body
    writer.writeEndElement();

    // end ownedComment
    writer.writeEndElement();
}

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java

/**
 * StAX for efficient streaming XML writing.
 * /*from w w w.ja va  2s  .com*/
 * @throws IOException
 * @throws XMLStreamException 
 */
private static void writeProfile(String dname, String fname) throws IOException, XMLStreamException {
    //create initial directory and file 
    File dir = new File(dname);
    if (!dir.exists())
        dir.mkdir();
    File f = new File(fname);
    f.createNewFile();

    FileOutputStream fos = new FileOutputStream(f);

    try {
        //create document
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(fos);
        //TODO use an alternative way for intentation
        //xsw = new IndentingXMLStreamWriter( xsw ); //remove this line if no indenting required

        //write document content
        xsw.writeStartDocument();
        xsw.writeStartElement(XML_PROFILE);
        xsw.writeAttribute(XML_DATE, String.valueOf(new Date()));

        //foreach instruction (boundle of cost functions)
        for (Entry<Integer, HashMap<Integer, CostFunction>> inst : _profile.entrySet()) {
            int instID = inst.getKey();
            String instName = _regInst_IDNames.get(instID);

            xsw.writeStartElement(XML_INSTRUCTION);
            xsw.writeAttribute(XML_ID, String.valueOf(instID));
            xsw.writeAttribute(XML_NAME, instName.replaceAll(Lop.OPERAND_DELIMITOR, " "));

            //foreach testdef cost function
            for (Entry<Integer, CostFunction> cfun : inst.getValue().entrySet()) {
                int tdefID = cfun.getKey();
                PerfTestDef def = _regTestDef.get(tdefID);
                CostFunction cf = cfun.getValue();

                xsw.writeStartElement(XML_COSTFUNCTION);
                xsw.writeAttribute(XML_ID, String.valueOf(tdefID));
                xsw.writeAttribute(XML_MEASURE, def.getMeasure().toString());
                xsw.writeAttribute(XML_VARIABLE, def.getVariable().toString());
                xsw.writeAttribute(XML_INTERNAL_VARIABLES, serializeTestVariables(def.getInternalVariables()));
                xsw.writeAttribute(XML_DATAFORMAT, def.getDataformat().toString());
                xsw.writeCharacters(serializeParams(cf.getParams()));
                xsw.writeEndElement();// XML_COSTFUNCTION
            }

            xsw.writeEndElement(); //XML_INSTRUCTION
        }

        xsw.writeEndElement();//XML_PROFILE
        xsw.writeEndDocument();
        xsw.close();
    } finally {
        IOUtilFunctions.closeSilently(fos);
    }
}

From source file:com.github.fritaly.graphml4j.LabelStyle.java

void writeTo(XMLStreamWriter writer, String label) throws XMLStreamException {
    Validate.notNull(writer, "The given stream writer is null");

    // y:NodeLabel
    writer.writeStartElement("y:NodeLabel");
    writer.writeAttribute("alignement", textAlignment.getValue());
    writer.writeAttribute("autoSizePolicy", sizePolicy.getValue());
    writer.writeAttribute("fontFamily", fontFamily);
    writer.writeAttribute("fontSize", Integer.toString(fontSize));
    writer.writeAttribute("fontStyle", fontStyle.getValue());
    writer.writeAttribute("modelName", placement.getValue());
    writer.writeAttribute("modelPosition", position.getValue());

    if (borderDistance != 0.0f) {
        writer.writeAttribute("borderDistance", String.format("%.1f", borderDistance));
    }/*from   ww  w . j  a  v a 2  s  .c  o m*/
    if (rotationAngle != 0.0f) {
        writer.writeAttribute("rotationAngle", String.format("%.1f", rotationAngle));
    }

    if (backgroundColor != null) {
        writer.writeAttribute("backgroundColor", Utils.encode(backgroundColor));
    } else {
        writer.writeAttribute("hasBackgroundColor", "false");
    }
    if (lineColor != null) {
        writer.writeAttribute("lineColor", Utils.encode(lineColor));
    } else {
        writer.writeAttribute("hasLineColor", "false");
    }
    if (hasInsets()) {
        writer.writeAttribute("bottomInset", Integer.toString(bottomInset));
        writer.writeAttribute("topInset", Integer.toString(topInset));
        writer.writeAttribute("leftInset", Integer.toString(leftInset));
        writer.writeAttribute("rightInset", Integer.toString(rightInset));
    }

    writer.writeAttribute("textColor", Utils.encode(textColor));
    writer.writeAttribute("visible", Boolean.toString(visible));

    if (underlinedText) {
        writer.writeAttribute("underlinedText", Boolean.toString(underlinedText));
    }

    writer.writeCharacters(label);
    writer.writeEndElement(); // </y:NodeLabel>
}