org.apache.cxf.binding.soap.saaj.SAAJUtils Java Examples

The following examples show how to use org.apache.cxf.binding.soap.saaj.SAAJUtils. 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: AbstractModifyRequestInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(SoapMessage mc) throws Fault {
    SOAPMessage saaj = mc.getContent(SOAPMessage.class);
    try {
        Iterator<?> secHeadersIterator =
            SAAJUtils.getHeader(saaj).getChildElements(SEC_HEADER);
        if (secHeadersIterator.hasNext()) {
            SOAPHeaderElement securityHeader =
                (SOAPHeaderElement)secHeadersIterator.next();
            modifySecurityHeader(securityHeader);
        }

        modifySOAPBody(SAAJUtils.getBody(saaj));
    } catch (SOAPException ex) {
        throw new Fault(ex);
    }
}
 
Example #2
Source File: TestSOAPHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
private SOAPFaultException createSOAPFaultExceptionWithDetail(String faultString)
    throws SOAPException {

    SOAPFault fault = SOAPFactory.newInstance().createFault();

    QName faultName = new QName(SOAPConstants.URI_NS_SOAP_ENVELOPE,
                    "Server");
    SAAJUtils.setFaultCode(fault, faultName);
    fault.setFaultActor("http://gizmos.com/orders");
    fault.setFaultString(faultString);

    Detail detail = fault.addDetail();

    QName entryName = new QName("http://gizmos.com/orders/",
                    "order", "PO");
    DetailEntry entry = detail.addDetailEntry(entryName);
    entry.addTextNode("Quantity element does not have a value");

    QName entryName2 = new QName("http://gizmos.com/orders/",
                    "order", "PO");
    DetailEntry entry2 = detail.addDetailEntry(entryName2);
    entry2.addTextNode("Incomplete address: no zip code");

    return new SOAPFaultException(fault);
}
 
Example #3
Source File: SOAPHandlerInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected QName getOpQName(Exchange ex, Object data) {
    SOAPMessageContextImpl sm = (SOAPMessageContextImpl)data;
    try {
        SOAPMessage msg = sm.getMessage();
        if (msg == null) {
            return null;
        }
        SOAPBody body = SAAJUtils.getBody(msg);
        if (body == null) {
            return null;
        }
        org.w3c.dom.Node nd = body.getFirstChild();
        while (nd != null && !(nd instanceof org.w3c.dom.Element)) {
            nd = nd.getNextSibling();
        }
        if (nd != null) {
            return new QName(nd.getNamespaceURI(), nd.getLocalName());
        }
    } catch (SOAPException e) {
        //ignore, nothing we can do
    }
    return null;
}
 
Example #4
Source File: TestHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SOAPFaultException createSOAPFaultException(String faultString) {
    try {
        SOAPFault fault = SOAPFactory.newInstance().createFault();
        fault.setFaultString(faultString);
        SAAJUtils.setFaultCode(fault, new QName("http://cxf.apache.org/faultcode", "Server"));
        return new SOAPFaultException(fault);
    } catch (SOAPException e) {
        // do nothing
    }
    return null;
}
 
Example #5
Source File: CustomUTValidator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    if (credential == null || credential.getUsernametoken() == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
    }

    // Need to use SAAJ to get the SOAP Body as we are just using the UsernameTokenInterceptor
    SOAPMessage soapMessage = getSOAPMessage((SoapMessage)data.getMsgContext());
    try {
        Element soapBody = SAAJUtils.getBody(soapMessage);

        if (soapBody != null) {
            // Find custom Element in the SOAP Body
            Element realm = XMLUtils.findElement(soapBody, "realm", "http://cxf.apache.org/custom");
            if (realm != null) {
                String realmStr = realm.getTextContent();
                if ("custom-realm".equals(realmStr)) {

                    UsernameTokenValidator validator = new UsernameTokenValidator();
                    return validator.validate(credential, data);
                }
            }
        }
    } catch (SOAPException ex) {
        // ignore
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
}
 
Example #6
Source File: DispatchImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private QName getPayloadElementName(SOAPMessage soapMessage) {
    try {
        // we only care about the first element node, not text nodes
        Element element = DOMUtils.getFirstElement(SAAJUtils.getBody(soapMessage));
        if (element != null) {
            return DOMUtils.getElementQName(element);
        }
    } catch (Exception e) {
        //ignore
    }
    return null;
}
 
