Search in sources :

Example 31 with SOAPMessageContext

use of javax.xml.ws.handler.soap.SOAPMessageContext in project cxf by apache.

the class SOAPHandlerInterceptorTest method testChangeSOAPHeaderInBound.

@Test
public void testChangeSOAPHeaderInBound() throws Exception {
    @SuppressWarnings("rawtypes") List<Handler> list = new ArrayList<>();
    list.add(new SOAPHandler<SOAPMessageContext>() {

        public boolean handleMessage(SOAPMessageContext smc) {
            try {
                Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
                if (!outboundProperty.booleanValue()) {
                    // change mustUnderstand to false
                    SOAPMessage message = smc.getMessage();
                    SOAPHeader soapHeader = message.getSOAPHeader();
                    Element headerElementNew = (Element) soapHeader.getFirstChild();
                    SoapVersion soapVersion = Soap11.getInstance();
                    Attr attr = headerElementNew.getOwnerDocument().createAttributeNS(soapVersion.getNamespace(), "SOAP-ENV:mustUnderstand");
                    attr.setValue("false");
                    headerElementNew.setAttributeNodeNS(attr);
                }
            } catch (Exception e) {
                throw new Fault(e);
            }
            return true;
        }

        public boolean handleFault(SOAPMessageContext smc) {
            return true;
        }

        public Set<QName> getHeaders() {
            return null;
        }

        public void close(MessageContext messageContext) {
        }
    });
    HandlerChainInvoker invoker = new HandlerChainInvoker(list);
    IMocksControl control = createNiceControl();
    Binding binding = control.createMock(Binding.class);
    expect(binding.getHandlerChain()).andReturn(list).anyTimes();
    Exchange exchange = control.createMock(Exchange.class);
    expect(exchange.get(HandlerChainInvoker.class)).andReturn(invoker).anyTimes();
    // This is to set direction to inbound
    expect(exchange.getOutMessage()).andReturn(null);
    SoapMessage message = new SoapMessage(new MessageImpl());
    message.setExchange(exchange);
    XMLStreamReader reader = preparemXMLStreamReader("resources/greetMeRpcLitReq.xml");
    message.setContent(XMLStreamReader.class, reader);
    Object[] headerInfo = prepareSOAPHeader();
    message.setContent(Node.class, headerInfo[0]);
    Node node = ((Element) headerInfo[1]).getFirstChild();
    message.getHeaders().add(new Header(new QName(node.getNamespaceURI(), node.getLocalName()), node));
    control.replay();
    SOAPHandlerInterceptor li = new SOAPHandlerInterceptor(binding);
    li.handleMessage(message);
    control.verify();
    // Verify SOAPMessage header
    SOAPMessage soapMessageNew = message.getContent(SOAPMessage.class);
    Element headerElementNew = DOMUtils.getFirstElement(soapMessageNew.getSOAPHeader());
    SoapVersion soapVersion = Soap11.getInstance();
    assertEquals("false", headerElementNew.getAttributeNS(soapVersion.getNamespace(), "mustUnderstand"));
    // Verify XMLStreamReader
    XMLStreamReader xmlReader = message.getContent(XMLStreamReader.class);
    QName qn = xmlReader.getName();
    assertEquals("sendReceiveData", qn.getLocalPart());
    // Verify Header Element
    Iterator<Header> iter = message.getHeaders().iterator();
    Element requiredHeader = null;
    while (iter.hasNext()) {
        Header localHdr = iter.next();
        if (localHdr.getObject() instanceof Element) {
            Element elem = (Element) localHdr.getObject();
            if ("http://apache.org/hello_world_rpclit/types".equals(elem.getNamespaceURI()) && "header1".equals(elem.getLocalName())) {
                requiredHeader = (Element) localHdr.getObject();
                break;
            }
        }
    }
    assertNotNull("Should have found header1", requiredHeader);
    assertEquals("false", requiredHeader.getAttributeNS(soapVersion.getNamespace(), "mustUnderstand"));
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) XMLStreamReader(javax.xml.stream.XMLStreamReader) PartialXMLStreamReader(org.apache.cxf.staxutils.PartialXMLStreamReader) SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) SOAPBodyElement(javax.xml.soap.SOAPBodyElement) SOAPElement(javax.xml.soap.SOAPElement) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) Fault(org.apache.cxf.interceptor.Fault) SOAPMessage(javax.xml.soap.SOAPMessage) Attr(org.w3c.dom.Attr) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) IMocksControl(org.easymock.IMocksControl) MessageContext(javax.xml.ws.handler.MessageContext) SOAPMessageContext(javax.xml.ws.handler.soap.SOAPMessageContext) SOAPHeader(javax.xml.soap.SOAPHeader) Binding(javax.xml.ws.Binding) QName(javax.xml.namespace.QName) SOAPHandler(javax.xml.ws.handler.soap.SOAPHandler) Handler(javax.xml.ws.handler.Handler) IOException(java.io.IOException) SoapVersion(org.apache.cxf.binding.soap.SoapVersion) Exchange(org.apache.cxf.message.Exchange) HandlerChainInvoker(org.apache.cxf.jaxws.handler.HandlerChainInvoker) SOAPHeader(javax.xml.soap.SOAPHeader) Header(org.apache.cxf.headers.Header) SOAPMessageContext(javax.xml.ws.handler.soap.SOAPMessageContext) MessageImpl(org.apache.cxf.message.MessageImpl) Test(org.junit.Test)

