org.apache.cxf.staxutils.StaxUtils Java Examples

The following examples show how to use org.apache.cxf.staxutils.StaxUtils. 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: Server.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Source invoke(Source obj) {
    //CHECK the incoming
    Element el;
    try {
        el = StaxUtils.read(obj).getDocumentElement();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    Map<String, String> ns = new HashMap<>();
    ns.put("ns", "http://apache.org/cxf/systest/ws/addr_feature/");
    XPathUtils xp = new XPathUtils(ns);
    String o = (String)xp.getValue("/ns:addNumbers/ns:number1", el, XPathConstants.STRING);
    String o2 = (String)xp.getValue("/ns:addNumbers/ns:number2", el, XPathConstants.STRING);
    int i = Integer.parseInt(o);
    int i2 = Integer.parseInt(o2);

    String resp = "<addNumbersResponse xmlns=\"http://apache.org/cxf/systest/ws/addr_feature/\">"
        + "<return>" + (i + i2) + "</return></addNumbersResponse>";
    return new StreamSource(new StringReader(resp));
}
 
Example #2
Source File: ClientServerRPCLitTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testDispatchClient() throws Exception {
    SOAPServiceRPCLit service = new SOAPServiceRPCLit();
    Dispatch<Source> disp = service.createDispatch(portName, Source.class,
                                                   javax.xml.ws.Service.Mode.PAYLOAD);
    updateAddressPort(disp, PORT);

    String req = "<ns1:sendReceiveData xmlns:ns1=\"http://apache.org/hello_world_rpclit\">"
        + "<in xmlns:ns2=\"http://apache.org/hello_world_rpclit/types\">"
        + "<ns2:elem1>elem1</ns2:elem1><ns2:elem2>elem2</ns2:elem2><ns2:elem3>45</ns2:elem3>"
        + "</in></ns1:sendReceiveData>";
    Source source = new StreamSource(new StringReader(req));
    Source resp = disp.invoke(source);
    assertNotNull(resp);

    Node nd = StaxUtils.read(resp);
    if (nd instanceof Document) {
        nd = ((Document)nd).getDocumentElement();
    }
    XPathUtils xpu = new XPathUtils(new W3CNamespaceContext((Element)nd));
    assertTrue(xpu.isExist("/ns1:sendReceiveDataResponse/out", nd, XPathConstants.NODE));
}
 
Example #3
Source File: DepthRestrictingStreamInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) {

        if (canBeIgnored(message)) {
            return;
        }

        XMLStreamReader reader = message.getContent(XMLStreamReader.class);
        if (reader == null) {
            InputStream is = message.getContent(InputStream.class);
            if (is != null) {
                reader = StaxUtils.createXMLStreamReader(is);
                message.setContent(InputStream.class, null);
            }
            if (reader == null) {
                return;
            }
        }
        DepthRestrictingStreamReader dr =
            new DepthRestrictingStreamReader(reader,
                                             elementCountThreshold,
                                             innerElementLevelThreshold,
                                             innerElementCountThreshold);
        message.setContent(XMLStreamReader.class, dr);
    }
 
Example #4
Source File: XSLTJaxbProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteToStreamWriter() throws Exception {
    XSLTJaxbProvider<Book> provider = new XSLTJaxbProvider<Book>() {
        @Override
        protected XMLStreamWriter getStreamWriter(Object obj, OutputStream os, MediaType mt) {
            return StaxUtils.createXMLStreamWriter(os);
        }
    };
    provider.setOutTemplate(TEMPLATE_LOCATION);
    provider.setMessageContext(new MessageContextImpl(createMessage()));
    Book b = new Book();
    b.setId(123L);
    b.setName("TheBook");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    provider.writeTo(b, Book.class, Book.class, b.getClass().getAnnotations(),
                     MediaType.TEXT_XML_TYPE, new MetadataMap<String, Object>(), bos);
    Unmarshaller um = provider.getClassContext(Book.class).createUnmarshaller();
    Book b2 = (Book)um.unmarshal(new StringReader(bos.toString()));
    b.setName("TheBook2");
    assertEquals("Transformation is bad", b, b2);
}
 
