Example usage for javax.xml.stream XMLOutputFactory setProperty

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

Introduction

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

Prototype

public abstract void setProperty(java.lang.String name, Object value) throws IllegalArgumentException;

Source Link

Document

Allows the user to set specific features/properties on the underlying implementation.

Usage

From source file:MainClass.java

public static void main(String[] args) throws XMLStreamException {
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
    XMLStreamWriter writer = outputFactory.createXMLStreamWriter(System.out);
    writer.writeStartDocument("1.0");

    writer.writeStartElement("http://www.t.com/f", "sample");

    writer.writeAttribute("attribute", "true");
    writer.writeAttribute("http://www.t.com/f", "attribute2", "false");
    writer.writeCharacters("some text");
    writer.writeCData("<test>");
    writer.writeEndElement();//from w ww.  ja  v  a2s. c om
    writer.writeEndDocument();
    writer.flush();
}

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  a v  a2s .  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.//ww  w.j ava 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:org.elasticsearch.discovery.ec2.Ec2DiscoveryClusterFormationTests.java

/**
 * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
 */// w w w  .  j a  va  2  s.  c om
@BeforeClass
public static void startHttpd() throws Exception {
    logDir = createTempDir();
    httpServer = MockHttpServer
            .createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);

    httpServer.createContext("/", (s) -> {
        Headers headers = s.getResponseHeaders();
        headers.add("Content-Type", "text/xml; charset=UTF-8");
        String action = null;
        for (NameValuePair parse : URLEncodedUtils.parse(IOUtils.toString(s.getRequestBody()),
                StandardCharsets.UTF_8)) {
            if ("Action".equals(parse.getName())) {
                action = parse.getValue();
                break;
            }
        }
        assertThat(action, equalTo("DescribeInstances"));

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
        xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
        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");
                {
                    Path[] files = FileSystemUtils.files(logDir);
                    for (int i = 0; i < files.length; i++) {
                        Path resolve = files[i].resolve("transport.ports");
                        if (Files.exists(resolve)) {
                            List<String> addresses = Files.readAllLines(resolve);
                            Collections.shuffle(addresses, random());

                            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(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("dnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        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(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("ipAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();

            sw.writeEndDocument();
            sw.flush();

            final byte[] responseAsBytes = out.toString().getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(200, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        } catch (XMLStreamException e) {
            Loggers.getLogger(Ec2DiscoveryClusterFormationTests.class).error("Failed serializing XML", e);
            throw new RuntimeException(e);
        }
    });

    httpServer.start();
}

From source file:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java

@Override
protected Collection<Throwable> call(String inputName) throws Exception {

    final CompiledScript compiledScript;
    Unmarshaller unmarshaller;/*from  w  w  w . j  a va  2  s. c  o  m*/
    Marshaller marshaller;
    try {
        compiledScript = super.compileJavascript();

        JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast");

        unmarshaller = jc.createUnmarshaller();
        marshaller = jc.createMarshaller();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        PrintWriter pw = openFileOrStdoutAsPrintWriter();
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
        XMLEventWriter w = xof.createXMLEventWriter(pw);

        StreamSource src = null;
        if (inputName == null) {
            LOG.info("Reading stdin");
            src = new StreamSource(stdin());
        } else {
            LOG.info("Reading file " + inputName);
            src = new StreamSource(new File(inputName));
        }

        XMLEventReader r = xmlInputFactory.createXMLEventReader(src);

        XMLEventFactory eventFactory = XMLEventFactory.newFactory();

        SimpleBindings bindings = new SimpleBindings();
        while (r.hasNext()) {
            XMLEvent evt = r.peek();
            switch (evt.getEventType()) {
            case XMLEvent.START_ELEMENT: {
                StartElement sE = evt.asStartElement();
                Hit hit = null;
                JAXBElement<Hit> jaxbElement = null;
                if (sE.getName().getLocalPart().equals("Hit")) {
                    jaxbElement = unmarshaller.unmarshal(r, Hit.class);
                    hit = jaxbElement.getValue();
                } else {
                    w.add(r.nextEvent());
                    break;
                }

                if (hit != null) {

                    bindings.put("hit", hit);

                    boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings);

                    if (accept) {
                        marshaller.marshal(jaxbElement, w);
                        w.add(eventFactory.createCharacters("\n"));
                    }
                }

                break;
            }
            case XMLEvent.SPACE:
                break;
            default: {
                w.add(r.nextEvent());
                break;
            }
            }
            r.close();
        }
        w.flush();
        w.close();
        pw.flush();
        pw.close();
        return RETURN_OK;
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}

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

/**
 * Generates a XML response that describe the EC2 instances
 *//* w  w  w.java  2  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.marklogic.client.impl.CombinedQueryBuilderImpl.java

private XMLStreamWriter makeXMLSerializer(OutputStream out) {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

    try {/*from w ww .j a  v  a 2 s .c o m*/
        XMLStreamWriter serializer = factory.createXMLStreamWriter(out, "UTF-8");

        serializer.setDefaultNamespace("http://marklogic.com/appservices/search");
        serializer.setPrefix("xs", XMLConstants.W3C_XML_SCHEMA_NS_URI);

        return serializer;
    } catch (Exception e) {
        throw new MarkLogicIOException(e);
    }
}

From source file:ca.uhn.fhir.util.XmlUtil.java

private static XMLOutputFactory getOrCreateFragmentOutputFactory() throws FactoryConfigurationError {
    XMLOutputFactory retVal = ourFragmentOutputFactory;
    if (retVal == null) {
        retVal = createOutputFactory();/*  ww w  .  ja v a  2  s .c om*/
        retVal.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
        ourFragmentOutputFactory = retVal;
        return retVal;
    }
    return retVal;
}

From source file:ca.uhn.fhir.util.XmlUtil.java

private static XMLOutputFactory createOutputFactory() throws FactoryConfigurationError {
    try {/*from w  ww.j  av a 2  s.co  m*/
        // Detect if we're running with the Android lib, and force repackaged Woodstox to be used
        Class.forName("ca.uhn.fhir.repackage.javax.xml.stream.XMLOutputFactory");
        System.setProperty("javax.xml.stream.XMLOutputFactory", "com.ctc.wstx.stax.WstxOutputFactory");
    } catch (ClassNotFoundException e) {
        // ok
    }

    XMLOutputFactory outputFactory = newOutputFactory();

    if (!ourHaveLoggedStaxImplementation) {
        logStaxImplementation(outputFactory.getClass());
    }

    /*
     * Note that these properties are Woodstox specific and they cause a crash in environments where SJSXP is
     * being used (e.g. glassfish) so we don't set them there.
     */
    try {
        Class.forName("com.ctc.wstx.stax.WstxOutputFactory");
        if (outputFactory instanceof WstxOutputFactory) {
            outputFactory.setProperty(XMLOutputFactory2.P_TEXT_ESCAPER, new MyEscaper());
        }
    } catch (ClassNotFoundException e) {
        ourLog.debug("WstxOutputFactory (Woodstox) not found on classpath");
    }
    return outputFactory;
}

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

/**
 * Gets an initilized {@code XMLOutputFactory2} instance.<br/> The returned instance is initialized as follows:
 * <ul> <li>If the provided parameter is set to {@code true}, IS_REPAIRING_NAMESPACES is set to true, i.e. the
 * created writers will automatically repair the namespaces, see {@code XMLOutputFactory} for details.</li>
 * <li>For writing escaped attribute values, the {@link StaxAttributeEscapingWriterFactory} is used<./li> <li>For
 * writing escaped text content, the {@link StaxTextEscapingWriterFactory} is used.</li> </ul>
 *
 * @param repairing Flag indicating if the factory shall create namespace repairing writers ({@code true}) or
 *                  non repairing writers ({@code false}).
 * @return Returns the initalized {@code XMLOutputFactory} instance.
 *///from w  ww . j  a v  a2  s. c o  m
private static XMLOutputFactory getInitilizedXmlOutputFactory(final boolean repairing) {
    final XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
    xmlof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, repairing);
    if (repairing) {
        xmlof.setProperty(XMLOutputFactory2.P_AUTOMATIC_NS_PREFIX, "ext");
    }
    xmlof.setProperty(XMLOutputFactory2.P_ATTR_VALUE_ESCAPER, new StaxAttributeEscapingWriterFactory());
    xmlof.setProperty(XMLOutputFactory2.P_TEXT_ESCAPER, new StaxTextEscapingWriterFactory());
    return xmlof;
}