Java Code Examples for javax.xml.ws.handler.MessageContext

The following examples show how to use javax.xml.ws.handler.MessageContext. These examples are extracted from open source projects. 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
void callHandlersOnResponse(MessageUpdatableContext context, boolean handleFault) {

        //Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
        Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
        AttachmentSet attSet = context.packet.getMessage().getAttachments();
        for (Map.Entry<String, DataHandler> entry : atts.entrySet()) {
            String cid = entry.getKey();
            if (attSet.get(cid) == null) { // Otherwise we would be adding attachments twice
                Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
                attSet.add(att);
            }
        }

        try {
            //SERVER-SIDE
            processor.callHandlersResponse(HandlerProcessor.Direction.OUTBOUND, context, handleFault);

        } catch (WebServiceException wse) {
            //no rewrapping
            throw wse;
        } catch (RuntimeException re) {
            throw re;

        }
    }
 
Example 2
Source Project: development   Source File: DiscountServiceWSTest.java    License: Apache License 2.0 6 votes vote down vote up
private WebServiceContext createWebServiceContextMock(String expectedIP,
        String expectedUser) {
    requestMock = mock(HttpServletRequest.class);
    when(requestMock.getRemoteAddr()).thenReturn(expectedIP);

    Principal principalMock = mock(Principal.class);
    when(principalMock.getName()).thenReturn(expectedUser);

    MessageContext msgContextMock = mock(MessageContext.class);
    when(msgContextMock.get(anyString())).thenReturn(requestMock);

    WebServiceContext wsContextMock = mock(WebServiceContext.class);
    when(wsContextMock.getUserPrincipal()).thenReturn(principalMock);
    when(wsContextMock.getMessageContext()).thenReturn(msgContextMock);

    return wsContextMock;
}
 
Example 3
void callHandlersOnResponse(MessageUpdatableContext context, boolean handleFault) {
    //Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
    Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
    AttachmentSet attSet = context.packet.getMessage().getAttachments();
    for (Entry<String, DataHandler> entry : atts.entrySet()) {
        String cid = entry.getKey();
        if (attSet.get(cid) == null) { // Otherwise we would be adding attachments twice
            Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
            attSet.add(att);
        }
    }

    try {
        //SERVER-SIDE
        processor.callHandlersResponse(HandlerProcessor.Direction.OUTBOUND, context, handleFault);

    } catch (WebServiceException wse) {
        //no rewrapping
        throw wse;
    } catch (RuntimeException re) {
        throw re;

    }
}
 
Example 4
Source Project: hottub   Source File: HandlerTube.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Called by close(MessageContext mc) in a Client Handlertube
 */
protected void closeClientsideHandlers(MessageContext msgContext) {
     if (processor == null)
        return;
    if (remedyActionTaken) {
        //Close only invoked handlers in the chain

        //CLIENT-SIDE
        processor.closeHandlers(msgContext, processor.getIndex(), 0);
        processor.setIndex(-1);
        //reset remedyActionTaken
        remedyActionTaken = false;
    } else {
        //Close all handlers in the chain

        //CLIENT-SIDE
        processor.closeHandlers(msgContext, handlers.size() - 1, 0);

    }
}
 
Example 5
public Object get(Object key) {
    if(packet.supports(key))
        return packet.get(key);    // strongly typed

    if(packet.getHandlerScopePropertyNames(true).contains(key))
        return null;            // no such application-scope property

    Object value =  packet.invocationProperties.get(key);

    //add the attachments from the Message to the corresponding attachment property
    if(key.equals(MessageContext.INBOUND_MESSAGE_ATTACHMENTS)){
        Map<String, DataHandler> atts = (Map<String, DataHandler>) value;
        if(atts == null)
            atts = new HashMap<String, DataHandler>();
        AttachmentSet attSet = packet.getMessage().getAttachments();
        for(Attachment att : attSet){
            atts.put(att.getContentId(), att.asDataHandler());
        }
        return atts;
    }
    return value;
}
 
Example 6
Source Project: hottub   Source File: HandlerTube.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Calls close on previously invoked handlers.
 * Also, Cleans up any state left over in the Tube instance from the current
 * invocation, as Tube instances can be reused after the completion of MEP.
 *
 * On Client, SOAPHandlers are closed first and then LogicalHandlers
 * On Server, LogicalHandlers are closed first and then SOAPHandlers
 */
