Search in sources :

Example 1 with XMLStreamWriter

use of javax.xml.stream.XMLStreamWriter in project camel by apache.

the class RawMessageWSDLGetOutInterceptor method handleMessage.

public void handleMessage(Message message) throws Fault {
    Document doc = (Document) message.get(RawMessageWSDLGetInterceptor.DOCUMENT_HOLDER);
    if (doc == null) {
        return;
    }
    message.remove(RawMessageWSDLGetInterceptor.DOCUMENT_HOLDER);
    OutputStream out = message.getContent(OutputStream.class);
    String enc = null;
    try {
        enc = doc.getXmlEncoding();
    } catch (Exception ex) {
    //ignore - not dom level 3
    }
    if (enc == null) {
        enc = "utf-8";
    }
    XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(out, enc);
    try {
        StaxUtils.writeNode(doc, writer, true);
        writer.flush();
    } catch (XMLStreamException e) {
        throw new Fault(e);
    }
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) OutputStream(java.io.OutputStream) Fault(org.apache.cxf.interceptor.Fault) Document(org.w3c.dom.Document) XMLStreamException(javax.xml.stream.XMLStreamException)

Example 2 with XMLStreamWriter

use of javax.xml.stream.XMLStreamWriter in project camel by apache.

the class StaxConverterTest method testEncodingXmlStreamReader.

public void testEncodingXmlStreamReader() throws Exception {
    TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM.reset();
    XMLStreamReader reader = null;
    XMLStreamWriter writer = null;
    ByteArrayOutputStream output = null;
    try {
        // enter text encoded with Latin1
        reader = context.getTypeConverter().mandatoryConvertTo(XMLStreamReader.class, TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM);
        output = new ByteArrayOutputStream();
        // ensure UTF-8 encoding
        Exchange exchange = new DefaultExchange(context);
        exchange.setProperty(Exchange.CHARSET_NAME, UTF_8.name());
        writer = context.getTypeConverter().mandatoryConvertTo(XMLStreamWriter.class, exchange, output);
        // copy to writer
        while (reader.hasNext()) {
            reader.next();
            switch(reader.getEventType()) {
                case XMLStreamConstants.START_DOCUMENT:
                    writer.writeStartDocument();
                    break;
                case XMLStreamConstants.END_DOCUMENT:
                    writer.writeEndDocument();
                    break;
                case XMLStreamConstants.START_ELEMENT:
                    writer.writeStartElement(reader.getName().getLocalPart());
                    break;
                case XMLStreamConstants.CHARACTERS:
                    writer.writeCharacters(reader.getText());
                    break;
                case XMLStreamConstants.END_ELEMENT:
                    writer.writeEndElement();
                    break;
                default:
                    break;
            }
        }
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
    assertNotNull(output);
    String result = new String(output.toByteArray(), UTF_8.name());
    assertEquals(TEST_XML, result);
}
Also used : DefaultExchange(org.apache.camel.impl.DefaultExchange) Exchange(org.apache.camel.Exchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) XMLStreamReader(javax.xml.stream.XMLStreamReader) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 3 with XMLStreamWriter

use of javax.xml.stream.XMLStreamWriter in project camel by apache.

the class StAX2SAXSourceTest method testDefaultPrefixInRootElementWithCopyTransformer.

public void testDefaultPrefixInRootElementWithCopyTransformer() throws Exception {
    TransformerFactory trf = TransformerFactory.newInstance();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLStreamReader reader = context.getTypeConverter().mandatoryConvertTo(XMLStreamReader.class, new StringReader(TEST_XML));
    // ensure UTF-8 encoding
    Exchange exchange = new DefaultExchange(context);
    exchange.setProperty(Exchange.CHARSET_NAME, UTF_8.toString());
    XMLStreamWriter writer = context.getTypeConverter().mandatoryConvertTo(XMLStreamWriter.class, exchange, baos);
    StAX2SAXSource staxSource = new StAX2SAXSource(reader);
    StreamSource templateSource = new StreamSource(getClass().getResourceAsStream("/xslt/common/copy.xsl"));
    Transformer transformer = trf.newTransformer(templateSource);
    log.info("Used transformer: {}", transformer.getClass().getName());
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(staxSource, new StreamResult(baos));
    writer.flush();
    baos.flush();
    assertThat(new String(baos.toByteArray()), equalTo(TEST_XML));
}
Also used : DefaultExchange(org.apache.camel.impl.DefaultExchange) Exchange(org.apache.camel.Exchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) TransformerFactory(javax.xml.transform.TransformerFactory) XMLStreamReader(javax.xml.stream.XMLStreamReader) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) StreamSource(javax.xml.transform.stream.StreamSource) StringReader(java.io.StringReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 4 with XMLStreamWriter

use of javax.xml.stream.XMLStreamWriter in project elasticsearch by elastic.

the class Ec2DiscoveryClusterFormationTests method startHttpd.

/**
     * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
     */
@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();
}
Also used : Path(java.nio.file.Path) NameValuePair(org.apache.http.NameValuePair) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) InetSocketAddress(java.net.InetSocketAddress) Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) StringWriter(java.io.StringWriter) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) BeforeClass(org.junit.BeforeClass)

Example 5 with XMLStreamWriter

use of javax.xml.stream.XMLStreamWriter in project jvm-serializers by eishay.

the class BaseStaxMediaSerializer method serializeItems.

@Override
public final void serializeItems(MediaContent[] items, OutputStream out) throws XMLStreamException {
    // XML requires single root, so add bogus "stream"
    XMLStreamWriter writer = createWriter(out);
    _serializer.writeDocument(writer, items);
    writer.flush();
    writer.close();
}
Also used : XMLStreamWriter(javax.xml.stream.XMLStreamWriter)

Aggregations

XMLStreamWriter (javax.xml.stream.XMLStreamWriter)82 XMLStreamException (javax.xml.stream.XMLStreamException)36 XMLOutputFactory (javax.xml.stream.XMLOutputFactory)28 StringWriter (java.io.StringWriter)15 ByteArrayOutputStream (java.io.ByteArrayOutputStream)14 IOException (java.io.IOException)12 XmlWriter (org.apache.aries.blueprint.plugin.spi.XmlWriter)7 OutputStream (java.io.OutputStream)6 StAXResult (javax.xml.transform.stax.StAXResult)6 Test (org.junit.Test)6 OutputStreamWriter (java.io.OutputStreamWriter)5 JAXBException (javax.xml.bind.JAXBException)5 StreamResult (javax.xml.transform.stream.StreamResult)5 ZipEntry (java.util.zip.ZipEntry)4 XMLStreamReader (javax.xml.stream.XMLStreamReader)4 PcrManifest (com.intel.mountwilson.manifest.data.PcrManifest)3 StringReader (java.io.StringReader)3 ToXmlGenerator (com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator)2 IManifest (com.intel.mountwilson.manifest.data.IManifest)2 Headers (com.sun.net.httpserver.Headers)2