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; }
/** * @return a token which contains a random Unique ID per caller and the caller IP as well */ private String getCaller() { MessageContext msgx = wsContext.getMessageContext(); HttpServletRequest request = ((HttpServletRequest) msgx.get(MessageContext.SERVLET_REQUEST)); String uid = ""; try { Map<String, List<String>> headers = (Map<String, List<String>>) msgx.get(MessageContext.HTTP_REQUEST_HEADERS); uid = headers.get(ApplicationContext.ATS_UID_SESSION_TOKEN).get(0); } catch (Exception e) { if (!alreadyLoggedErrorAboutSessionUid) { log.warn("Could not get ATS UID for call from " + request.getRemoteAddr() + ". This error will not be logged again before Agent restart.", e); alreadyLoggedErrorAboutSessionUid = true; } } return "<Caller: " + request.getRemoteAddr() + "; ATS UID: " + uid + ">"; }
/** * Called by close(MessageContext mc) in a Server Handlertube */ protected void closeServersideHandlers(MessageContext msgContext) { if (processor == null) return; if (remedyActionTaken) { //Close only invoked handlers in the chain //SERVER-SIDE processor.closeHandlers(msgContext, processor.getIndex(), handlers.size() - 1); processor.setIndex(-1); //reset remedyActionTaken remedyActionTaken = false; } else { //Close all handlers in the chain //SERVER-SIDE processor.closeHandlers(msgContext, 0, handlers.size() - 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 (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; } }
@Override @SuppressWarnings("element-type-mismatch") 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.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){ atts.put(att.getContentId(), att.asDataHandler()); } return atts; } return value; }
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; } }
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; } }
/** * 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; }
/** * 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); } }
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; }
@Override public boolean handleMessage(final SOAPMessageContext msgCtx) { // Indicator telling us which direction this message is going in final Boolean outInd = (Boolean) msgCtx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); // Handler must only add security headers to outbound messages if (outInd.booleanValue()) { try { // Get the SOAP Envelope final SOAPEnvelope envelope = msgCtx.getMessage().getSOAPPart().getEnvelope(); // Header may or may not exist yet SOAPHeader header = envelope.getHeader(); if (header == null) header = envelope.addHeader(); // Add WSS Usertoken Element Tree final SOAPElement security = header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); final SOAPElement userToken = security.addChildElement("UsernameToken", "wsse"); userToken.addChildElement("Username", "wsse").addTextNode(userId); userToken.addChildElement("Password", "wsse").addAttribute(new QName("Type"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText").addTextNode(password); } catch (final Exception e) { e.printStackTrace(); return false; } } return true; }
/** * The method is invoked for normal processing of outbound messages. * * @param context * the message context. * @return An indication of whether handler processing should continue for * the current message. Return <code>true</code> to continue * processing. * * @throws Exception * Causes the JAX-WS runtime to cease fault message processing. **/ @Override public boolean handleMessage(SOAPMessageContext context) { Boolean request_p = (Boolean) context .get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (request_p.booleanValue()) { try { SOAPMessage msg = context.getMessage(); SOAPEnvelope env = msg.getSOAPPart().getEnvelope(); SOAPHeader hdr = env.getHeader(); if (hdr == null) { hdr = env.addHeader(); } QName qname_user = new QName("http://com/auth/", "auth"); SOAPHeaderElement helem_user = hdr.addHeaderElement(qname_user); helem_user.setActor(VERSION); if (version != null && version.trim().length() != 0) { helem_user.addTextNode(version); } msg.saveChanges(); message = soapMessage2String(msg); } catch (Exception e) { e.printStackTrace(); } } return true; }
/** * 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; }
/** * The method is invoked for normal processing of outbound messages. * * @param context * the message context. * @return An indication of whether handler processing should continue for * the current message. Return <code>true</code> to continue * processing. * * @throws Exception * Causes the JAX-WS runtime to cease fault message processing. **/ @Override public boolean handleMessage(SOAPMessageContext context) { Boolean request_p = (Boolean) context .get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (request_p.booleanValue()) { try { SOAPMessage msg = context.getMessage(); SOAPEnvelope env = msg.getSOAPPart().getEnvelope(); SOAPHeader hdr = env.getHeader(); if (hdr == null) { hdr = env.addHeader(); } QName qname_user = new QName("http://com/auth/", "auth"); SOAPHeaderElement helem_user = hdr.addHeaderElement(qname_user); helem_user.setActor(VERSION); if (version == null || version.trim().length() == 0) { helem_user.addTextNode(apiVersionInfo.getProperty(VERSION)); } else { helem_user.addTextNode(version); } msg.saveChanges(); message = soapMessage2String(msg); } catch (Exception e) { e.printStackTrace(); } } return true; }
@Before public void setup() { httpRequestMock = mock(HttpServletRequest.class); when(httpRequestMock.getHeader("x-forwarded-for")) .thenReturn("1.1.1.1"); when(httpRequestMock.getHeader("X-Forwarded-For")) .thenReturn("1.1.1.2"); when(httpRequestMock.getRemoteAddr()).thenReturn("255.255.255.255"); wsContextMock = mock(WebServiceContext.class); MessageContext msgContextMock = mock(MessageContext.class); when(msgContextMock.get(MessageContext.SERVLET_REQUEST)).thenReturn( httpRequestMock); when(wsContextMock.getMessageContext()).thenReturn(msgContextMock); }
/** * 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; }
boolean callHandlersOnRequest(MessageUpdatableContext context, boolean isOneWay) { boolean handlerResult; //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 { //CLIENT-SIDE handlerResult = processor.callHandlersRequest(HandlerProcessor.Direction.OUTBOUND, context, !isOneWay); } catch (WebServiceException wse) { remedyActionTaken = true; //no rewrapping throw wse; } catch (RuntimeException re) { remedyActionTaken = true; throw new WebServiceException(re); } if (!handlerResult) { remedyActionTaken = true; } return handlerResult; }
@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; }
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; }
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())); } }
@Override protected void initiateClosing(MessageContext mc) { if (getBinding().getSOAPVersion() != null) { super.initiateClosing(mc); } else { close(mc); super.initiateClosing(mc); } }
/** * 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); } }
@Override @Property(MessageContext.QUERY_STRING) public String getQueryString() { URI requestUri = httpExchange.getRequestURI(); String query = requestUri.getQuery(); if (query != null) return query; return null; }
@Override @Property(MessageContext.PATH_INFO) public String getPathInfo() { URI requestUri = httpExchange.getRequestURI(); String reqPath = requestUri.getPath(); String ctxtPath = httpExchange.getHttpContext().getPath(); if (reqPath.length() > ctxtPath.length()) { return reqPath.substring(ctxtPath.length()); } return null; }