Example #7
Source File: SOAPHandlerInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected MessageContext createProtocolMessageContext(SoapMessage message) {
    SOAPMessageContextImpl sm = new SOAPMessageContextImpl(message);

    Exchange exch = message.getExchange();
    setupBindingOperationInfo(exch, sm);
    SOAPMessage msg = sm.getMessage();
    if (msg != null) {
        try {
            List<SOAPElement> params = new ArrayList<>();
            message.put(MessageContext.REFERENCE_PARAMETERS, params);
            SOAPHeader head = SAAJUtils.getHeader(msg);
            if (head != null) {
                Iterator<Node> it = CastUtils.cast(head.getChildElements());
                while (it != null && it.hasNext()) {
                    Node nd = it.next();
                    if (nd instanceof SOAPElement) {
                        SOAPElement el = (SOAPElement) nd;
                        if (el.hasAttributeNS(Names.WSA_NAMESPACE_NAME, "IsReferenceParameter")
                                && ("1".equals(el.getAttributeNS(Names.WSA_NAMESPACE_NAME,
                                "IsReferenceParameter"))
                                || Boolean.parseBoolean(el.getAttributeNS(Names.WSA_NAMESPACE_NAME,
                                "IsReferenceParameter")))) {
                            params.add(el);
                        }
                    }
                }
            }
            if (isRequestor(message) && msg.getSOAPPart().getEnvelope().getBody() != null
                    && msg.getSOAPPart().getEnvelope().getBody().hasFault()) {
                return null;
            }
        } catch (SOAPException e) {
            throw new Fault(e);
        }
    }

    return sm;
}
 
Example #8
Source File: CustomUTValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    if (credential == null || credential.getUsernametoken() == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
    }

    // Need to use SAAJ to get the SOAP Body as we are just using the UsernameTokenInterceptor
    SOAPMessage soapMessage = getSOAPMessage((SoapMessage)data.getMsgContext());
    try {
        Element soapBody = SAAJUtils.getBody(soapMessage);

        if (soapBody != null) {
            // Find custom Element in the SOAP Body
            Element realm = XMLUtils.findElement(soapBody, "realm", "http://cxf.apache.org/custom");
            if (realm != null) {
                String realmStr = realm.getTextContent();
                if ("custom-realm".equals(realmStr)) {

                    UsernameTokenValidator validator = new UsernameTokenValidator();
                    return validator.validate(credential, data);
                }
            }
        }
    } catch (SOAPException ex) {
        // ignore
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
}
 
Example #9
Source File: DispatchClientServerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handleResponse(Response<SOAPMessage> response) {
    try {
        SOAPMessage reply = response.get();
        replyBuffer = DOMUtils.getContent(SAAJUtils.getBody(reply).getFirstChild().getFirstChild());
    } catch (Exception e) {
        //e.printStackTrace();
    }
}
 
Example #10
Source File: DispatchClientServerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateDispatchWithEPR() throws Exception {

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

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

    W3CEndpointReferenceBuilder builder = new  W3CEndpointReferenceBuilder();
    builder.address("http://localhost:"
                    + greeterPort
                    + "/SOAPDispatchService/SoapDispatchPort");
    builder.serviceName(SERVICE_NAME);
    builder.endpointName(PORT_NAME);
    W3CEndpointReference w3cEpr = builder.build();
    Dispatch<SOAPMessage> disp = service
        .createDispatch(w3cEpr, SOAPMessage.class, Service.Mode.MESSAGE);
    InputStream is = getClass().getResourceAsStream("resources/GreetMeDocLiteralReq.xml");
    SOAPMessage soapReqMsg = MessageFactory.newInstance().createMessage(null, is);
    assertNotNull(soapReqMsg);
    SOAPMessage soapResMsg = disp.invoke(soapReqMsg);

    assertNotNull(soapResMsg);
    String expected = "Hello TestSOAPInputMessage";
    assertEquals("Response should be : Hello TestSOAPInputMessage", expected,
                 DOMUtils.getAllContent(SAAJUtils.getBody(soapResMsg)).trim());
}
 
