Example usage for javax.xml.stream XMLOutputFactory newInstance

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

Introduction

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

Prototype

public static XMLOutputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

/**
 * {@inheritDoc }//  www .  ja v a 2  s.c om
 */
@Override
protected InputStream addLinks(final String entitySetName, final String entitykey, final InputStream is,
        final Set<String> links) throws Exception {

    // -----------------------------------------
    // 0. Build reader and writer
    // -----------------------------------------
    final XMLEventReader reader = getEventReader(is);
    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);
    // -----------------------------------------

    final XmlElement entry = getAtomElement(reader, writer, "entry");
    writer.add(entry.getStart());

    // add for links
    for (String link : links) {
        final Set<Attribute> attributes = new HashSet<Attribute>();
        attributes.add(eventFactory.createAttribute(new QName("title"), link));
        attributes.add(eventFactory.createAttribute(new QName("href"),
                Commons.getLinksURI(version, entitySetName, entitykey, link)));
        attributes.add(eventFactory.createAttribute(new QName("rel"), Constants.ATOM_LINK_REL + link));
        attributes.add(eventFactory.createAttribute(new QName("type"),
                Commons.linkInfo.get(version).isFeed(entitySetName, link) ? Constants.ATOM_LINK_FEED
                        : Constants.ATOM_LINK_ENTRY));

        writer.add(eventFactory.createStartElement(new QName(LINK), attributes.iterator(), null));
        writer.add(eventFactory.createEndElement(new QName(LINK), null));
    }

    writer.add(entry.getContentReader());
    writer.add(entry.getEnd());
    writer.add(reader);
    IOUtils.closeQuietly(is);

    writer.flush();
    writer.close();
    reader.close();

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:de.uzk.hki.da.model.ObjectPremisXmlWriter.java

/**
 * Note: On its way writing the PREMIS file all the previously created jhove files get integrated into the resulting file. This
 * can't be done outside and passed as object attributes because it can be potentially very big and cause memory issues.
 *
 * @param object the object// w w  w  .ja va 2  s. c o  m
 * @param f the f
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void serialize(Object object, File f, Path jhoveDataPath) throws IOException {
    if ((object.getPackages() == null) || (object.getPackages().isEmpty()))
        throw new IllegalStateException("No Packages set");
    if (object.getIdentifier() == null)
        throw new IllegalStateException("object identifier is null");
    if (object.getContractor() == null)
        throw new IllegalStateException("object has no contractor");
    if (object.getOrig_name() == null)
        throw new IllegalStateException("object has no orig name");

    this.jhoveDataPath = jhoveDataPath;
    agents = new HashSet<Agent>();

    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    FileOutputStream outputStream = new FileOutputStream(f);

    try {
        writer = outputFactory.createXMLStreamWriter(outputStream, C.ENCODING_UTF_8);
    } catch (XMLStreamException e) {
        throw new IOException("Failed to create XMLStreamWriter", e);
    }

    try {
        writer.writeStartDocument(C.ENCODING_UTF_8, "1.0");
        writer.setPrefix("xsi", C.XSI_NS);

        createOpenElement("premis", 0);
        createAttribute(C.XSI_NS, "schemaLocation",
                "info:lc/xmlns/premis-v2 http://www.loc.gov/standards/premis/v2/premis-v2-2.xsd");
        createAttribute("version", "2.2");
        createAttribute("xmlns", "info:lc/xmlns/premis-v2");
        createAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

        createObjectElement(object.getIdentifier(), object.getUrn(), object.getOrig_name());

        for (Package pkg : object.getPackages())
            createPackageElement(object, pkg);

        // generate files
        for (Package pkg : object.getPackages())
            for (DAFile fi : pkg.getFiles())
                createFileElement(fi, object, pkg);

        generateEvents(object);

        for (Agent a : agents)
            createAgentElement(object, a);

        createOpenElement("rights", 1);
        generateRightsStatementElement(object.getRights());
        createOpenElement("rightsExtension", 2);
        generateRightsGrantedElement(object, object.getRights());

        createCloseElement(2);
        createCloseElement(1);

        createCloseElement(0);

        writer.writeDTD("\n");
        writer.writeEndDocument();
        writer.close();
        outputStream.close();

    } catch (XMLStreamException e) {
        throw new RuntimeException("Failed to serialize premis.xml", e);
    }

}

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

/**
 * Setup a XML writer configured with the namespace prefixes and UTF-8
 * encoding.//ww w.  j  a  v a  2s .co m
 * 
 * @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.hpe.application.automation.tools.octane.tests.xml.TestResultXmlWriter.java

private void initialize(ResultFields resultFields)
        throws IOException, InterruptedException, XMLStreamException {
    if (outputStream == null) {
        outputStream = targetPath.write();
        writer = XMLOutputFactory.newInstance().createXMLStreamWriter(outputStream);
        writer.writeStartDocument();//w  w w .  j a va  2 s. c o  m

        writer.writeStartElement("test_result");
        writer.writeStartElement("build");
        writer.writeAttribute("server_id", ConfigurationService.getModel().getIdentity());
        writer.writeAttribute("job_id", buildDescriptor.getJobId());
        writer.writeAttribute("job_name", buildDescriptor.getJobName());
        writer.writeAttribute("build_id", buildDescriptor.getBuildId());
        writer.writeAttribute("build_name", buildDescriptor.getBuildName());
        if (!StringUtils.isEmpty(buildDescriptor.getSubType())) {
            writer.writeAttribute("sub_type", buildDescriptor.getSubType());
        }
        writer.writeEndElement(); // build
        writeFields(resultFields);
        writer.writeStartElement("test_runs");
    }
}

From source file:com.mtgi.analytics.JdbcBehaviorEventPersisterImpl.java

@Override
protected void initDao() throws Exception {
    super.initDao();
    this.xmlFactory = XMLOutputFactory.newInstance();
}

From source file:com.norconex.collector.core.filter.impl.ExtensionReferenceFilter.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {//from   w w  w  .  j av  a 2s .  c o m
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("filter");
        writer.writeAttribute("class", getClass().getCanonicalName());
        saveToXML(writer);
        writer.writeAttribute("caseSensitive", Boolean.toString(caseSensitive));
        writer.writeCharacters(extensions);
        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:com.norconex.committer.core.impl.MultiCommitter.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {/*  w w w. j a va 2s  .c  o m*/
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("committer");
        writer.writeAttribute("class", getClass().getCanonicalName());
        for (ICommitter committer : committers) {
            writer.flush();
            if (!(committer instanceof IXMLConfigurable)) {
                LOG.error("Cannot save committer to XML as it does not " + "implement IXMLConfigurable: "
                        + committer);
            }
            ((IXMLConfigurable) committer).saveToXML(out);
        }
        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:io.mapzone.arena.csw.CswRequest.java