Example 32 with SOAPMessageContext

use of javax.xml.ws.handler.soap.SOAPMessageContext in project cxf by apache.

the class SOAPHandlerInterceptor method handleAbort.

private void handleAbort(SoapMessage message, MessageContext context) {
    if (isRequestor(message)) {
        // client side outbound
        if (getInvoker(message).isOutbound()) {
            message.getInterceptorChain().abort();
            MessageObserver observer = message.getExchange().get(MessageObserver.class);
            if (!message.getExchange().isOneWay() && observer != null) {
                Endpoint e = message.getExchange().getEndpoint();
                Message responseMsg = new MessageImpl();
                responseMsg.setExchange(message.getExchange());
                responseMsg = e.getBinding().createMessage(responseMsg);
                // the request message becomes the response message
                message.getExchange().setInMessage(responseMsg);
                SOAPMessage soapMessage = ((SOAPMessageContext) context).getMessage();
                if (soapMessage != null) {
                    responseMsg.setContent(SOAPMessage.class, soapMessage);
                    XMLStreamReader xmlReader = createXMLStreamReaderFromSOAPMessage(soapMessage);
                    responseMsg.setContent(XMLStreamReader.class, xmlReader);
                }
                responseMsg.put(InterceptorChain.STARTING_AT_INTERCEPTOR_ID, SOAPHandlerInterceptor.class.getName());
                observer.onMessage(responseMsg);
            }
        // We dont call onCompletion here, as onCompletion will be called by inbound
        // LogicalHandlerInterceptor
        } else {
            // client side inbound - Normal handler message processing
            // stops, but the inbound interceptor chain still continues, dispatch the message
            // By onCompletion here, we can skip following Logical handlers
            onCompletion(message);
        }
    } else {
        if (!getInvoker(message).isOutbound()) {
            // server side inbound
            message.getInterceptorChain().abort();
            Endpoint e = message.getExchange().getEndpoint();
            if (!message.getExchange().isOneWay()) {
                Message responseMsg = new MessageImpl();
                responseMsg.setExchange(message.getExchange());
                responseMsg = e.getBinding().createMessage(responseMsg);
                message.getExchange().setOutMessage(responseMsg);
                SOAPMessage soapMessage = ((SOAPMessageContext) context).getMessage();
                responseMsg.setContent(SOAPMessage.class, soapMessage);
                InterceptorChain chain = OutgoingChainInterceptor.getOutInterceptorChain(message.getExchange());
                responseMsg.setInterceptorChain(chain);
                // so the idea of starting interceptor chain from any
                // specified point does not work
                // well for outbound case, as many outbound interceptors
                // have their ending interceptors.
                // For example, we can not skip MessageSenderInterceptor.
                chain.doInterceptStartingAfter(responseMsg, SoapPreProtocolOutInterceptor.class.getName());
            }
        } else {
        // server side outbound - Normal handler message processing
        // stops, but still continue the outbound interceptor chain, dispatch the message
        }
    }
}
Also used : InterceptorChain(org.apache.cxf.interceptor.InterceptorChain) MessageObserver(org.apache.cxf.transport.MessageObserver) XMLStreamReader(javax.xml.stream.XMLStreamReader) SoapPreProtocolOutInterceptor(org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor) Endpoint(org.apache.cxf.endpoint.Endpoint) Message(org.apache.cxf.message.Message) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) SOAPMessage(javax.xml.soap.SOAPMessage) SOAPMessageContext(javax.xml.ws.handler.soap.SOAPMessageContext) MessageImpl(org.apache.cxf.message.MessageImpl) SOAPMessage(javax.xml.soap.SOAPMessage)

