Example usage for javax.xml.stream XMLOutputFactory createXMLStreamWriter

List of usage examples for javax.xml.stream XMLOutputFactory createXMLStreamWriter

Introduction

In this page you can find the example usage for javax.xml.stream XMLOutputFactory createXMLStreamWriter.

Prototype

public abstract XMLStreamWriter createXMLStreamWriter(Result result) throws XMLStreamException;

Source Link

Document

Create a new XMLStreamWriter that writes to a JAXP result.

Usage

From source file:com.fiorano.openesb.application.DmiObject.java

public void toXMLString(String fileName, boolean writeCDataSections) throws FioranoException {
    XMLOutputFactory outputFactory = XMLUtils.getStaxOutputFactory();
    //outputFactory.setProperty(XMLOutputFactory.INDENTATION, "/t");
    FileOutputStream fos = null;/* w  ww .  j  a  v a2s .  co  m*/
    XMLStreamWriter writer = null;
    try {
        try {
            fos = new FileOutputStream(fileName);
            writer = outputFactory.createXMLStreamWriter(fos);
            toJXMLString(writer, writeCDataSections);
            writer.flush();
        } finally {
            try {
                if (writer != null)
                    writer.close();
            } catch (XMLStreamException e) {
                // Ignore
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    } catch (XMLStreamException e) {
        throw new FioranoException(e);
    } catch (IOException e) {
        throw new FioranoException(e);
    }
}

From source file:com.fiorano.openesb.application.DmiObject.java

/**
 * Writes this object to specified filename
 * @param fileName file name/*from   w ww.j  av  a 2  s.  c o m*/
 * @throws FioranoException FioranoException
 */
public void toXMLString(String fileName) throws FioranoException {
    XMLOutputFactory outputFactory = XMLUtils.getStaxOutputFactory();
    //outputFactory.setProperty(XMLOutputFactory.INDENTATION, "/t");
    FileOutputStream fos = null;
    XMLStreamWriter writer = null;
    try {
        try {
            fos = new FileOutputStream(fileName);
            writer = outputFactory.createXMLStreamWriter(fos);
            toJXMLString(writer);
            writer.flush();
        } finally {
            try {
                if (writer != null)
                    writer.close();
            } catch (XMLStreamException e) {
                // Ignore
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    } catch (XMLStreamException e) {
        throw new FioranoException(e);
    } catch (IOException e) {
        throw new FioranoException(e);
    }

}

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

/**
 * This method creates the XMI file. Created content is:<br/>
 * <code>&lt;?xml version="{@link XMIConstants4SchemaGraph2XMI#XML_VERSION}" encoding="{@link XMIConstants4SchemaGraph2XMI#XML_ENCODING}"?&gt;<br/>
 * &lt;!-- content created by {@link SchemaGraph2XMI#createRootElement(XMLStreamWriter, SchemaGraph)} --&gt;
 * </code>/*from   w ww . j  a  va 2  s  .  c om*/
 * 
 * @param xmiName
 *            {@link String} the path of the XMI file
 * @param schemaGraph
 *            {@link SchemaGraph} to be converted into an XMI
 * @throws XMLStreamException
 * @throws IOException
 */
private void createXMI(String xmiName, SchemaGraph schemaGraph) throws XMLStreamException, IOException {
    Writer out = null;
    XMLStreamWriter writer = null;
    try {
        // create the XMLStreamWriter which creates the current xmi-file.
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmiName), "UTF-8"));
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        factory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.TRUE);
        writer = factory.createXMLStreamWriter(out);

        // write the first line
        writer.writeStartDocument(XMIConstants4SchemaGraph2XMI.XML_ENCODING,
                XMIConstants4SchemaGraph2XMI.XML_VERSION);
        createRootElement(writer, schemaGraph);
        // write the end of the document
        writer.writeEndDocument();

        // close the XMLStreamWriter
        writer.flush();
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // no handling of exceptions, because they are throw as mentioned in
        // the declaration.
        if (writer != null) {
            writer.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

private void sparqlQuery(String sparql, TripleStore ts, Map<String, String[]> params, String pathInfo,
        HttpServletResponse res) throws Exception {
    if (sparql == null) {
        Map err = error(SC_BAD_REQUEST, "No query specified.", null);
        output(err, params, pathInfo, res);
        return;/*from w w  w  .j a  v a 2s . c om*/
    } else {
        log.info("sparql: " + sparql);
    }

    // sparql query
    BindingIterator objs = ts.sparqlSelect(sparql);

    // start output
    String sparqlNS = "http://www.w3.org/2005/sparql-results#";
    res.setContentType("application/sparql-results+xml");
    OutputStream out = res.getOutputStream();
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    XMLStreamWriter stream = factory.createXMLStreamWriter(out);
    stream.setDefaultNamespace(sparqlNS);
    stream.writeStartDocument();
    stream.writeStartElement("sparql");

    // output bindings
    boolean headerWritten = false;
    while (objs.hasNext()) {
        Map<String, String> binding = objs.nextBinding();

        // write header on first binding
        if (!headerWritten) {
            Iterator<String> it = binding.keySet().iterator();
            stream.writeStartElement("head");
            while (it.hasNext()) {
                String k = it.next();
                stream.writeStartElement("variable");
                stream.writeAttribute("name", k);
                stream.writeEndElement();
            }
            stream.writeEndElement();
            stream.writeStartElement("results"); // ordered='false' distinct='false'
            headerWritten = true;
        }

        stream.writeStartElement("result");
        Iterator<String> it = binding.keySet().iterator();
        while (it.hasNext()) {
            String k = it.next();
            String v = binding.get(k);
            stream.writeStartElement("binding");
            stream.writeAttribute("name", k);
            String type = null;
            if (v.startsWith("\"") && v.endsWith("\"")) {
                type = "literal";
                v = v.substring(1, v.length() - 1);
            } else if (v.startsWith("_:")) {
                type = "bnode";
                v = v.substring(2);
            } else {
                type = "uri";
            }
            stream.writeStartElement(type);
            stream.writeCharacters(v);
            stream.writeEndElement();
            stream.writeEndElement();
        }
        stream.writeEndElement();
    }

    // finish output
    stream.writeEndElement();
    stream.writeEndDocument();
    stream.flush();
    stream.close();
}

From source file:nl.armatiek.xslweb.serializer.RequestSerializer.java

public String serializeToXML() throws Exception {
    StringWriter sw = new StringWriter();

    List<FileItem> fileItems = getMultipartContentItems();

    XMLOutputFactory output = XMLOutputFactory.newInstance();
    this.xsw = output.createXMLStreamWriter(sw);
    if (developmentMode) {
        this.xsw = new IndentingXMLStreamWriter(this.xsw);
    }/*from  w w w.ja  v  a2s. c o m*/

    xsw.writeStartDocument();
    xsw.setPrefix("req", URI);
    xsw.writeStartElement(URI, "request");
    xsw.writeNamespace("req", URI);

    serializeProperties();
    serializeHeaders();
    serializeParameters(fileItems);
    serializeBody(fileItems);
    serializeAttributes();
    serializeFileUploads(fileItems);
    serializeSession();
    serializeCookies();

    xsw.writeEndElement();
    xsw.writeEndDocument();

    return sw.toString();
}

From source file:nl.nn.adapterframework.extensions.svn.ScanTibcoSolutionPipe.java

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    StringWriter stringWriter = new StringWriter();
    XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
    XMLStreamWriter xmlStreamWriter;
    try {//  ww  w  .  ja  v  a 2s  . co  m
        xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(stringWriter);
        xmlStreamWriter.writeStartDocument();
        xmlStreamWriter.writeStartElement("root");
        xmlStreamWriter.writeAttribute("url", getUrl());
        // xmlStreamWriter.writeAttribute("level",
        // String.valueOf(getLevel()));
        process(xmlStreamWriter, getUrl(), getLevel());
        xmlStreamWriter.writeEndDocument();
        xmlStreamWriter.flush();
        xmlStreamWriter.close();
    } catch (XMLStreamException e) {
        throw new PipeRunException(this, "XMLStreamException", e);
    } catch (DomBuilderException e) {
        throw new PipeRunException(this, "DomBuilderException", e);
    } catch (XPathExpressionException e) {
        throw new PipeRunException(this, "XPathExpressionException", e);
    }

    return new PipeRunResult(getForward(), stringWriter.getBuffer().toString());
}

From source file:nz.co.jsrsolutions.ds3.test.RetrieveTestData.java

public static void main(String[] args) {

    logger.info("Starting application [ rtd ] ...");

    try {//  w  ww  . j a  v a2 s  . c  o  m

        config.addConfiguration(
                new XMLConfiguration(RetrieveTestData.class.getClassLoader().getResource(CONFIG_FILENAME)));

        HierarchicalConfiguration appConfig = config.configurationAt(APPLICATION_CONFIG_ROOT);

        EodDataProvider eodDataProvider = null;

        OutputStream out = new FileOutputStream(OUTPUT_FILENAME);
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);

        eodDataProvider = EodDataProviderFactory.create(appConfig, EODDATA_PROVIDER_NAME);

        writer.writeStartDocument("utf-8", "1.0");
        writer.writeCharacters(NEWLINE);
        writer.writeComment("Test data for running DataScraper unit tests against");
        writer.writeCharacters(NEWLINE);

        writer.setPrefix(XML_PREFIX, XML_NAMESPACE_URI);

        writer.writeStartElement(XML_NAMESPACE_URI, TESTDATA_LOCALNAME);
        writer.writeNamespace(XML_PREFIX, XML_NAMESPACE_URI);
        writer.writeCharacters(NEWLINE);

        serializeExchanges(eodDataProvider, writer);
        serializeSymbols(eodDataProvider, writer);
        serializeQuotes(eodDataProvider, writer);

        writer.writeEndElement();
        writer.writeCharacters(NEWLINE);
        writer.writeEndDocument();
        writer.flush();
        writer.close();

    } catch (ConfigurationException ce) {

        logger.error(ce.toString());
        ce.printStackTrace();

    } catch (Exception e) {

        logger.error(e.toString());
        logger.error(e);

    }

    logger.info("Exiting application [ rtd ] ...");

}

From source file:org.activiti.bpmn.converter.BpmnXMLConverter.java

public byte[] convertToXML(BpmnModel model, String encoding) {
    try {/*  w w w  .ja v  a2 s  .com*/

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        OutputStreamWriter out = new OutputStreamWriter(outputStream, encoding);

        XMLStreamWriter writer = xof.createXMLStreamWriter(out);
        XMLStreamWriter xtw = new IndentingXMLStreamWriter(writer);

        DefinitionsRootExport.writeRootElement(model, xtw, encoding);
        SignalAndMessageDefinitionExport.writeSignalsAndMessages(model, xtw);
        PoolExport.writePools(model, xtw);

        for (Process process : model.getProcesses()) {

            if (process.getFlowElements().size() == 0 && process.getLanes().size() == 0) {
                // empty process, ignore it 
                continue;
            }

            ProcessExport.writeProcess(process, xtw);

            for (FlowElement flowElement : process.getFlowElements()) {
                createXML(flowElement, model, xtw);
            }

            for (Artifact artifact : process.getArtifacts()) {
                createXML(artifact, model, xtw);
            }

            // end process element
            xtw.writeEndElement();
        }

        BPMNDIExport.writeBPMNDI(model, xtw);

        // end definitions root element
        xtw.writeEndElement();
        xtw.writeEndDocument();

        xtw.flush();

        outputStream.close();

        xtw.close();

        return outputStream.toByteArray();

    } catch (Exception e) {
        LOGGER.error("Error writing BPMN XML", e);
        throw new XMLException("Error writing BPMN XML", e);
    }
}

From source file:org.activiti.dmn.xml.converter.DmnXMLConverter.java

public byte[] convertToXML(DmnDefinition model, String encoding) {
    try {//w  w  w  .j a  v a  2  s.c  o m

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        OutputStreamWriter out = new OutputStreamWriter(outputStream, encoding);

        XMLStreamWriter writer = xof.createXMLStreamWriter(out);
        XMLStreamWriter xtw = new IndentingXMLStreamWriter(writer);

        xtw.writeStartElement(ELEMENT_DEFINITIONS);
        xtw.writeDefaultNamespace(DMN_NAMESPACE);
        xtw.writeAttribute(ATTRIBUTE_ID, model.getId());
        if (StringUtils.isNotEmpty(model.getName())) {
            xtw.writeAttribute(ATTRIBUTE_NAME, model.getName());
        }
        xtw.writeAttribute(ATTRIBUTE_NAMESPACE, MODEL_NAMESPACE);

        DmnXMLUtil.writeElementDescription(model, xtw);
        DmnXMLUtil.writeExtensionElements(model, xtw);

        for (ItemDefinition itemDefinition : model.getItemDefinitions()) {
            xtw.writeStartElement(ELEMENT_ITEM_DEFINITION);
            xtw.writeAttribute(ATTRIBUTE_ID, itemDefinition.getId());
            if (StringUtils.isNotEmpty(itemDefinition.getName())) {
                xtw.writeAttribute(ATTRIBUTE_NAME, itemDefinition.getName());
            }

            DmnXMLUtil.writeElementDescription(itemDefinition, xtw);
            DmnXMLUtil.writeExtensionElements(itemDefinition, xtw);

            xtw.writeStartElement(ELEMENT_TYPE_DEFINITION);
            xtw.writeCharacters(itemDefinition.getTypeDefinition());
            xtw.writeEndElement();

            xtw.writeEndElement();
        }

        for (Decision decision : model.getDrgElements()) {
            xtw.writeStartElement(ELEMENT_DECISION);
            xtw.writeAttribute(ATTRIBUTE_ID, decision.getId());
            if (StringUtils.isNotEmpty(decision.getName())) {
                xtw.writeAttribute(ATTRIBUTE_NAME, decision.getName());
            }

            DmnXMLUtil.writeElementDescription(decision, xtw);
            DmnXMLUtil.writeExtensionElements(decision, xtw);

            DecisionTable decisionTable = decision.getDecisionTable();
            xtw.writeStartElement(ELEMENT_DECISION_TABLE);
            xtw.writeAttribute(ATTRIBUTE_ID, decisionTable.getId());

            if (decisionTable.getHitPolicy() != null) {
                xtw.writeAttribute(ATTRIBUTE_HIT_POLICY, decisionTable.getHitPolicy().toString());
            }

            DmnXMLUtil.writeElementDescription(decisionTable, xtw);
            DmnXMLUtil.writeExtensionElements(decisionTable, xtw);

            for (InputClause clause : decisionTable.getInputs()) {
                xtw.writeStartElement(ELEMENT_INPUT_CLAUSE);
                if (StringUtils.isNotEmpty(clause.getId())) {
                    xtw.writeAttribute(ATTRIBUTE_ID, clause.getId());
                }
                if (StringUtils.isNotEmpty(clause.getLabel())) {
                    xtw.writeAttribute(ATTRIBUTE_LABEL, clause.getLabel());
                }

                DmnXMLUtil.writeElementDescription(clause, xtw);
                DmnXMLUtil.writeExtensionElements(clause, xtw);

                if (clause.getInputExpression() != null) {
                    xtw.writeStartElement(ELEMENT_INPUT_EXPRESSION);
                    xtw.writeAttribute(ATTRIBUTE_ID, clause.getInputExpression().getId());

                    if (StringUtils.isNotEmpty(clause.getInputExpression().getTypeRef())) {
                        xtw.writeAttribute(ATTRIBUTE_TYPE_REF, clause.getInputExpression().getTypeRef());
                    }

                    if (StringUtils.isNotEmpty(clause.getInputExpression().getText())) {
                        xtw.writeStartElement(ELEMENT_TEXT);
                        xtw.writeCharacters(clause.getInputExpression().getText());
                        xtw.writeEndElement();
                    }

                    xtw.writeEndElement();
                }

                xtw.writeEndElement();
            }

            for (OutputClause clause : decisionTable.getOutputs()) {
                xtw.writeStartElement(ELEMENT_OUTPUT_CLAUSE);
                if (StringUtils.isNotEmpty(clause.getId())) {
                    xtw.writeAttribute(ATTRIBUTE_ID, clause.getId());
                }
                if (StringUtils.isNotEmpty(clause.getLabel())) {
                    xtw.writeAttribute(ATTRIBUTE_LABEL, clause.getLabel());
                }
                if (StringUtils.isNotEmpty(clause.getName())) {
                    xtw.writeAttribute(ATTRIBUTE_NAME, clause.getName());
                }
                if (StringUtils.isNotEmpty(clause.getTypeRef())) {
                    xtw.writeAttribute(ATTRIBUTE_TYPE_REF, clause.getTypeRef());
                }

                DmnXMLUtil.writeElementDescription(clause, xtw);
                DmnXMLUtil.writeExtensionElements(clause, xtw);

                xtw.writeEndElement();
            }

            for (DecisionRule rule : decisionTable.getRules()) {
                xtw.writeStartElement(ELEMENT_RULE);
                if (StringUtils.isNotEmpty(rule.getId())) {
                    xtw.writeAttribute(ATTRIBUTE_ID, rule.getId());
                }

                DmnXMLUtil.writeElementDescription(rule, xtw);
                DmnXMLUtil.writeExtensionElements(rule, xtw);

                for (RuleInputClauseContainer container : rule.getInputEntries()) {
                    xtw.writeStartElement(ELEMENT_INPUT_ENTRY);
                    xtw.writeAttribute(ATTRIBUTE_ID, container.getInputEntry().getId());

                    xtw.writeStartElement(ELEMENT_TEXT);
                    xtw.writeCharacters(container.getInputEntry().getText());
                    xtw.writeEndElement();

                    xtw.writeEndElement();
                }

                for (RuleOutputClauseContainer container : rule.getOutputEntries()) {
                    xtw.writeStartElement(ELEMENT_OUTPUT_ENTRY);
                    xtw.writeAttribute(ATTRIBUTE_ID, container.getOutputEntry().getId());

                    xtw.writeStartElement(ELEMENT_TEXT);
                    xtw.writeCharacters(container.getOutputEntry().getText());
                    xtw.writeEndElement();

                    xtw.writeEndElement();
                }

                xtw.writeEndElement();
            }

            xtw.writeEndElement();

            xtw.writeEndElement();
        }

        // end definitions root element
        xtw.writeEndElement();
        xtw.writeEndDocument();

        xtw.flush();

        outputStream.close();

        xtw.close();

        return outputStream.toByteArray();

    } catch (Exception e) {
        LOGGER.error("Error writing BPMN XML", e);
        throw new DmnXMLException("Error writing BPMN XML", e);
    }
}