@Override
public R execute(IProgressMonitor monitor) throws Exception {
    assert writer == null && buf == null;
    buf = new ByteArrayOutputStream(4096);
    writer = XMLOutputFactory.newInstance().createXMLStreamWriter(buf, DEFAULT_XML_ENCODING);
    writer = new IndentingXMLStreamWriter(writer);

    // write content
    out().writeStartDocument(DEFAULT_XML_ENCODING, "1.0");
    writeRequest();//from   w ww  . j av  a2 s .  c  om
    prepare(monitor);
    out().writeEndElement();
    out().writeEndDocument();
    out().flush();

    String content = buf.toString(DEFAULT_XML_ENCODING);
    log.info(content);

    // execute POST
    // XXX streaming content would be cool, but probably waste of effort
    HttpPost post = new HttpPost(baseUrl.get());
    StringEntity entity = new StringEntity(content, DEFAULT_XML_ENCODING);
    entity.setContentType("application/xml");
    post.setEntity(entity);

    // read response
    try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.get().execute(post);
            InputStream in = response.getEntity().getContent();) {
        // check return code
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) {
            throw new IOException(status.getReasonPhrase() + " (" + status.getStatusCode() + ")");
        }

        // handle response
        System.out.print("RESPONSE: ");
        TeeInputStream tee = new TeeInputStream(in, System.out);
        return handleResponse(tee, monitor);
    } finally {
        writer = null;
        buf = null;
    }
}

From source file:com.norconex.collector.http.sitemap.impl.DefaultSitemapResolver.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {//from  w  w  w  .j  av a 2  s.c o m
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("sitemap");
        writer.writeAttribute("class", getClass().getCanonicalName());
        writer.writeAttribute("lenient", Boolean.toString(lenient));
        if (sitemapLocations != null) {
            for (String location : sitemapLocations) {
                writer.writeStartElement("location");
                writer.writeCharacters(location);
                writer.writeEndElement();
            }
        }
        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:com.norconex.collector.core.filter.impl.RegexMetadataFilter.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {// w w w .j av a2 s  .c  om
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("filter");
        writer.writeAttribute("class", getClass().getCanonicalName());
        super.saveToXML(writer);
        writer.writeAttribute("caseSensitive", Boolean.toString(caseSensitive));
        writer.writeAttribute("field", field);
        writer.writeCharacters(regex == null ? "" : regex);
        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}