Example #11
Source File: HWSoapMessageProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public SOAPMessage invoke(SOAPMessage request) {
    SOAPMessage response = null;
    try {
        SOAPBody body = SAAJUtils.getBody(request);
        Node n = body.getFirstChild();

        while (n.getNodeType() != Node.ELEMENT_NODE) {
            n = n.getNextSibling();
        }
        if (n.getLocalName().equals(sayHi.getLocalPart())) {
            response = sayHiResponse;
            if (request.countAttachments() > 0) {
                MessageFactory factory = MessageFactory.newInstance();
                InputStream is = getClass().getResourceAsStream("resources/sayHiRpcLiteralResp.xml");
                response = factory.createMessage(null, is);
                is.close();
                Iterator<AttachmentPart> it = CastUtils.cast(request.getAttachments(),
                                                             AttachmentPart.class);
                while (it.hasNext()) {
                    response.addAttachmentPart(it.next());
                }
            }
        } else if (n.getLocalName().equals(greetMe.getLocalPart())) {
            response = greetMeResponse;
        } else {
            response = request;
            //response.writeTo(System.out);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return response;
}
 
Example #12
Source File: NBSoapMessageDocProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public SOAPMessage invoke(SOAPMessage request) {
    SOAPBody body = null;
    try {
        body = SAAJUtils.getBody(request);
    } catch (SOAPException e) {
        throw new RuntimeException("soap body expected");
    }
    if (body.getFirstChild() != null) {
        throw new RuntimeException("no body expected");
    }
    return sayHiResponse;
}
 
Example #13
Source File: HandlerTestImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SOAPFaultException createSOAPFaultException(String faultString) {
    try {
        SOAPFault fault = SOAPFactory.newInstance().createFault();
        fault.setFaultString(faultString);
        SAAJUtils.setFaultCode(fault, new QName("http://cxf.apache.org/faultcode", "Server"));
        return new SOAPFaultException(fault);
    } catch (SOAPException e) {
        // do nothing
    }
    return null;
}
 
Example #14
Source File: DispatchClientServerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testSOAPMessage() throws Exception {

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

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

    Dispatch<SOAPMessage> disp = service
        .createDispatch(PORT_NAME, SOAPMessage.class, Service.Mode.MESSAGE);
    disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                                 "http://localhost:"
                                 + greeterPort
                                 + "/SOAPDispatchService/SoapDispatchPort");

    // Test request-response
    InputStream is = getClass().getResourceAsStream("resources/GreetMeDocLiteralReq.xml");
    SOAPMessage soapReqMsg = MessageFactory.newInstance().createMessage(null, is);
    assertNotNull(soapReqMsg);
    SOAPMessage soapResMsg = disp.invoke(soapReqMsg);

    assertNotNull(soapResMsg);
    String expected = "Hello TestSOAPInputMessage";
    assertEquals("Response should be : Hello TestSOAPInputMessage", expected,
                 DOMUtils.getContent(SAAJUtils.getBody(soapResMsg)
                                         .getFirstChild().getFirstChild()).trim());

    // Test oneway
    InputStream is1 = getClass().getResourceAsStream("resources/GreetMe1WDocLiteralReq2.xml");
    SOAPMessage soapReqMsg1 = MessageFactory.newInstance().createMessage(null, is1);
    assertNotNull(soapReqMsg1);
    disp.invokeOneWay(soapReqMsg1);

    // Test async polling
    InputStream is2 = getClass().getResourceAsStream("resources/GreetMeDocLiteralReq2.xml");
    SOAPMessage soapReqMsg2 = MessageFactory.newInstance().createMessage(null, is2);
    assertNotNull(soapReqMsg2);

    Response<?> response = disp.invokeAsync(soapReqMsg2);
    SOAPMessage soapResMsg2 = (SOAPMessage)response.get();
    assertNotNull(soapResMsg2);
    String expected2 = "Hello TestSOAPInputMessage2";
    assertEquals("Response should be : Hello TestSOAPInputMessage2", expected2,
                 DOMUtils.getContent(SAAJUtils.getBody(soapResMsg2).getFirstChild().getFirstChild()));

    // Test async callback
    InputStream is3 = getClass().getResourceAsStream("resources/GreetMeDocLiteralReq3.xml");
    SOAPMessage soapReqMsg3 = MessageFactory.newInstance().createMessage(null, is3);
    assertNotNull(soapReqMsg3);
    TestSOAPMessageHandler tsmh = new TestSOAPMessageHandler();
    Future<?> f = disp.invokeAsync(soapReqMsg3, tsmh);
    assertNotNull(f);
    waitForFuture(f);

    String expected3 = "Hello TestSOAPInputMessage3";
    assertEquals("Response should be : Hello TestSOAPInputMessage3",
                 expected3, tsmh.getReplyBuffer().trim());

}
 
Example #15
Source File: HWSoapMessageDocProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
public SOAPMessage invoke(SOAPMessage request) {
    QName qn = (QName)ctx.getMessageContext().get(MessageContext.WSDL_OPERATION);
    if (qn == null) {
        throw new RuntimeException("No Operation Name");
    }

    SOAPMessage response = null;
    SOAPBody body = null;
    try {
        body = SAAJUtils.getBody(request);
    } catch (SOAPException e) {
        return null;
    }
    Node n = body.getFirstChild();

    while (n.getNodeType() != Node.ELEMENT_NODE) {
        n = n.getNextSibling();
    }
    if (n.getLocalName().equals(sayHi.getLocalPart())) {
        response = sayHiResponse;
    } else if (n.getLocalName().equals(greetMe.getLocalPart())) {
        Element el = DOMUtils.getFirstElement(n);
        String v = DOMUtils.getContent(el);
        if (v.contains("Return sayHi")) {
            response = sayHiResponse;
        } else if (v.contains("exceed maxLength")) {
            response = greetMeResponseExceedMaxLengthRestriction;
        } else if (v.contains("throwFault")) {
            try {
                SOAPFactory f = SOAPFactory.newInstance();
                SOAPFault soapFault = f.createFault();

                soapFault.setFaultString("Test Fault String ****");

                Detail detail = soapFault.addDetail();
                detail = soapFault.getDetail();

                QName qName = new QName("http://www.Hello.org/greeter", "TestFault", "ns");
                DetailEntry de = detail.addDetailEntry(qName);

                qName = new QName("http://www.Hello.org/greeter", "ErrorCode", "ns");
                SOAPElement errorElement = de.addChildElement(qName);
                errorElement.setTextContent("errorcode");
                throw new SOAPFaultException(soapFault);
            } catch (SOAPException ex) {
                //ignore
            }

        } else {
            response = greetMeResponse;
        }
    }
    return response;
}
 
Example #16
Source File: TestSOAPHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
private SOAPFaultException createSOAPFaultException(String faultString) throws SOAPException {
    SOAPFault fault = SOAPFactory.newInstance().createFault();
    fault.setFaultString(faultString);
    SAAJUtils.setFaultCode(fault, new QName("http://cxf.apache.org/faultcode", "Server"));
    return new SOAPFaultException(fault);
}
 
Example #17
Source File: AbstractBindingBuilder.java    From cxf with Apache License 2.0 4 votes vote down vote up
public AbstractBindingBuilder(
                       WSSConfig config,
                       AbstractBinding binding,
                       SOAPMessage saaj,
                       WSSecHeader secHeader,
                       AssertionInfoMap aim,
                       SoapMessage message) throws SOAPException {
    super(message);
    this.wssConfig = config;
    this.binding = binding;
    this.aim = aim;
    this.secHeader = secHeader;
    this.saaj = saaj;
    message.getExchange().put(WSHandlerConstants.SEND_SIGV, signatures);

    boolean storeBytes =
        MessageUtils.getContextualBoolean(
            message, SecurityConstants.STORE_BYTES_IN_ATTACHMENT, true
        );
    boolean mtomEnabled = AttachmentUtil.isMtomEnabled(message);
    if (storeBytes && mtomEnabled) {
        storeBytesInAttachment = true;
        if (binding instanceof AbstractSymmetricAsymmetricBinding
            && (ProtectionOrder.EncryptBeforeSigning
                == ((AbstractSymmetricAsymmetricBinding)binding).getProtectionOrder()
                || ((AbstractSymmetricAsymmetricBinding)binding).isProtectTokens())) {
            LOG.fine("Disabling SecurityConstants.STORE_BYTES_IN_ATTACHMENT due to "
                + "EncryptBeforeSigning or ProtectTokens policy.");
            storeBytesInAttachment = false;
        }
    }
    expandXopInclude = MessageUtils.getContextualBoolean(
        message, SecurityConstants.EXPAND_XOP_INCLUDE, mtomEnabled);

    wsDocInfo = new WSDocInfo(secHeader.getSecurityHeaderElement().getOwnerDocument());

    Element soapBody = SAAJUtils.getBody(saaj);
    if (soapBody != null) {
        callbackLookup = new CXFCallbackLookup(soapBody.getOwnerDocument(), soapBody);
    } else {
        callbackLookup = null;
    }
}