Java Code Examples for org.apache.cxf.staxutils.StaxUtils#createXMLStreamWriter()

The following examples show how to use org.apache.cxf.staxutils.StaxUtils#createXMLStreamWriter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XSLTJaxbProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected Object unmarshalFromReader(Unmarshaller unmarshaller, XMLStreamReader reader,
                                     Annotation[] anns, MediaType mt)
    throws JAXBException {
    CachedOutputStream out = new CachedOutputStream();
    try {
        XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(out);
        StaxUtils.copy(new StaxSource(reader), writer);
        writer.writeEndDocument();
        writer.flush();
        writer.close();
        return unmarshalFromInputStream(unmarshaller, out.getInputStream(), anns, mt);
    } catch (Exception ex) {
        throw ExceptionUtils.toBadRequestException(ex, null);
    }
}
 
Example 2
Source File: OutTransformWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testReplaceDefaultNamespace() throws Exception {
    InputStream is = new ByteArrayInputStream(
            "<test xmlns=\"http://bar\"><a>1</a></test>".getBytes());

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    XMLStreamWriter writer =
        new OutTransformWriter(StaxUtils.createXMLStreamWriter(os, StandardCharsets.UTF_8.name()),
                               null, null, null, null, false, "");
    StaxUtils.copy(new StreamSource(is), writer);
    writer.flush();

    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(os.toByteArray()));

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    StaxUtils.copy(reader, bos);
    String value = bos.toString();
    assertEquals("<ps1:test xmlns:ps1=\"http://bar\"><ps1:a>1</ps1:a></ps1:test>", value);
}
 
Example 3
Source File: CapturingXMLWriter.java    From cxf with Apache License 2.0 6 votes vote down vote up
public CapturingXMLWriter(XMLStreamWriter del) {
    delegate = del;
    capture = StaxUtils.createXMLStreamWriter(bos, StandardCharsets.UTF_8.name());

    Map<String, String> map = new HashMap<>();
    map.put("{http://schemas.xmlsoap.org/ws/2005/02/rm}Sequence", "");
    map.put("{http://schemas.xmlsoap.org/ws/2005/02/rm}SequenceAcknowledgement", "");
    map.put("{http://docs.oasis-open.org/ws-rx/wsrm/200702}Sequence", "");
    map.put("{http://docs.oasis-open.org/ws-rx/wsrm/200702}SequenceAcknowledgement", "");

    capture = new OutTransformWriter(capture,
                                     map,
                                     Collections.<String, String>emptyMap(),
                                     Collections.<String>emptyList(),
                                     false,
                                     null);
}
 
Example 4
Source File: OutTransformWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultNamespace() throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(os, StandardCharsets.UTF_8.name());

    Map<String, String> outMap = new HashMap<>();
    outMap.put("{http://testbeans.com}*", "{http://testbeans.com/v2}*");
    OutTransformWriter transformWriter = new OutTransformWriter(writer,
                                                                outMap,
                                                                Collections.<String, String>emptyMap(),
                                                                Collections.<String>emptyList(),
                                                                false,
                                                                "http://testbeans.com/v2");
    JAXBContext context = JAXBContext.newInstance(TestBean.class);
    Marshaller m = context.createMarshaller();
    m.marshal(new TestBean(), transformWriter);

    String expected = "<?xml version='1.0' encoding='UTF-8'?>"
        + "<testBean xmlns=\"http://testbeans.com/v2\"><bean/></testBean>";
    assertEquals(expected, os.toString());
}
 
Example 5
Source File: OutTransformWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testReplaceSimpleElement() throws Exception {
    InputStream is = new ByteArrayInputStream(
            "<ns:test xmlns:ns=\"http://bar\"><ns:a>1</ns:a></ns:test>".getBytes());

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    XMLStreamWriter writer =
        new OutTransformWriter(StaxUtils.createXMLStreamWriter(os, StandardCharsets.UTF_8.name()),
                               null, Collections.singletonMap("{http://bar}a", "{http://bar}a=1 2 3"),
                               null, null, false, null);
    StaxUtils.copy(new StreamSource(is), writer);
    writer.flush();

    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(os.toByteArray()));

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    StaxUtils.copy(reader, bos);
    String value = bos.toString();
    assertEquals("<ns:test xmlns:ns=\"http://bar\"><ns:a>1 2 3</ns:a></ns:test>", value);
}
 