Example #5
Source File: WSDiscoveryServiceImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Source mapToOld(Document doc, JAXBElement<?> mt) throws JAXBException, XMLStreamException {
    doc.removeChild(doc.getDocumentElement());
    DOMResult result = new DOMResult(doc);
    XMLStreamWriter r = StaxUtils.createXMLStreamWriter(result);
    context.createMarshaller().marshal(mt, r);

    XMLStreamReader domReader = StaxUtils.createXMLStreamReader(doc);
    Map<String, String> inMap = new HashMap<>();
    inMap.put("{" + WSDVersion.INSTANCE_1_1.getNamespace() + "}*",
              "{" + WSDVersion.INSTANCE_1_0.getNamespace() + "}*");
    inMap.put("{" + WSDVersion.INSTANCE_1_1.getAddressingNamespace() + "}*",
              "{" + WSDVersion.INSTANCE_1_0.getAddressingNamespace() + "}*");

    InTransformReader reader = new InTransformReader(domReader, inMap, null, false);
    doc = StaxUtils.read(reader);
    return new DOMSource(doc);
}
 
Example #6
Source File: DispatchTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testDOMSource() throws Exception {
    ServiceImpl service =
        new ServiceImpl(getBus(), getClass().getResource("/wsdl/hello_world.wsdl"), SERVICE_NAME, null);

    Dispatch<Source> disp = service.createDispatch(PORT_NAME, Source.class, Service.Mode.MESSAGE);
    disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, ADDRESS);

    d.setMessageObserver(new MessageReplayObserver("/org/apache/cxf/jaxws/sayHiResponse.xml"));

    Document doc = StaxUtils.read(getResourceAsStream("/org/apache/cxf/jaxws/sayHi2.xml"));
    DOMSource source = new DOMSource(doc);
    Source res = disp.invoke(source);
    assertNotNull(res);

}
 
Example #7
Source File: EndpointReferenceTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testServiceGetPortUsingEndpointReference() throws Exception {
    BusFactory.setDefaultBus(getBus());
    GreeterImpl greeter1 = new GreeterImpl();
    try (EndpointImpl endpoint = new EndpointImpl(getBus(), greeter1, (String)null)) {
        endpoint.publish("http://localhost:8080/test");

        javax.xml.ws.Service s = javax.xml.ws.Service
            .create(new QName("http://apache.org/hello_world_soap_http", "SoapPort"));

        InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml");
        Document doc = StaxUtils.read(is);
        DOMSource erXML = new DOMSource(doc);
        EndpointReference endpointReference = EndpointReference.readFrom(erXML);

        WebServiceFeature[] wfs = new WebServiceFeature[] {};

        Greeter greeter = s.getPort(endpointReference, Greeter.class, wfs);

        String response = greeter.greetMe("John");

        assertEquals("Hello John", response);
    }
}
 
Example #8
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssueSAML2TokenPlain() throws Exception {
    WebClient client = webClient()
        .path("saml2.0")
        .accept(MediaType.TEXT_PLAIN);

    String encodedAssertion = client.get(String.class);
    assertNotNull(encodedAssertion);

    byte[] deflatedToken = Base64Utility.decode(encodedAssertion);
    InputStream inputStream = CompressionUtils.inflate(deflatedToken);
    Document doc =
        StaxUtils.read(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

    // Process the token
    SamlAssertionWrapper assertion = validateSAMLToken(doc);
    assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);
}
 
Example #9
Source File: SoapPayloadConverterTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void convertXmlToCxfToXml() throws IOException, XMLStreamException {

    // read XML bytes as an XML Document
    final ByteArrayInputStream bis = new ByteArrayInputStream(IOUtils.readBytesFromStream(inputStream));
    final Document request = StaxUtils.read(bis);
    bis.reset();

    // convert XML to CxfPayload
    final Exchange exchange = createExchangeWithBody(bis);
    final Message in = exchange.getIn();
    requestConverter.process(exchange);

    Assertions.assertThat(in.getBody()).isInstanceOf(CxfPayload.class);

    // convert CxfPayload back to XML
    final SoapMessage soapMessage = new SoapMessage(Soap12.getInstance());
    in.setHeader("CamelCxfMessage", soapMessage);
    responseConverter.process(exchange);

    assertIsInstanceOf(InputStream.class, in.getBody());
    Document response = StaxUtils.read((InputStream) in.getBody());

    XMLUnit.setIgnoreAttributeOrder(true);
    assertThat(response, isSimilarTo(request).ignoreWhitespace());
}
 