final public void close(MessageContext msgContext) {
    //assuming cousinTube is called if requestProcessingSucessful is true
    if (requestProcessingSucessful) {
        if (cousinTube != null) {
            cousinTube.close(msgContext);
        }

    }
    if (processor != null)
        closeHandlers(msgContext);

    // Clean up the exchange for next invocation.
    exchange = null;
    requestProcessingSucessful = false;

}
 
Example 7
void callHandlersOnResponse(MessageUpdatableContext context, boolean handleFault) {
    //Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
    Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
    AttachmentSet attSet = context.packet.getMessage().getAttachments();
    for (Entry<String, DataHandler> entry : atts.entrySet()) {
        String cid = entry.getKey();
        Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
        attSet.add(att);
    }

    try {
        //SERVER-SIDE
        processor.callHandlersResponse(HandlerProcessor.Direction.OUTBOUND, context, handleFault);

    } catch (WebServiceException wse) {
        //no rewrapping
        throw wse;
    } catch (RuntimeException re) {
        throw re;
    }
}
 
Example 8
Source Project: openjdk-8-source   Source File: Packet.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the QName of the wsdl operation associated with this packet.
 * <p/>
 * Information such as Payload QName, wsa:Action header, SOAPAction HTTP header are used depending on the features
 * enabled on the particular port.
 *
 * @return null if there is no WSDL model or
 *         runtime cannot uniquely identify the wsdl operation from the information in the packet.
 */
@Property(MessageContext.WSDL_OPERATION)
public final
@Nullable
QName getWSDLOperation() {
    if (wsdlOperation != null) return wsdlOperation;
    if ( wsdlOperationMapping == null)  wsdlOperationMapping = getWSDLOperationMapping();
    if ( wsdlOperationMapping != null ) wsdlOperation = wsdlOperationMapping.getOperationName();
    return wsdlOperation;
}
 
Example 9
Source Project: jdk8u60   Source File: HandlerProcessor.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the Message Direction.
 * MessageContext.MESSAGE_OUTBOUND_PROPERTY is changed.
 */
private void setDirection(Direction direction, C context) {
    if (direction == Direction.OUTBOUND) {
        context.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, true);
    } else {
        context.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, false);
    }
}
 
Example 10
public Object get(Object key) {
    if(key == null)
        return null;
    Object value = asMapIncludingInvocationProperties.get(key);
    //add the attachments from the Message to the corresponding attachment property
    if(key.equals(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS) ||
        key.equals(MessageContext.INBOUND_MESSAGE_ATTACHMENTS)){
        Map<String, DataHandler> atts = (Map<String, DataHandler>) value;
        if(atts == null)
            atts = new HashMap<String, DataHandler>();
        AttachmentSet attSet = packet.getMessage().getAttachments();
        for(Attachment att : attSet){
            String cid = att.getContentId();
            if (cid.indexOf("@jaxws.sun.com") == -1) {
                Object a = atts.get(cid);
                if (a == null) {
                    a = atts.get("<" + cid + ">");
                    if (a == null) atts.put(att.getContentId(), att.asDataHandler());
                }
            } else {
                atts.put(att.getContentId(), att.asDataHandler());
            }
        }
        return atts;
    }
    return value;
}
 
Example 11
@Override
protected Packet getResponse(Packet request, Exception e, WSDLPort port, WSBinding binding) {
    Packet response = super.getResponse(request, e, port, binding);
    if (e instanceof HTTPException) {
        if (response.supports(MessageContext.HTTP_RESPONSE_CODE)) {
            response.put(MessageContext.HTTP_RESPONSE_CODE, ((HTTPException)e).getStatusCode());
        }
    }
    return response;
}
 