Example 6
Source File: ImportRepairTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void dumpSchema(Document document) throws Exception {
    if (!dumpSchemas) {
        return;
    }

    XMLStreamWriter xwriter = StaxUtils.createXMLStreamWriter(System.err);
    xwriter = new PrettyPrintXMLStreamWriter(xwriter, 2);
    StaxUtils.copy(new DOMSource(document), xwriter);
    xwriter.close();
}
 
Example 7
Source File: WSS4JFaultCodeTest.java    From steady with Apache License 2.0 5 votes vote down vote up
private byte[] getMessageBytes(Document doc) throws Exception {
    // XMLOutputFactory factory = XMLOutputFactory.newInstance();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    // XMLStreamWriter byteArrayWriter =
    // factory.createXMLStreamWriter(outputStream);
    XMLStreamWriter byteArrayWriter = StaxUtils.createXMLStreamWriter(outputStream);

    StaxUtils.writeDocument(doc, byteArrayWriter, false);

    byteArrayWriter.flush();
    return outputStream.toByteArray();
}
 
Example 8
Source File: RMCaptureInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private CachedOutputStream removeUnnecessarySoapHeaders(CachedOutputStream saved) {
    CachedOutputStream newSaved = new CachedOutputStream();

    try (InputStream is = saved.getInputStream()) {
        XMLStreamWriter capture = StaxUtils.createXMLStreamWriter(newSaved,
                                                                  StandardCharsets.UTF_8.name());
        Map<String, String> map = new HashMap<>();
        map.put("{http://schemas.xmlsoap.org/ws/2005/02/rm}Sequence", "");
        map.put("{http://schemas.xmlsoap.org/ws/2005/02/rm}SequenceAcknowledgement", "");
        map.put("{http://docs.oasis-open.org/ws-rx/wsrm/200702}Sequence", "");
        map.put("{http://docs.oasis-open.org/ws-rx/wsrm/200702}SequenceAcknowledgement", "");
        map.put("{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}Security",
                "");
        // attributes to be removed
        Map<String, String> amap = new HashMap<>();
        amap.put("{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd}Id",
                 "");

        capture = new OutTransformWriter(capture, map, Collections.<String, String> emptyMap(),
                                         Collections.<String> emptyList(), amap, false, null);
        StaxUtils.copy(new StreamSource(is), capture);
        capture.flush();
        capture.close();
        newSaved.flush();
        // hold temp file, otherwise it will be deleted in case msg was written to RMTxStore
        // or resend was executed
        newSaved.holdTempFile();
    } catch (IOException | XMLStreamException e) {
        throw new Fault(e);
    }
    return newSaved;
}
 
Example 9
Source File: HWSAXSourcePayloadProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
private File getSOAPBodyFile(Document doc) throws Exception {
    File file = FileUtils.createTempFile("cxf-systest", "xml");
    try (FileOutputStream out = new FileOutputStream(file)) {
        XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(out);
        StaxUtils.writeDocument(doc, writer, true);
        writer.close();
        return file;
    }
}
 
Example 10
Source File: XSLTInterceptorsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void outXMLStreamTest() throws XMLStreamException, SAXException, IOException, ParserConfigurationException {
    CachedWriter cWriter = new CachedWriter();
    cWriter.holdTempFile();
    XMLStreamWriter xWriter = StaxUtils.createXMLStreamWriter(cWriter);
    message.setContent(XMLStreamWriter.class, xWriter);
    outInterceptor.handleMessage(message);
    XMLStreamWriter tXWriter = message.getContent(XMLStreamWriter.class);
    StaxUtils.copy(new StreamSource(messageIS), tXWriter);
    tXWriter.close();
    cWriter.releaseTempFileHold();
    Document doc = StaxUtils.read(cWriter.getReader());
    Assert.assertTrue("Message was not transformed", checkTransformedXML(doc));
}
 
Example 11
Source File: WSS4JFaultCodeTest.java    From steady with Apache License 2.0 5 votes vote down vote up
private byte[] getMessageBytes(Document doc) throws Exception {
    // XMLOutputFactory factory = XMLOutputFactory.newInstance();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    // XMLStreamWriter byteArrayWriter =
    // factory.createXMLStreamWriter(outputStream);
    XMLStreamWriter byteArrayWriter = StaxUtils.createXMLStreamWriter(outputStream);

    StaxUtils.writeDocument(doc, byteArrayWriter, false);

    byteArrayWriter.flush();
    return outputStream.toByteArray();
}
 