Example #10
Source File: DispatchXMLClientServerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testDOMSourcePAYLOAD() throws Exception {
    URL wsdl = getClass().getResource("/wsdl/hello_world_xml_wrapped.wsdl");
    assertNotNull(wsdl);

    XMLService service = new XMLService(wsdl, SERVICE_NAME);
    assertNotNull(service);

    InputStream is = getClass().getResourceAsStream("/messages/XML_GreetMeDocLiteralReq.xml");
    Document doc = StaxUtils.read(is);
    DOMSource reqMsg = new DOMSource(doc);
    assertNotNull(reqMsg);

    Dispatch<DOMSource> disp = service.createDispatch(PORT_NAME, DOMSource.class,
                                                      Service.Mode.PAYLOAD);
    disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                                 "http://localhost:"
                                 + port
                                 + "/XMLService/XMLDispatchPort");
    DOMSource result = disp.invoke(reqMsg);
    assertNotNull(result);

    Node respDoc = result.getNode();
    assertEquals("greetMeResponse", respDoc.getFirstChild().getLocalName());
    assertEquals("Hello tli", respDoc.getFirstChild().getTextContent());
}
 
Example #11
Source File: EndpointReferenceTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testEndpointGetEndpointReferenceXMLBinding() throws Exception {
    org.apache.hello_world_xml_http.bare.Greeter greeter =
        new org.apache.hello_world_xml_http.bare.GreeterImpl();
    try (EndpointImpl endpoint = new EndpointImpl(getBus(), greeter, (String)null)) {

        endpoint.publish("http://localhost:8080/test");

        try {
            InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml");
            Document doc = StaxUtils.read(is);
            Element referenceParameters = fetchElementByNameAttribute(doc.getDocumentElement(),
                                                                      "wsa:ReferenceParameters",
                                                                      "");
            endpoint.getEndpointReference(referenceParameters);

            fail("Did not get expected UnsupportedOperationException");
        } catch (UnsupportedOperationException e) {
            //do nothing
        }

        endpoint.stop();
    }
}
 
Example #12
Source File: SoapPayloadConverterTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void convertXmlToValidCxfPayload() throws IOException, XMLStreamException {

    // read XML bytes as an XML Document
    ByteArrayInputStream bis = new ByteArrayInputStream(IOUtils.readBytesFromStream(inputStream));
    StaxUtils.read(bis);
    bis.reset();

    // convert XML to CxfPayload
    final Exchange exchange = createExchangeWithBody(bis);
    final Message in = exchange.getIn();
    requestConverter.process(exchange);

    final Object body = in.getBody();
    Assertions.assertThat(body).isInstanceOf(CxfPayload.class);
    @SuppressWarnings("unchecked")
    final CxfPayload<Source> cxfPayload = (CxfPayload<Source>) body;

    // validate every header and body part XML
    for (Source headerPart : cxfPayload.getHeaders()) {
        validateXml(headerPart);
    }
    for (Source bodyPart : cxfPayload.getBodySources()) {
        validateXml(bodyPart);
    }
}
 
Example #13
Source File: JaxbAssertionBuilderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuild() throws Exception {
    QName qn = new QName("http://cxf.apache.org/test/assertions/foo", "FooType");
    JaxbAssertionBuilder<FooType> ab = new JaxbAssertionBuilder<>(FooType.class, qn);
    assertNotNull(ab);
    InputStream is = JaxbAssertionBuilderTest.class.getResourceAsStream("foo.xml");
    Document doc = StaxUtils.read(is);
    Element elem = DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),
                                                      "http://cxf.apache.org/test/assertions/foo",
                                                      "foo").get(0);
    Assertion a = ab.build(elem, null);
    JaxbAssertion<FooType> jba = JaxbAssertion.cast(a, FooType.class);
    FooType foo = jba.getData();
    assertEquals("CXF", foo.getName());
    assertEquals(2, foo.getNumber().intValue());
}
 
Example #14
Source File: RPCOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected String addOperationNode(NSStack nsStack, Message message,
                                  XMLStreamWriter xmlWriter,
                                  boolean output,
                                  BindingOperationInfo boi)
    throws XMLStreamException {
    String ns = boi.getName().getNamespaceURI();
    SoapBody body = null;
    if (output) {
        body = boi.getOutput().getExtensor(SoapBody.class);
    } else {
        body = boi.getInput().getExtensor(SoapBody.class);
    }
    if (body != null) {
        final String nsUri = body.getNamespaceURI(); //do it once, as it might internally use reflection...
        if (!StringUtils.isEmpty(nsUri)) {
            ns = nsUri;
        }
    }

    nsStack.add(ns);
    String prefix = nsStack.getPrefix(ns);
    String name = output ? boi.getName().getLocalPart() + "Response" : boi.getName().getLocalPart();
    StaxUtils.writeStartElement(xmlWriter, prefix, name, ns);
    return ns;
}
 
