Example usage for javax.xml.stream XMLOutputFactory IS_REPAIRING_NAMESPACES

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

Introduction

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

Prototype

String IS_REPAIRING_NAMESPACES

To view the source code for javax.xml.stream XMLOutputFactory IS_REPAIRING_NAMESPACES.

Click Source Link

Document

Property used to set prefix defaulting on the output side

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();//w  w w . j av a 2 s .  c o m
    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  ww . ja va2  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:org.elasticsearch.discovery.ec2.AmazonEC2Fixture.java

/**
 * Generates a XML response that describe the EC2 instances
 *///from w  w  w.  j  a v a  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.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  av  a  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.Ec2DiscoveryClusterFormationTests.java

/**
 * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
 */// w w  w. ja  va 2s  .c o  m
@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.marklogic.client.impl.CombinedQueryBuilderImpl.java

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

    try {/*  w w w .  ja v  a  2 s.c om*/
        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:org.javelin.sws.ext.bind.SweJaxbMarshaller.java

/**
 * The main marshal method which converts an object into a series of {@link XMLEventWriter XML events} being added to {@link XMLEventWriter}.
 * /*from w  w w  .j  a v  a  2 s. co  m*/
 * @param jaxbElement
 * @param writer
 */
private void marshal0(Object jaxbElement, XMLEventWriter writer) throws JAXBException {
    ElementPattern<?> pattern = this.determineXmlPattern(jaxbElement);
    try {
        if (this.formatting)
            writer = new IndentingXMLEventWriter(writer);

        if (!this.fragment)
            writer.add(XmlEventsPattern.XML_EVENTS_FACTORY.createStartDocument(this.encoding, "1.0", true));

        MarshallingContext context = new MarshallingContext();
        // TODO: correctly handle internal xmlOutputFactory's IS_REPAIRING_NAMESPACES property!
        context.setRepairingXmlEventWriter(
                (Boolean) this.xmlOutputFactory.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES));
        context.setMultiRefEncoding(this.multiRefEncoding);
        context.setSendTypes(this.sendTypes);

        // go!
        pattern.replay(jaxbElement, writer, context);

        if (context.isMultiRefEncoding())
            context.getMultiRefSupport().outputMultiRefs(writer, context);

        if (!this.fragment)
            writer.add(XmlEventsPattern.XML_EVENTS_FACTORY.createEndDocument());
    } catch (XMLStreamException e) {
        throw new MarshalException(e);
    }
}

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

private static XMLOutputFactory getOrCreateFragmentOutputFactory() throws FactoryConfigurationError {
    XMLOutputFactory retVal = ourFragmentOutputFactory;
    if (retVal == null) {
        retVal = createOutputFactory();//from   w  w  w  .j  av a  2s.co  m
        retVal.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
        ourFragmentOutputFactory = retVal;
        return retVal;
    }
    return retVal;
}

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.
 *//* www  .j  a  va  2s .co 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;
}

From source file:org.apache.axiom.om.util.StAXUtils.java

private static XMLOutputFactory newXMLOutputFactory(final ClassLoader classLoader,
        final StAXWriterConfiguration configuration) {
    return (XMLOutputFactory) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader savedClassLoader;
            if (classLoader == null) {
                savedClassLoader = null;
            } else {
                savedClassLoader = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(classLoader);
            }//from ww w  .j a  va2s .c o m
            try {
                XMLOutputFactory factory = XMLOutputFactory.newInstance();
                factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
                Map props = loadFactoryProperties("XMLOutputFactory.properties");
                if (props != null) {
                    for (Iterator it = props.entrySet().iterator(); it.hasNext();) {
                        Map.Entry entry = (Map.Entry) it.next();
                        factory.setProperty((String) entry.getKey(), entry.getValue());
                    }
                }
                StAXDialect dialect = StAXDialectDetector.getDialect(factory.getClass());
                if (configuration != null) {
                    factory = configuration.configure(factory, dialect);
                }
                return new ImmutableXMLOutputFactory(dialect.normalize(dialect.makeThreadSafe(factory)));
            } finally {
                if (savedClassLoader != null) {
                    Thread.currentThread().setContextClassLoader(savedClassLoader);
                }
            }
        }
    });
}