Example 33 with SOAPMessageContext

use of javax.xml.ws.handler.soap.SOAPMessageContext in project cxf by apache.

the class JaxWsClientTest method testSoapHandler.

@Test
public void testSoapHandler() {
    URL url = getClass().getResource("/wsdl/hello_world.wsdl");
    javax.xml.ws.Service s = javax.xml.ws.Service.create(url, SERVICE_NAME);
    Greeter greeter = s.getPort(PORT_NAME, Greeter.class);
    d.setMessageObserver(new MessageReplayObserver("sayHiResponse.xml"));
    @SuppressWarnings("rawtypes") List<Handler> chain = ((BindingProvider) greeter).getBinding().getHandlerChain();
    chain.add(new SOAPHandler<SOAPMessageContext>() {

        public boolean handleMessage(SOAPMessageContext context) {
            Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
            if (outbound) {
                headers = CastUtils.cast((Map<?, ?>) context.get(MessageContext.HTTP_REQUEST_HEADERS));
                if (headers == null) {
                    headers = new HashMap<>();
                    context.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
                }
                headers.put("My-Custom-Header", Collections.singletonList("value"));
            }
            return true;
        }

        public boolean handleFault(SOAPMessageContext smc) {
            return true;
        }

        public Set<QName> getHeaders() {
            return null;
        }

        public void close(MessageContext messageContext) {
        }
    });
    ((BindingProvider) greeter).getBinding().setHandlerChain(chain);
    String response = greeter.sayHi();
    assertNotNull(response);
    assertTrue("custom header should be present", headers.containsKey("My-Custom-Header"));
    assertTrue("existing SOAPAction header should not be removed", headers.containsKey("SOAPAction"));
}
Also used : Set(java.util.Set) HashMap(java.util.HashMap) SOAPHandler(javax.xml.ws.handler.soap.SOAPHandler) LogicalHandler(javax.xml.ws.handler.LogicalHandler) Handler(javax.xml.ws.handler.Handler) InvocationHandler(java.lang.reflect.InvocationHandler) URL(java.net.URL) SOAPMessageContext(javax.xml.ws.handler.soap.SOAPMessageContext) Greeter(org.apache.hello_world_soap_http.Greeter) MessageContext(javax.xml.ws.handler.MessageContext) SOAPMessageContext(javax.xml.ws.handler.soap.SOAPMessageContext) LogicalMessageContext(javax.xml.ws.handler.LogicalMessageContext) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test)

Example 34 with SOAPMessageContext

use of javax.xml.ws.handler.soap.SOAPMessageContext in project cxf by apache.

the class HandlerInvocationTest method testServerEndpointRemoteFault.

@Test
public void testServerEndpointRemoteFault() throws PingException {
    TestHandler<LogicalMessageContext> handler1 = new TestHandler<>(false);
    TestHandler<LogicalMessageContext> handler2 = new TestHandler<LogicalMessageContext>(false) {

        public boolean handleFault(LogicalMessageContext ctx) {
            super.handleFault(ctx);
            try {
                Boolean outbound = (Boolean) ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
                if (!outbound) {
                    LogicalMessage msg = ctx.getMessage();
                    String payload = convertDOMToString(msg.getPayload());
                    assertTrue(payload.indexOf("<faultstring>" + "servant throws SOAPFaultException" + "</faultstring>") > -1);
                }
            } catch (Exception e) {
                e.printStackTrace();
                fail(e.toString());
            }
            return true;
        }

        private String convertDOMToString(Source s) throws TransformerException {
            StringWriter stringWriter = new StringWriter();
            StreamResult streamResult = new StreamResult(stringWriter);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "no");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.transform(s, streamResult);
            return stringWriter.toString();
        }
    };
    TestSOAPHandler soapHandler1 = new TestSOAPHandler(false);
    TestSOAPHandler soapHandler2 = new TestSOAPHandler(false) {

        public boolean handleFault(SOAPMessageContext ctx) {
            super.handleFault(ctx);
            try {
                Boolean outbound = (Boolean) ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
                if (!outbound) {
                    SOAPEnvelope env = ctx.getMessage().getSOAPPart().getEnvelope();
                    assertTrue("expected SOAPFault in SAAJ model", env.getBody().hasFault());
                }
            } catch (Exception e) {
                e.printStackTrace();
                fail(e.toString());
            }
            return true;
        }
    };
    addHandlersToChain((BindingProvider) handlerTest, handler1, handler2, soapHandler1, soapHandler2);
    try {
        handlerTest.pingWithArgs("servant throw SOAPFaultException");
        fail("did not get expected Exception");
    } catch (SOAPFaultException sfe) {
    // expected
    }
    assertEquals(1, handler1.getHandleMessageInvoked());
    assertEquals(1, handler2.getHandleMessageInvoked());
    assertEquals(1, soapHandler1.getHandleMessageInvoked());
    assertEquals(1, soapHandler2.getHandleMessageInvoked());
    assertEquals(1, handler2.getHandleFaultInvoked());
    assertEquals(1, handler1.getHandleFaultInvoked());
    assertEquals(1, soapHandler1.getHandleFaultInvoked());
    assertEquals(1, soapHandler2.getHandleFaultInvoked());
    assertEquals(1, handler1.getCloseInvoked());
    assertEquals(1, handler2.getCloseInvoked());
    assertEquals(1, soapHandler1.getCloseInvoked());
    assertEquals(1, soapHandler2.getCloseInvoked());
    assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