Example #15
Source File: TransformTestUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
static void transformInStreamAndCompare(String inname, String outname,
                                       Map<String, String> transformElements,
                                       Map<String, String> appendElements,
                                       List<String> dropElements,
                                       Map<String, String> transformAttributes)
    throws XMLStreamException {

    XMLStreamReader reader = createInTransformedStreamReader(inname,
                                                             transformElements,
                                                             appendElements,
                                                             dropElements,
                                                             transformAttributes);
    XMLStreamReader teacher =
        StaxUtils.createXMLStreamReader(
                  TransformTestUtils.class.getResourceAsStream(outname));

    verifyReaders(teacher, reader, false, true);
}
 
Example #16
Source File: AbstractLoggingInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void writePrettyPayload(StringBuilder builder,
                            StringWriter stringWriter,
                            String contentType)
    throws Exception {
    // Just transform the XML message when the cos has content

    StringWriter swriter = new StringWriter();
    XMLStreamWriter xwriter = StaxUtils.createXMLStreamWriter(swriter);
    xwriter = new PrettyPrintXMLStreamWriter(xwriter, 2);
    StaxUtils.copy(new StreamSource(new StringReader(stringWriter.getBuffer().toString())), xwriter);
    xwriter.close();

    String result = swriter.toString();
    if (result.length() < limit || limit == -1) {
        builder.append(swriter.toString());
    } else {
        builder.append(swriter.toString().substring(0, limit));
    }
}
 
Example #17
Source File: XMLMessageOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void writeMessage(Message message, QName name, boolean executeBare) {
    XMLStreamWriter xmlWriter = message.getContent(XMLStreamWriter.class);
    try {
        String pfx = name.getPrefix();
        if (StringUtils.isEmpty(pfx)) {
            pfx = "ns1";
        }
        StaxUtils.writeStartElement(xmlWriter,
                                    pfx,
                                    name.getLocalPart(),
                                    name.getNamespaceURI());
        if (executeBare) {
            new BareOutInterceptor().handleMessage(message);
        }
        xmlWriter.writeEndElement();
    } catch (XMLStreamException e) {
        throw new Fault(new org.apache.cxf.common.i18n.Message("STAX_WRITE_EXC", BUNDLE, e));
    }

}
 
Example #18
Source File: ClientServerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetWSDL() throws Exception {
    String url = "http://localhost:" + PORT + "/SoapContext/SoapPort?wsdl";
    HttpURLConnection httpConnection = getHttpConnection(url);

    // just testing that GZIP is not enabled by default
    httpConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
    httpConnection.connect();

    assertEquals(200, httpConnection.getResponseCode());

    assertEquals("text/xml;charset=utf-8", stripSpaces(httpConnection.getContentType().toLowerCase()));
    assertEquals("OK", httpConnection.getResponseMessage());

    InputStream in = httpConnection.getInputStream();
    assertNotNull(in);

    Document doc = StaxUtils.read(in);
    assertNotNull(doc);
}
 
Example #19
Source File: WSDLGetOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    Document doc = (Document)message.get(WSDLGetInterceptor.DOCUMENT_HOLDER);
    if (doc == null) {
        return;
    }
    message.remove(WSDLGetInterceptor.DOCUMENT_HOLDER);

    XMLStreamWriter writer = message.getContent(XMLStreamWriter.class);
    if (writer == null) {
        return;
    }
    message.put(Message.CONTENT_TYPE, "text/xml");
    try {
        StaxUtils.writeDocument(doc, writer,
                                !MessageUtils.getContextualBoolean(message,
                                                                   StaxOutInterceptor.FORCE_START_DOCUMENT,
                                                                   false),
                                true);
    } catch (XMLStreamException e) {
        throw new Fault(e);
    }
}
 