Example 12
Source Project: cxf   Source File: WebServiceContextImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSetMessageContext() {
    WebServiceContextImpl wsci = new WebServiceContextImpl();
    assertNull(wsci.getMessageContext());

    MessageImpl msg = new MessageImpl();
    final MessageContext ctx = new WrappedMessageContext(msg);
    WebServiceContextImpl.setMessageContext(ctx);

    assertSame(ctx, wsci.getMessageContext());

    Thread t = new Thread() {
            public void run() {
                WebServiceContextImpl threadLocalWSCI = new WebServiceContextImpl();

                assertNull(threadLocalWSCI.getMessageContext());

                MessageImpl msg1 = new MessageImpl();
                MessageContext threadLocalCtx = new WrappedMessageContext(msg1);
                WebServiceContextImpl.setMessageContext(threadLocalCtx);


                assertSame(threadLocalCtx, threadLocalWSCI.getMessageContext());
                assertTrue(ctx !=  threadLocalWSCI.getMessageContext());

            }
        };

    t.start();

    try {
        t.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 13
@Override
protected void initiateClosing(MessageContext mc) {
     if (getBinding().getSOAPVersion() != null) {
        super.initiateClosing(mc);
    } else {
        close(mc);
        super.initiateClosing(mc);
    }
}
 
Example 14
/**
 * Reverses the Message Direction.
 * MessageContext.MESSAGE_OUTBOUND_PROPERTY is changed.
 */
private void reverseDirection(Direction origDirection, C context) {
    if (origDirection == Direction.OUTBOUND) {
        context.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, false);
    } else {
        context.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, true);
    }
}
 
Example 15
@Test
public void testCaptureServiceAndOperationNames_soapException() throws Exception {
  when(mockSoapMessageContext.get(MessageContext.WSDL_SERVICE))
      .thenReturn(wsdlService);
  when(mockSoapMessageContext.getMessage()).thenReturn(mockMessage);
  when(mockMessage.getSOAPBody()).thenThrow(new SOAPException());

  jaxWsSoapContextHandler.captureServiceAndOperationNames(mockSoapMessageContext);
  RequestInfo requestInfo = jaxWsSoapContextHandler.getLastRequestInfoBuilder().build();
  assertEquals(wsdlService.getLocalPart(), requestInfo.getServiceName());
  assertEquals("", requestInfo.getMethodName());
}
 
Example 16
Source Project: openjdk-jdk8u-backup   Source File: Packet.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gives a list of Reference Parameters in the Message
 * <p>
 * Headers which have attribute wsa:IsReferenceParameter="true"
 * This is not cached as one may reset the Message.
 *<p>
 */
@Property(MessageContext.REFERENCE_PARAMETERS)
public
@NotNull
List<Element> getReferenceParameters() {
    Message msg = getMessage();
    List<Element> refParams = new ArrayList<Element>();
    if (msg == null) {
        return refParams;
    }
    MessageHeaders hl = msg.getHeaders();
    for (Header h : hl.asList()) {
        String attr = h.getAttribute(AddressingVersion.W3C.nsUri, "IsReferenceParameter");
        if (attr != null && (attr.equals("true") || attr.equals("1"))) {
            Document d = DOMUtil.createDom();
            SAX2DOMEx s2d = new SAX2DOMEx(d);
            try {
                h.writeTo(s2d, XmlUtil.DRACONIAN_ERROR_HANDLER);
                refParams.add((Element) d.getLastChild());
            } catch (SAXException e) {
                throw new WebServiceException(e);
            }
            /*
            DOMResult result = new DOMResult(d);
            XMLDOMWriterImpl domwriter = new XMLDOMWriterImpl(result);
            try {
                h.writeTo(domwriter);
                refParams.add((Element) result.getNode().getLastChild());
            } catch (XMLStreamException e) {
                throw new WebServiceException(e);
            }
            */
        }
    }
    return refParams;
}
 
Example 17
@Override
protected void initiateClosing(MessageContext mc) {
     if (getBinding().getSOAPVersion() != null) {
        super.initiateClosing(mc);
    } else {
        close(mc);
        super.initiateClosing(mc);
    }
}
 
Example 18
Source Project: uavstack   Source File: JaxWSHookIT.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleFault(SOAPMessageContext context) {

    boolean isOut = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    // inbound
    if (isOut == false) {

        getTargetServer(context);
    }
    return true;
}
 
