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(java.io.OutputStream stream, String encoding)
        throws XMLStreamException;

Source Link

Document

Create a new XMLStreamWriter that writes to a stream

Usage

From source file:Main.java

public static String convertBean2Xml(Object obj) throws IOException {
    String result = null;//from w  w w.  j ava 2  s  . c  o  m
    try {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(baos,
                (String) marshaller.getProperty(Marshaller.JAXB_ENCODING));
        xmlStreamWriter.writeStartDocument((String) marshaller.getProperty(Marshaller.JAXB_ENCODING), "1.0");
        marshaller.marshal(obj, xmlStreamWriter);
        xmlStreamWriter.writeEndDocument();
        xmlStreamWriter.close();
        result = baos.toString("UTF-8");

    } catch (JAXBException e) {
        e.printStackTrace();
        return null;
    } catch (XMLStreamException e) {
        e.printStackTrace();
        return null;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
    return result;
}

From source file:edu.vt.middleware.gator.util.StaxIndentationHandler.java

/**
 * Convenience method for creating a {@link XMLStreamWriter} that emits
 * indented output using an instance of this class.
 * /*from  w  w  w. j ava2 s.c o m*/
 * @param  out  Output stream that receives written XML.
 *
 * @return  Proxy to a {@link XMLStreamWriter} that has an instance of this
 * class as an invocation handler to provided indented output.
 * 
 * @throws  FactoryConfigurationError
 * On serious errors creating an XMLOutputFactory
 * @throws  XMLStreamException  On errors creating a an XMLStreamWriter from
 * the default factory.
 */
public static XMLStreamWriter createIndentingStreamWriter(final OutputStream out)
        throws XMLStreamException, FactoryConfigurationError {
    final XMLOutputFactory factory = XMLOutputFactory.newInstance();
    factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
    final XMLStreamWriter writer = factory.createXMLStreamWriter(out, "UTF-8");
    return (XMLStreamWriter) Proxy.newProxyInstance(XMLStreamWriter.class.getClassLoader(),
            new Class[] { XMLStreamWriter.class }, new StaxIndentationHandler(writer));
}

From source file:eu.esdihumboldt.hale.io.xslt.XslTransformationUtil.java

/**
 * Setup a XML writer configured with the namespace prefixes and UTF-8
 * encoding./* w w  w .j  av a  2 s.c  om*/
 * 
 * @param outStream the output stream to write the XML content to
 * @param namespaces the namespace context, e.g. as retrieved from a
 *            {@link XsltGenerationContext}
 * @return the XML stream writer
 * @throws XMLStreamException if an error occurs setting up the writer
 */
public static XMLStreamWriter setupXMLWriter(OutputStream outStream, NamespaceContext namespaces)
        throws XMLStreamException {
    // create and set-up a writer
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    // will set namespaces if these not set explicitly
    outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", //$NON-NLS-1$
            Boolean.valueOf(true));
    // create XML stream writer with UTF-8 encoding
    XMLStreamWriter tmpWriter = outputFactory.createXMLStreamWriter(outStream, "UTF-8"); //$NON-NLS-1$

    tmpWriter.setNamespaceContext(namespaces);

    return new IndentingXMLStreamWriter(tmpWriter);
}

From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. A static factory method to construct an <code>XMLStreamWriter</code> instance based on
 * the specified <code>OutputStream</code>.
 * //from   ww  w  .j  a v  a  2 s  . c  om
 * @param outStream
 *            The <code>OutputStream</code> instance to create an <code>XMLStreamWriter</code> on.
 * @return
 *         An <code>XMLStreamWriter</code> instance based on the specified <code>OutputStream</code>.
 * @throws XMLStreamException
 *             if an error occurs while creating the stream.
 */
protected static XMLStreamWriter generateTableWriter(final OutputStream outStream) throws XMLStreamException {
    final XMLOutputFactory xmlOutFactoryInst = XMLOutputFactory.newInstance();
    return xmlOutFactoryInst.createXMLStreamWriter(outStream, "UTF-8");
}

From source file:com.moviejukebox.writer.MovieJukeboxHTMLWriter.java

/**
 * Generate a simple jukebox index file from scratch
 *
 * @param jukebox//from w  w w .  j a  v  a 2 s.  c o  m
 * @param library
 */