Example 12
Source File: SamlTokenTest.java    From steady with Apache License 2.0 5 votes vote down vote up
private byte[] getMessageBytes(Document doc) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    XMLStreamWriter byteArrayWriter = StaxUtils.createXMLStreamWriter(outputStream);
    StaxUtils.writeDocument(doc, byteArrayWriter, false);
    byteArrayWriter.flush();
    return outputStream.toByteArray();
}
 
Example 13
Source File: SignatureConfirmationTest.java    From steady with Apache License 2.0 5 votes vote down vote up
private byte[] getMessageBytes(Document doc) throws Exception {
    // XMLOutputFactory factory = XMLOutputFactory.newInstance();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    // XMLStreamWriter byteArrayWriter =
    // factory.createXMLStreamWriter(outputStream);
    XMLStreamWriter byteArrayWriter = StaxUtils.createXMLStreamWriter(outputStream);

    StaxUtils.writeDocument(doc, byteArrayWriter, false);

    byteArrayWriter.flush();
    return outputStream.toByteArray();
}
 
Example 14
Source File: XSLTOutInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void transformXWriter(Message message, XMLStreamWriter xWriter) {
    CachedWriter writer = new CachedWriter();
    XMLStreamWriter delegate = StaxUtils.createXMLStreamWriter(writer);
    XSLTStreamWriter wrapper = new XSLTStreamWriter(getXSLTTemplate(), writer, delegate, xWriter);
    message.setContent(XMLStreamWriter.class, wrapper);
    message.put(AbstractOutDatabindingInterceptor.DISABLE_OUTPUTSTREAM_OPTIMIZATION,
                Boolean.TRUE);
}
 
Example 15
Source File: SignatureConfirmationTest.java    From steady with Apache License 2.0 5 votes vote down vote up
private byte[] getMessageBytes(Document doc) throws Exception {
    // XMLOutputFactory factory = XMLOutputFactory.newInstance();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    // XMLStreamWriter byteArrayWriter =
    // factory.createXMLStreamWriter(outputStream);
    XMLStreamWriter byteArrayWriter = StaxUtils.createXMLStreamWriter(outputStream);

    StaxUtils.writeDocument(doc, byteArrayWriter, false);

    byteArrayWriter.flush();
    return outputStream.toByteArray();
}
 
Example 16
Source File: WSS4JFaultCodeTest.java    From steady with Apache License 2.0 5 votes vote down vote up
private byte[] getMessageBytes(Document doc) throws Exception {
    // XMLOutputFactory factory = XMLOutputFactory.newInstance();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    // XMLStreamWriter byteArrayWriter =
    // factory.createXMLStreamWriter(outputStream);
    XMLStreamWriter byteArrayWriter = StaxUtils.createXMLStreamWriter(outputStream);

    StaxUtils.writeDocument(doc, byteArrayWriter, false);

    byteArrayWriter.flush();
    return outputStream.toByteArray();
}
 
Example 17
Source File: XMLFaultOutInterceptorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testFault() throws Exception {
    FaultDetail detail = new FaultDetail();
    detail.setMajor((short)2);
    detail.setMinor((short)1);
    PingMeFault fault = new PingMeFault("TEST_FAULT", detail);

    XMLFault xmlFault = XMLFault.createFault(new Fault(fault));
    Element el = xmlFault.getOrCreateDetail();
    JAXBContext ctx = JAXBContext.newInstance(FaultDetail.class);
    Marshaller m = ctx.createMarshaller();
    m.marshal(detail, el);

    OutputStream outputStream = new ByteArrayOutputStream();
    xmlMessage.setContent(OutputStream.class, outputStream);
    XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(outputStream);
    xmlMessage.setContent(XMLStreamWriter.class, writer);
    xmlMessage.setContent(Exception.class, xmlFault);

    out.handleMessage(xmlMessage);
    outputStream.flush();

    XMLStreamReader reader = getXMLReader();
    DepthXMLStreamReader dxr = new DepthXMLStreamReader(reader);

    dxr.nextTag();
    StaxUtils.toNextElement(dxr);
    assertEquals(XMLConstants.NS_XML_FORMAT, dxr.getNamespaceURI());
    assertEquals(XMLFault.XML_FAULT_ROOT, dxr.getLocalName());

    dxr.nextTag();
    StaxUtils.toNextElement(dxr);
    assertEquals(XMLFault.XML_FAULT_STRING, dxr.getLocalName());
    assertEquals(fault.toString(), dxr.getElementText());

    dxr.nextTag();
    StaxUtils.toNextElement(dxr);
    assertEquals(XMLFault.XML_FAULT_DETAIL, dxr.getLocalName());

    dxr.nextTag();
    StaxUtils.toNextElement(dxr);
    assertEquals("faultDetail", dxr.getLocalName());
}
 