Example 19
Source Project: cxf   Source File: HWDOMSourceMessageProvider.java    License: Apache License 2.0 5 votes vote down vote up
public DOMSource invoke(DOMSource request) {
    QName qn = (QName)ctx.getMessageContext().get(MessageContext.WSDL_OPERATION);
    if (qn == null) {
        throw new RuntimeException("No Operation Name");
    }

    //XMLUtils.writeTo(request, System.out);
    DOMSource response = new DOMSource();
    try {
        SOAPMessage msg = factory.createMessage();
        msg.getSOAPPart().setContent(request);
        SOAPBody body = msg.getSOAPBody();
        Node n = body.getFirstChild();

        while (n.getNodeType() != Node.ELEMENT_NODE) {
            n = n.getNextSibling();
        }
        if (n.getLocalName().equals(sayHi.getLocalPart())) {
            response.setNode(sayHiResponse.getSOAPPart());
        } else if (n.getLocalName().equals(greetMe.getLocalPart())) {
            response.setNode(greetMeResponse.getSOAPPart());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return response;
}
 
Example 20
Source Project: jdk8u60   Source File: SOAPMessageDispatch.java    License: GNU General Public License v2.0 5 votes vote down vote up
Packet createPacket(SOAPMessage arg) {
    Iterator iter = arg.getMimeHeaders().getAllHeaders();
    Headers ch = new Headers();
    while(iter.hasNext()) {
        MimeHeader mh = (MimeHeader) iter.next();
        ch.add(mh.getName(), mh.getValue());
    }
    Packet packet = new Packet(SAAJFactory.create(arg));
    packet.invocationProperties.put(MessageContext.HTTP_REQUEST_HEADERS, ch);
    return packet;
}
 
Example 21
public MessageContext getMessageContext() {
    Packet packet = getRequestPacket();
    if (packet == null) {
        throw new IllegalStateException("getMessageContext() can only be called while servicing a request");
    }
    return new EndpointMessageContextImpl(packet);
}
 
Example 22
Source Project: hottub   Source File: XMLHandlerProcessor.java    License: GNU General Public License v2.0 5 votes vote down vote up
final void insertFaultMessage(C context,
        ProtocolException exception) {
    if(exception instanceof HTTPException) {
        context.put(MessageContext.HTTP_RESPONSE_CODE,((HTTPException)exception).getStatusCode());
    }
    if (context != null) {
        // non-soap case
        context.setPacketMessage(Messages.createEmpty(binding.getSOAPVersion()));
    }
}
 
Example 23
/**
 * Captures the raw XML message behind a SOAP interaction.
 *
 * @param context the context of the SOAP message passing through this handler
 */
private void captureSoapXml(SOAPMessageContext context) {
  SOAPMessage message = context.getMessage();
  if ((Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)) {
    // Outbound message (request).
    requestInfoXPathSet.parseMessage(lastRequestInfo, message);
  } else {
    // Inbound message (response).
    responseInfoXPathSet.parseMessage(lastResponseInfo, message);
  }
}
 
Example 24
Source Project: development   Source File: OperationServiceBean.java    License: Apache License 2.0 5 votes vote down vote up
private RequestLogEntry createLogEntry(String title) {
    final ServletContext servletContext = (ServletContext) context
            .getMessageContext().get(MessageContext.SERVLET_CONTEXT);
    final RequestLog log = (RequestLog) servletContext
            .getAttribute(InitServlet.REQUESTLOG);
    final RequestLogEntry entry = log.createEntry(
            OperationService.class.getSimpleName() + "." + title,
            RequestDirection.INBOUND);
    ServletRequest request = (ServletRequest) context.getMessageContext()
            .get(MessageContext.SERVLET_REQUEST);
    entry.setHost(request.getRemoteHost());
    return entry;
}
 
Example 25
@Test
public void testHandleMessage_outboundNoHeaders() throws Exception {
  final String mockSoapXml = "<Hi>Hello world!</Hi>";
  Answer<Object> transform =
      (invocation) -> {
        StreamResult stream = (StreamResult) invocation.getArguments()[1];
        Streams.write(mockSoapXml, stream.getOutputStream(), Charset.forName(UTF_8));
        return null;
      };

  when(mockSoapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY))
      .thenReturn(Boolean.TRUE);
  when(mockSoapMessageContext.getMessage()).thenReturn(mockMessage);
  when(mockMessage.getSOAPPart()).thenReturn(mockSoapPart);
  when(mockSoapPart.getEnvelope()).thenReturn(mockEnvelope);
  when(mockEnvelope.addHeader()).thenReturn(mockHeader);

  // captureServiceAndOperationNames
  when(mockSoapMessageContext.get(MessageContext.WSDL_SERVICE))
      .thenReturn(wsdlService);
  when(mockSoapMessageContext.getMessage()).thenReturn(mockMessage);
  when(mockMessage.getSOAPBody()).thenReturn(mockSoapBody);
  when(mockMessage.getSOAPPart()).thenReturn(mockSoapPart);
  when(mockSoapBody.getFirstChild()).thenReturn(firstChild);
  when(firstChild.getLocalName()).thenReturn(OPERATION_LOCAL_NAME);

  // captureSoapXml
  when(mockSoapMessageContext.getMessage()).thenReturn(mockMessage);
  when(mockTransformerSupplier.get()).thenReturn(mockTransformer);
  Mockito.doAnswer(transform).when(mockTransformer).transform(any(), any());

  assertTrue(jaxWsSoapContextHandler.handleMessage(mockSoapMessageContext));
  RequestInfo requestInfo = jaxWsSoapContextHandler.getLastRequestInfoBuilder().build();
  assertEquals(mockSoapXml, requestInfo.getPayload());
  assertEquals(wsdlService.getLocalPart(), requestInfo.getServiceName());
  assertEquals(OPERATION_LOCAL_NAME, requestInfo.getMethodName());
}
 
Example 26
Source Project: cxf   Source File: TestHandlerBase.java    License: Apache License 2.0 5 votes vote down vote up
protected List<String> getHandlerInfoList(MessageContext ctx) {
    List<String> handlerInfoList = null;
    if (ctx.containsKey("handler.info")) {
        handlerInfoList = CastUtils.cast((List<?>)ctx.get("handler.info"));
    } else {
        handlerInfoList = new ArrayList<>();
        ctx.put("handler.info", handlerInfoList);
        ctx.setScope("handler.info", MessageContext.Scope.APPLICATION);
    }
    return handlerInfoList;
}
 
Example 27
Source Project: tomee   Source File: JaxWsInvocationTest.java    License: Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object invoke(final InvocationContext context) throws Exception {

    /**
     * For JAX-WS invocations context.getContextData() must return the 
     * JAX-WS MessageContex. As per the agreement between OpenEJB and the Web Service Provider
     * the MessageContex should have been passed into the container.invoke method
     * and the container should then ensure it's available via getContextData()
     * for the duration of this call.
     */
    final MessageContext messageContext = (MessageContext) context.getContextData();

    org.junit.Assert.assertNotNull("message context should not be null", messageContext);
    org.junit.Assert.assertTrue("the Web Service Provider's message context should be used", messageContext instanceof FakeMessageContext);

    // Try to get JAX-RPC context, should throw an exception since it's JAX-WS
    try {
        ctx.getMessageContext();
        org.junit.Assert.fail("Did not throw exception");
    } catch (final IllegalStateException e) {
        // that's expected since it's JAX-WS
    }

    // test @Resource WebServiceContext injection
    org.junit.Assert.assertNotNull("web service context should not be null", wsContext);
    org.junit.Assert.assertEquals("msg context should be the smae", messageContext, wsContext.getMessageContext());

    org.junit.Assert.assertFalse("user in role 'foo'", wsContext.isUserInRole("foo"));
    org.junit.Assert.assertNotNull("user principal", wsContext.getUserPrincipal());

    calls.add(Call.Bean_Invoke_BEFORE);
    final Object o = context.proceed();
    calls.add(Call.Bean_Invoke_AFTER);
    return o;
}
 
Example 28
@Test
public void shouldHandleOutgoingContextInOutgoingMethod() {
	final SOAPMessageContext messageContext = mock(SOAPMessageContext.class);
	when(messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)).thenReturn(Boolean.TRUE);
	unit.handleMessage(messageContext);

	verify(unit).handleOutgoing(messageContext);
}
 
Example 29
/** {@inheritDoc} */
public void close(MessageContext arg0) {}
 
Example 30
@Property(MessageContext.SERVLET_RESPONSE)
public Object getServletResponse() {
    return httpExchange.getAttribute(MessageContext.SERVLET_RESPONSE);
}