Also used : LogicalMessageContext(javax.xml.ws.handler.LogicalMessageContext) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) SOAPFaultException(javax.xml.ws.soap.SOAPFaultException) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) PingException(org.apache.handler_test.PingException) ProtocolException(javax.xml.ws.ProtocolException) SOAPFaultException(javax.xml.ws.soap.SOAPFaultException) TransformerException(javax.xml.transform.TransformerException) WebServiceException(javax.xml.ws.WebServiceException) Source(javax.xml.transform.Source) StringWriter(java.io.StringWriter) SOAPMessageContext(javax.xml.ws.handler.soap.SOAPMessageContext) LogicalMessage(javax.xml.ws.LogicalMessage) HandlerTest(org.apache.handler_test.HandlerTest) Test(org.junit.Test)

Example 35 with SOAPMessageContext

use of javax.xml.ws.handler.soap.SOAPMessageContext in project jbossws-cxf by jbossws.

the class EndpointHandler method handleInbound.

@Override
protected boolean handleInbound(SOAPMessageContext msgContext) {
    log.info("handleInbound");
    try {
        SOAPMessage soapMessage = ((SOAPMessageContext) msgContext).getMessage();
        SOAPBody soapBody = soapMessage.getSOAPBody();
        SOAPBodyElement soapBodyElement = (SOAPBodyElement) soapBody.getChildElements().next();
        SOAPElement soapElement = (SOAPElement) soapBodyElement.getChildElements().next();
        String value = soapElement.getValue();
        soapElement.setValue(value + "|EpIn");
    } catch (SOAPException e) {
        throw new WebServiceException(e);
    }
    return true;
}
Also used : SOAPBody(javax.xml.soap.SOAPBody) WebServiceException(javax.xml.ws.WebServiceException) SOAPMessageContext(javax.xml.ws.handler.soap.SOAPMessageContext) SOAPException(javax.xml.soap.SOAPException) SOAPElement(javax.xml.soap.SOAPElement) SOAPMessage(javax.xml.soap.SOAPMessage) SOAPBodyElement(javax.xml.soap.SOAPBodyElement)

Aggregations

SOAPMessageContext (javax.xml.ws.handler.soap.SOAPMessageContext)45 SOAPMessage (javax.xml.soap.SOAPMessage)33 WebServiceException (javax.xml.ws.WebServiceException)24 SOAPException (javax.xml.soap.SOAPException)22 SOAPElement (javax.xml.soap.SOAPElement)18 Test (org.junit.Test)13 SOAPBody (javax.xml.soap.SOAPBody)12 SOAPBodyElement (javax.xml.soap.SOAPBodyElement)10 QName (javax.xml.namespace.QName)7 SoapMessage (org.apache.cxf.binding.soap.SoapMessage)7 IOException (java.io.IOException)6 List (java.util.List)6 Set (java.util.Set)6 ContentType (javax.mail.internet.ContentType)6 SOAPEnvelope (javax.xml.soap.SOAPEnvelope)6 SOAPHeaderElement (javax.xml.soap.SOAPHeaderElement)6 Handler (javax.xml.ws.handler.Handler)6 MessageContext (javax.xml.ws.handler.MessageContext)6 SOAPHandler (javax.xml.ws.handler.soap.SOAPHandler)6 ArrayList (java.util.ArrayList)5