Example 18
Source File: JavaToProcessorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testTransientMessage() throws Exception {
    //CXF-5744
    env.put(ToolConstants.CFG_OUTPUTFILE, output.getPath() + "/transient_message.wsdl");
    env.put(ToolConstants.CFG_CLASSNAME, "org.apache.cxf.tools.fortest.exception.Echo4");
    env.put(ToolConstants.CFG_VERBOSE, ToolConstants.CFG_VERBOSE);
    try {
        processor.setEnvironment(env);
        processor.process();
    } catch (Exception e) {
        e.printStackTrace();
    }

    File wsdlFile = new File(output, "transient_message.wsdl");
    assertTrue(wsdlFile.exists());

    Document doc = StaxUtils.read(wsdlFile);
    //StaxUtils.print(doc);
    Map<String, String> map = new HashMap<>();
    map.put("xsd", "http://www.w3.org/2001/XMLSchema");
    map.put("wsdl", "http://schemas.xmlsoap.org/wsdl/");
    map.put("soap", "http://schemas.xmlsoap.org/wsdl/soap/");
    map.put("tns", "http://cxf.apache.org/test/HelloService");
    XPathUtils util = new XPathUtils(map);

    String path = "//xsd:complexType[@name='TransientMessageException']//xsd:sequence/xsd:element[@name='message']";
    Element nd = (Element)util.getValueNode(path, doc);
    assertNull(nd);

    //ok, we didn't map it into the schema.  Make sure the runtime won't write it out.
    List<ServiceInfo> sl = CastUtils.cast((List<?>)env.get("serviceList"));
    FaultInfo mi = sl.get(0).getInterface().getOperation(new QName("http://cxf.apache.org/test/HelloService",
                                                                   "echo"))
        .getFault(new QName("http://cxf.apache.org/test/HelloService",
                            "TransientMessageException"));
    MessagePartInfo mpi = mi.getMessagePart(0);
    JAXBContext ctx = JAXBContext.newInstance(String.class, Integer.TYPE);
    StringWriter sw = new StringWriter();
    XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(sw);
    TransientMessageException tme = new TransientMessageException(12, "Exception Message");
    Marshaller ms = ctx.createMarshaller();
    ms.setProperty(Marshaller.JAXB_FRAGMENT, true);
    JAXBEncoderDecoder.marshallException(ms, tme, mpi, writer);
    writer.flush();
    writer.close();
    assertEquals(-1, sw.getBuffer().indexOf("Exception Message"));
}
 