private static void generateDefaultIndexHTML(Jukebox jukebox, Library library) {
    @SuppressWarnings("resource")
    OutputStream fos = null;
    XMLStreamWriter writer = null;

    try {
        File htmlFile = new File(jukebox.getJukeboxTempLocation(),
                PropertiesUtil.getProperty("mjb.indexFile", "index.htm"));
        FileTools.makeDirsForFile(htmlFile);

        fos = FileTools.createFileOutputStream(htmlFile);
        XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        writer = outputFactory.createXMLStreamWriter(fos, "UTF-8");

        String homePage = PropertiesUtil.getProperty("mjb.homePage", "");
        if (homePage.length() == 0) {
            String defCat = library.getDefaultCategory();
            if (defCat != null) {
                homePage = FileTools.createPrefix("Other",
                        HTMLTools.encodeUrl(FileTools.makeSafeFilename(defCat))) + "1";
            } else {
                // figure out something better to do here
                LOG.info("No categories were found, so you should specify mjb.homePage in the config file.");
            }
        }

        writer.writeStartDocument();
        writer.writeStartElement("html");
        writer.writeStartElement("head");

        writer.writeStartElement("meta");
        writer.writeAttribute("name", "YAMJ");
        writer.writeAttribute("content", "MovieJukebox");
        writer.writeEndElement();

        writer.writeStartElement("meta");
        writer.writeAttribute("HTTP-EQUIV", "Content-Type");
        writer.writeAttribute("content", "text/html; charset=UTF-8");
        writer.writeEndElement();

        writer.writeStartElement("meta");
        writer.writeAttribute("HTTP-EQUIV", "REFRESH");
        writer.writeAttribute("content", "0; url=" + jukebox.getDetailsDirName() + '/' + homePage + EXT_HTML);
        writer.writeEndElement();

        writer.writeEndElement();
        writer.writeEndElement();
    } catch (XMLStreamException | IOException ex) {
        LOG.error("Failed generating HTML library index: {}", ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (Exception ex) {
                LOG.trace("Failed to close XMLStreamWriter");
            }
        }

        if (fos != null) {
            try {
                fos.close();
            } catch (Exception ex) {
                LOG.trace("Failed to close FileOutputStream");
            }
        }
    }
}

From source file:diuf.unifr.ch.first.xwot.rxtx.notifications.JAXBEntity.java

@Override
public void writeTo(final OutputStream outstream) throws IOException {
    XMLOutputFactory xmloutputf = XMLOutputFactory.newInstance();
    try {//ww w .j av a2 s . c o  m
        XMLStreamWriter writer = xmloutputf.createXMLStreamWriter(outstream, "UTF-8");
        // do the actual writing using an appropriate Marshaller 
        // and do not forget to flush
        writer.flush();
    } catch (XMLStreamException ex) {
        // Re-throw appropriate i/o or runtime exception
        throw new IOException("Oppsie");
    }
}

From source file:com.norconex.committer.gsa.XmlOutput.java

public XmlOutput(OutputStream out) throws XMLStreamException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    writer = factory.createXMLStreamWriter(out, CharEncoding.UTF_8);
}

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

public final void writeRequest(OutputStream out) throws IOException {
    XMLOutputFactory f = XMLOutputFactory.newInstance();
    try {/*w  w  w .ja v 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:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Writes a single entity to the specified <code>OutputStream</code> as a complete XML
 * document.//  w w w. ja  v a 2s .  com
 * 
 * @param outStream
 *            The <code>OutputStream</code> to write the entity to.
 * @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 opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @throws XMLStreamException
 *             if an error occurs creating or accessing the stream.
 * @throws StorageException
 *             if a Storage service error occurs.
 */
private static void writeSingleAtomEntity(final OutputStream outStream, final TableEntity entity,
        final boolean isTableEntry, final OperationContext opContext)
        throws XMLStreamException, StorageException {
    final XMLOutputFactory xmlOutFactoryInst = XMLOutputFactory.newInstance();
    XMLStreamWriter xmlw = xmlOutFactoryInst.createXMLStreamWriter(outStream, Constants.UTF8_CHARSET);

    // default is UTF8
    xmlw.writeStartDocument(Constants.UTF8_CHARSET, "1.0");

    writeAtomEntity(entity, isTableEntry, xmlw, opContext);

    // end doc
    xmlw.writeEndDocument();
    xmlw.flush();
}

From source file:com.github.lindenb.jvarkit.tools.bam2xml.Bam2Xml.java

private int run(SamReader samReader) {
    OutputStream fout = null;// ww  w. j a  v  a  2 s . com
    SAMRecordIterator iter = null;
    XMLStreamWriter w = null;
    try {
        XMLOutputFactory xmlfactory = XMLOutputFactory.newInstance();

        if (getOutputFile() != null) {
            fout = IOUtils.openFileForWriting(getOutputFile());
            w = xmlfactory.createXMLStreamWriter(fout, "UTF-8");
        } else {
            w = xmlfactory.createXMLStreamWriter(stdout(), "UTF-8");
        }
        w.writeStartDocument("UTF-8", "1.0");
        final SAMFileHeader header = samReader.getFileHeader();
        final SAMXMLWriter xw = new SAMXMLWriter(w, header);
        final SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(header);
        iter = samReader.iterator();
        while (iter.hasNext()) {
            xw.addAlignment(progress.watch(iter.next()));
        }
        xw.close();
        w.writeEndDocument();
        if (fout != null)
            fout.flush();
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error(e);
        return -1;
    } finally {
        CloserUtil.close(w);
        CloserUtil.close(iter);
        CloserUtil.close(fout);
    }
    return 0;
}