Example #20
Source File: XMLMessageOutInterceptorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrapOut() throws Exception {
    GreetMe greetMe = new GreetMe();
    greetMe.setRequestType("tli");
    params.add(greetMe);
    common("/wsdl/hello_world_xml_wrapped.wsdl", new QName(wrapNs, "XMLPort"), GreetMe.class);

    BindingInfo bi = super.serviceInfo.getBinding(new QName(wrapNs, "Greeter_XMLBinding"));
    BindingOperationInfo boi = bi.getOperation(new QName(wrapNs, "greetMe"));
    xmlMessage.getExchange().put(BindingOperationInfo.class, boi);

    out.handleMessage(xmlMessage);

    XMLStreamReader reader = getXMLReader();
    DepthXMLStreamReader dxr = new DepthXMLStreamReader(reader);
    StaxUtils.nextEvent(dxr);
    StaxUtils.toNextElement(dxr);
    assertEquals(wrapGreetMeQName.getNamespaceURI(), dxr.getNamespaceURI());
    assertEquals(wrapGreetMeQName.getLocalPart(), dxr.getLocalName());
    StaxUtils.toNextElement(dxr);
    StaxUtils.toNextText(dxr);
    assertEquals(greetMe.getRequestType(), dxr.getText());
}
 
Example #21
Source File: AbstractSTSTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected Element createUserToken(String username, String password)
    throws JAXBException, SAXException,     IOException, ParserConfigurationException, XMLStreamException {

    JAXBElement<UsernameTokenType> supportingToken = createUsernameToken(username, password);
    final JAXBContext jaxbContext = JAXBContext.newInstance(UsernameTokenType.class);
    StringWriter writer = new StringWriter();
    jaxbContext.createMarshaller().marshal(supportingToken, writer);
    writer.flush();
    try (InputStream is = new ByteArrayInputStream(writer.toString().getBytes())) {
        return StaxUtils.read(is).getDocumentElement();
    }
}
 
Example #22
Source File: SOAPHandlerInterceptorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private XMLStreamReader preparemXMLStreamReader(String resouceName) throws Exception {
    InputStream is = this.getClass().getResourceAsStream(resouceName);
    XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(is);

    // skip until soap body
    if (xmlReader.nextTag() == XMLStreamConstants.START_ELEMENT) {
        String ns = xmlReader.getNamespaceURI();
        SoapVersion soapVersion = SoapVersionFactory.getInstance().getSoapVersion(ns);
        // message.setVersion(soapVersion);

        QName qn = xmlReader.getName();
        while (!qn.equals(soapVersion.getBody()) && !qn.equals(soapVersion.getHeader())) {
            while (xmlReader.nextTag() != XMLStreamConstants.START_ELEMENT) {
                // nothing to do
            }
            qn = xmlReader.getName();
        }
        if (qn.equals(soapVersion.getHeader())) {
            XMLStreamReader filteredReader = new PartialXMLStreamReader(xmlReader, soapVersion.getBody());

            StaxUtils.read(filteredReader);
        }
        // advance just past body.
        xmlReader.next();

        while (xmlReader.isWhiteSpace()) {
            xmlReader.next();
        }
    }
    return xmlReader;
}
 
Example #23
Source File: UndertowSpringTypesFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Map<String, ThreadingParameters> createThreadingParametersMap(String s,
                                                                     JAXBContext ctx)
    throws Exception {
    Document doc = StaxUtils.read(new StringReader(s));
    List <ThreadingParametersIdentifiedType> threadingParametersIdentifiedTypes =
        UndertowSpringTypesFactory
            .parseListElement(doc.getDocumentElement(),
                              new QName(UndertowHTTPServerEngineFactoryBeanDefinitionParser.HTTP_UNDERTOW_NS,
                                        "identifiedThreadingParameters"),
                              ThreadingParametersIdentifiedType.class, ctx);
    return toThreadingParameters(threadingParametersIdentifiedTypes);
}
 
Example #24
Source File: IntegrationBaseTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected Representation getRepresentation(String content) throws XMLStreamException {
    Document doc = null;
    doc = StaxUtils.read(new StringReader(content));
    Representation representation = new Representation();
    representation.setAny(doc.getDocumentElement());
    return representation;
}
 