Example 19
Source File: StaxOutInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("resource")
public void handleMessage(Message message) {
    OutputStream os = message.getContent(OutputStream.class);
    XMLStreamWriter xwriter = message.getContent(XMLStreamWriter.class);
    Writer writer = null;
    if (os == null) {
        writer = message.getContent(Writer.class);
    }
    if ((os == null && writer == null) || xwriter != null) {
        return;
    }

    String encoding = getEncoding(message);

    try {
        XMLOutputFactory factory = getXMLOutputFactory(message);
        if (factory == null) {
            if (writer == null) {
                os = setupOutputStream(os);
                xwriter = StaxUtils.createXMLStreamWriter(os, encoding);
            } else {
                xwriter = StaxUtils.createXMLStreamWriter(writer);
            }
        } else {
            if (PropertyUtils.isTrue(message.getContextualProperty(Message.THREAD_SAFE_STAX_FACTORIES))) {
                if (writer == null) {
                    os = setupOutputStream(os);
                    xwriter = factory.createXMLStreamWriter(os, encoding);
                } else {
                    xwriter = factory.createXMLStreamWriter(writer);
                }
            } else {
                synchronized (factory) {
                    if (writer == null) {
                        os = setupOutputStream(os);
                        xwriter = factory.createXMLStreamWriter(os, encoding);
                    } else {
                        xwriter = factory.createXMLStreamWriter(writer);
                    }
                }
            }
        }
        if (MessageUtils.getContextualBoolean(message, FORCE_START_DOCUMENT, false)) {
            xwriter.writeStartDocument(encoding, "1.0");
            message.removeContent(OutputStream.class);
            message.put(OUTPUT_STREAM_HOLDER, os);
            message.removeContent(Writer.class);
            message.put(WRITER_HOLDER, writer);
        }
    } catch (XMLStreamException e) {
        throw new Fault(new org.apache.cxf.common.i18n.Message("STREAM_CREATE_EXC", BUNDLE), e);
    }
    message.setContent(XMLStreamWriter.class, xwriter);

    // Add a final interceptor to write end elements
    message.getInterceptorChain().add(ENDING);
}
 
Example 20
Source File: OutTransformWriterTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testReadWithComplexTransformationNamespace2() throws Exception {
    Map<String, String> map = new HashMap<>();
    map.put("{http://testbeans.com/double}*",
        "{http://testbeans.com/double/v2}*");
    map.put("{http://testbeans.com}*",
        "{http://testbeans.com/v3}*");

    // the namespaces are prefixed in the input
    XMLStreamReader reader =
        TransformTestUtils.createOutTransformedStreamReader("../resources/doubleBeanIn1.xml",
                                                            map, null, null, null, false, null);
    XMLStreamReader reader2 =
        StaxUtils.createXMLStreamReader(
            InTransformReader.class.getResourceAsStream("../resources/doubleBean.xml"));
    TransformTestUtils.verifyReaders(reader2, reader, true, false);

    // the child elements with the default namespace that is declared in the elements
    reader =
        TransformTestUtils.createOutTransformedStreamReader("../resources/doubleBeanIn2.xml",
                                                            map, null, null, null, false, null);
    reader2 =
        StaxUtils.createXMLStreamReader(
            InTransformReader.class.getResourceAsStream("../resources/doubleBean.xml"));
    TransformTestUtils.verifyReaders(reader2, reader, true, false);

    // the child elements with the default namespace that is declared in their parent element
    reader =
        TransformTestUtils.createOutTransformedStreamReader("../resources/doubleBeanIn3.xml",
                                                            map, null, null, null, false, null);
    reader2 =
        StaxUtils.createXMLStreamReader(
            InTransformReader.class.getResourceAsStream("../resources/doubleBean.xml"));
    TransformTestUtils.verifyReaders(reader2, reader, true, false);

    // writing each child separately (as the soap header children are serialized)
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    XMLStreamWriter writer =
        new OutTransformWriter(StaxUtils.createXMLStreamWriter(os, StandardCharsets.UTF_8.name()),
                               map, null,
                               null, null, false, null);
    boolean nsset = "ns3".equals(writer.getNamespaceContext().getPrefix("http://testbeans.com/double"));
    writer.writeStartElement("ns3", "testDoubleBean", "http://testbeans.com/double");
    if (!nsset) {
        writer.writeNamespace("ns3", "http://testbeans.com/double");
    }
    nsset = "".equals(writer.getNamespaceContext().getPrefix("http://testbeans.com"));
    writer.writeStartElement("", "bean", "http://testbeans.com");
    if (!nsset) {
        writer.writeNamespace("", "http://testbeans.com");
    }
    writer.writeEndElement();
    nsset = "".equals(writer.getNamespaceContext().getPrefix("http://testbeans.com"));
    writer.writeStartElement("", "beanNext", "http://testbeans.com");
    if (!nsset) {
        writer.writeNamespace("", "http://testbeans.com");
    }
    writer.writeEndElement();
    writer.writeEndElement();
    writer.flush();

    reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(os.toByteArray()));
    reader2 =
        StaxUtils.createXMLStreamReader(
            InTransformReader.class.getResourceAsStream("../resources/doubleBean.xml"));
    TransformTestUtils.verifyReaders(reader2, reader, true, false);
}