Example #25
Source File: DispatchClientServerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testStAXSourcePAYLOAD() throws Exception {

    URL wsdl = getClass().getResource("/wsdl/hello_world.wsdl");
    assertNotNull(wsdl);

    Service service = Service.create(wsdl, SERVICE_NAME);
    assertNotNull(service);

    Dispatch<StAXSource> disp = service.createDispatch(PORT_NAME, StAXSource.class, Service.Mode.PAYLOAD);
    disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                                 "http://localhost:"
                                 + greeterPort
                                 + "/SOAPDispatchService/SoapDispatchPort");
    QName opQName = new QName("http://apache.org/hello_world_soap_http", "greetMe");
    disp.getRequestContext().put(MessageContext.WSDL_OPERATION, opQName);

    // Test request-response
    InputStream is = getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReq.xml");
    StAXSource staxSourceReq = new StAXSource(StaxUtils.createXMLStreamReader(is));
    assertNotNull(staxSourceReq);
    Source resp = disp.invoke(staxSourceReq);
    assertNotNull(resp);
    assertTrue(resp instanceof StAXSource);
    String expected = "Hello TestSOAPInputMessage";
    String actual = StaxUtils.toString(StaxUtils.read(resp));
    assertTrue("Expected: " + expected, actual.contains(expected));
}
 
Example #26
Source File: JAXBEncoderDecoder.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static XMLStreamWriter getStreamWriter(Object source) throws Fault {
    if (source instanceof XMLStreamWriter) {
        return (XMLStreamWriter)source;
    } else if (source instanceof OutputStream) {
        return StaxUtils.createXMLStreamWriter((OutputStream)source);
    } else if (source instanceof Node) {
        return new W3CDOMStreamWriter((Element)source);
    }
    throw new Fault(new Message("UNKNOWN_SOURCE", LOG, source.getClass().getName()));
}
 
Example #27
Source File: PutTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test(expected = SOAPFaultException.class)
public void wrongStudentPutTest() throws XMLStreamException {
    createStudent();
    CreateResponse createResponse = createStudent();

    Document putStudentXML = StaxUtils.read(
            getClass().getResourceAsStream("/xml/putStudent.xml"));
    Put request = new Put();
    request.setRepresentation(new Representation());
    request.getRepresentation().setAny(putStudentXML.getDocumentElement());

    Resource client = TestUtils.createResourceClient(createResponse.getResourceCreated());
    client.put(request);
}
 
Example #28
Source File: Saml2BearerGrantHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected Element readToken(InputStream tokenStream) {

        try {
            Document doc = StaxUtils.read(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
            return doc.getDocumentElement();
        } catch (Exception ex) {
            throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
        }
    }
 
Example #29
Source File: WadlGeneratorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericImplementation() throws Exception {
    setUpGenericImplementationTest();

    WadlGenerator wg = new WadlGenerator();
    wg.setApplicationTitle("My Application");
    wg.setNamespacePrefix("ns");
    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(ActualResource.class, ActualResource.class, true, true);
    Message m = mockMessage("http://example.com", "/", WadlGenerator.WADL_QUERY, cri);
    Response r = handleRequest(wg, m);
    checkResponse(r);
    Document doc = StaxUtils.read(new StringReader(r.getEntity().toString()));
    checkDocs(doc.getDocumentElement(), "My Application", "", "");
    List<Element> grammarEls = DOMUtils.getChildrenWithName(doc.getDocumentElement(),
                                                            WadlGenerator.WADL_NS,
                                                            "grammars");
    assertEquals(1, grammarEls.size());
    List<Element> schemasEls = DOMUtils.getChildrenWithName(grammarEls.get(0),
                                                            Constants.URI_2001_SCHEMA_XSD,
                                                            "schema");
    assertEquals(2, schemasEls.size());
    
    List<Element> importEls = DOMUtils.getChildrenWithName(schemasEls.get(0),
                                                           Constants.URI_2001_SCHEMA_XSD,
                                                           "import");
    int schemaElementsIndex = !importEls.isEmpty() ? 0 : 1;
    int schemaTypesIndex = schemaElementsIndex == 0 ? 1 : 0;
    
    checkGenericImplSchemaWithTypes(schemasEls.get(schemaTypesIndex));
    checkGenericImplSchemaWithElements(schemasEls.get(schemaElementsIndex));

    List<Element> reps = DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),
                                   WadlGenerator.WADL_NS, "representation");
    assertEquals(2, reps.size());
    assertEquals("ns1:actual", reps.get(0).getAttribute("element"));
    assertEquals("ns1:actual", reps.get(1).getAttribute("element"));

}
 
Example #30
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();
}