Java Code Examples for javax.xml.ws.handler.MessageContext#get()

The following examples show how to use javax.xml.ws.handler.MessageContext#get() . 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: AgentWsImpl.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * @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 + ">";
}
 
Example 2
Source File: GreeterSessionImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void greetMeOneWay(String me) {
    LOG.info("Executing operation greetMeOneWay");
    LOG.info("Message received: " + me);
    MessageContext mc = context.getMessageContext();
    HttpServletRequest req = (HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST);

    HttpSession session = req.getSession();
    if (session == null) {
        throw new WebServiceException("No session in WebServiceContext");
    }
    String name = (String)session.getAttribute("name");
    if (name == null) {
        name = me;
        LOG.info("Starting the Session");
    }

    session.setAttribute("name", me);

}
 
Example 3
Source File: AbstractJAXWSMethodInvoker.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void updateHeader(Exchange exchange, MessageContext ctx) {
    if (ctx.containsKey(Header.HEADER_LIST)
            && ctx.get(Header.HEADER_LIST) instanceof List<?>) {
        List<?> list = (List<?>) ctx.get(Header.HEADER_LIST);
        if (list != null && !list.isEmpty()) {
            SoapMessage sm = (SoapMessage) createResponseMessage(exchange);
            if (sm != null) {
                Iterator<?> iter = list.iterator();
                while (iter.hasNext()) {
                    Header header = (Header) iter.next();
                    if (header.getDirection() != Header.Direction.DIRECTION_IN
                        && !header.getName().getNamespaceURI().
                            equals("http://docs.oasis-open.org/wss/2004/01/"
                                    + "oasis-200401-wss-wssecurity-secext-1.0.xsd")
                               && !header.getName().getNamespaceURI().
                                   equals("http://docs.oasis-open.org/"
                                          + "wss/oasis-wss-wssecurity-secext-1.1.xsd")) {
                        //don't copy over security header, out interceptor chain will take care of it.
                        sm.getHeaders().add(header);
                    }
                }
            }
        }
    }
}
 
Example 4
Source File: GreeterSessionImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void greetMeOneWay(String me) {
    LOG.info("Executing operation greetMeOneWay");
    LOG.info("Message received: " + me);
    MessageContext mc = context.getMessageContext();
    HttpServletRequest req = (HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST);

    HttpSession session = req.getSession();
    if (session == null) {
        throw new WebServiceException("No session in WebServiceContext");
    }
    String name = (String)session.getAttribute("name");
    if (name == null) {
        name = me;
        LOG.info("Starting the Session");
    }

    session.setAttribute("name", me);

}
 
Example 5
Source File: LoggingHandler.java    From juddi with Apache License 2.0 6 votes vote down vote up
private void unregisterMessage(MessageContext context)
{
    RequestData reqData = (RequestData) context.get(XLT_REQUEST_DATA);

    if (reqData != null)
    {
        reqData.setRunTime();
        reqData.setFailed(isFaultReceived(context));
        reqData.setBytesReceived(0);
        reqData.setResponseCode(getResponseCode(context));
        reqData.setUrl(getServiceUrl(context));
        reqData.setContentType(getContentType(context));

        Session.getCurrent().getDataManager().logDataRecord(reqData);
    }
}
 
Example 6
Source File: ContextPropertiesMappingTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateWebServiceContextWithInAttachments() {
    Exchange exchange = new ExchangeImpl();
    Message inMessage = new MessageImpl();

    Collection<Attachment> attachments = new LinkedList<>();

    DataSource source = new ByteDataSource(new byte[0], "text/xml");

    DataHandler handler1 = new DataHandler(source);
    attachments.add(new AttachmentImpl("part1", handler1));
    DataHandler handler2 = new DataHandler(source);
    attachments.add(new AttachmentImpl("part2", handler2));
    inMessage.setAttachments(attachments);

    inMessage.putAll(message);
    exchange.setInMessage(inMessage);
    exchange.setOutMessage(new MessageImpl());

    MessageContext ctx = new WrappedMessageContext(exchange.getInMessage(), Scope.APPLICATION);

    Object inAttachments = ctx.get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS);
    assertNotNull("inbound attachments object must be initialized", inAttachments);
    assertTrue("inbound attachments must be in a Map", inAttachments instanceof Map);
    Map<String, DataHandler> dataHandlers = CastUtils.cast((Map<?, ?>)inAttachments);
    assertEquals("two inbound attachments expected", 2, dataHandlers.size());

    assertTrue("part1 attachment is missing", dataHandlers.containsKey("part1"));
    // should do as it's the same instance
    assertTrue("part1 handler is missing", dataHandlers.get("part1") == handler1);
    assertTrue("part2 attachment is missing", dataHandlers.containsKey("part2"));
    assertTrue("part2 handler is missing", dataHandlers.get("part2") == handler2);
}
 
Example 7
Source File: ManualNumberImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * pull id from manual context appendage
 */
protected String idFromMessageContext(MessageContext mc) {

    String id = null;
    String path = (String)mc.get(MessageContext.PATH_INFO);
    if (null != path) {
        id = path.substring(path.lastIndexOf('/') + 1);
    }
    return id;
}
 
Example 8
Source File: GreeterSessionImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public String greetMe(String me) {
    LOG.info("Executing operation greetMe");
    LOG.info("Message received: " + me);
    MessageContext mc = context.getMessageContext();
    HttpServletRequest req = (HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST);
    Cookie[] cookies = req.getCookies();
    String val = "";
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            val += ";" + cookie.getName() + "=" + cookie.getValue();
        }
    }


    HttpSession session = req.getSession();
    // Get a session property "counter" from context
    if (session == null) {
        throw new WebServiceException("No session in WebServiceContext");
    }
    String name = (String)session.getAttribute("name");
    if (name == null) {
        name = me;
        LOG.info("Starting the Session");
    }

    session.setAttribute("name", me);

    return "Hello " + name + val;
}
 
Example 9
Source File: AbstractJAXWSMethodInvoker.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void updateWebServiceContext(Exchange exchange, MessageContext ctx) {
    // Guard against wrong type associated with header list.
    // Need to copy header only if the message is going out.
    if (ctx.containsKey(Header.HEADER_LIST)
            && ctx.get(Header.HEADER_LIST) instanceof List<?>) {
        List<?> list = (List<?>) ctx.get(Header.HEADER_LIST);
        if (list != null && !list.isEmpty()) {
            SoapMessage sm = (SoapMessage) createResponseMessage(exchange);
            if (sm != null) {
                Iterator<?> iter = list.iterator();
                while (iter.hasNext()) {
                    sm.getHeaders().add((Header) iter.next());
                }
            }
        }
    }
    if (exchange.getOutMessage() != null) {
        Message out = exchange.getOutMessage();
        if (out.containsKey(Message.PROTOCOL_HEADERS)) {
            Map<String, List<String>> heads = CastUtils
                .cast((Map<?, ?>)exchange.getOutMessage().get(Message.PROTOCOL_HEADERS));
            if (heads.containsKey("Content-Type")) {
                List<String> ct = heads.get("Content-Type");
                exchange.getOutMessage().put(Message.CONTENT_TYPE, ct.get(0));
                heads.remove("Content-Type");
            }
        }
    }
}
 
Example 10
Source File: AbstractProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public T invoke(T req) {

        MessageContext mc = wsContext.getMessageContext();
        String method = (String)mc.get(MessageContext.HTTP_REQUEST_METHOD);
        LOG.info("method: " + method);

        T ret = null;
        if ("GET".equalsIgnoreCase(method)) {
            ret = get(req);
        }  else if ("POST".equalsIgnoreCase(method)) {
            ret = post(req);
        }

        return ret;
    }
 
Example 11
Source File: GpContext.java    From govpay with GNU General Public License v3.0 4 votes vote down vote up
public static void popolaGpContext(GpContext ctx, MessageContext msgCtx, String tipoServizio, int versioneServizio) throws ServiceException {
	ApplicationTransaction transaction = ctx.getTransaction();
	transaction.setRole(Role.SERVER);
	transaction.setProtocol(TIPO_PROTOCOLLO_WS);

	Service service = new Service();
	if(msgCtx.get(MessageContext.WSDL_SERVICE) != null)
		service.setName(((QName) msgCtx.get(MessageContext.WSDL_SERVICE)).getLocalPart());
	else 
		service.setName(UNKNOWN);
	service.setVersion(versioneServizio);
	service.setType(tipoServizio);

	transaction.setService(service);

	Operation operation = new Operation();
	operation.setMode(FlowMode.INPUT_OUTPUT);
	if(msgCtx.get(MessageContext.WSDL_OPERATION) != null)
		operation.setName(((QName) msgCtx.get(MessageContext.WSDL_OPERATION)).getLocalPart());
	else 
		operation.setName(UNKNOWN);
	transaction.setOperation(operation);

	HttpServletRequest servletRequest = (HttpServletRequest) msgCtx.get(MessageContext.SERVLET_REQUEST);
	BaseClient client = new HttpClient();
	client.setInvocationEndpoint(servletRequest.getRequestURI());

	if(msgCtx.get(MessageContext.WSDL_INTERFACE) != null)
		client.setInterfaceName(((QName) msgCtx.get(MessageContext.WSDL_INTERFACE)).getLocalPart());
	else 
		client.setInterfaceName(UNKNOWN);

	String user = AutorizzazioneUtils.getPrincipal(SecurityContextHolder.getContext().getAuthentication());

	if(user != null)
		client.setPrincipal(user);
	transaction.setClient(client);

	ctx.getEventoCtx().setCategoriaEvento(Categoria.INTERFACCIA);
	ctx.getEventoCtx().setRole(Role.SERVER);
	ctx.getEventoCtx().setDataRichiesta(new Date());
	ctx.getEventoCtx().setMethod((String) msgCtx.get(MessageContext.HTTP_REQUEST_METHOD));
	ctx.getEventoCtx().setComponente(Componente.API_PAGOPA);
	ctx.getEventoCtx().setUrl(servletRequest.getRequestURI());
	ctx.getEventoCtx().setPrincipal(user);
	ctx.getEventoCtx().setTipoEvento(operation.getName());
}
 
Example 12
Source File: LoggingHandler.java    From juddi with Apache License 2.0 4 votes vote down vote up
private int getResponseCode(MessageContext context)
{
    Integer responseCode = (Integer) context.get(MessageContext.HTTP_RESPONSE_CODE);

    return responseCode.intValue();
}
 
Example 13
Source File: LoggingHandler.java    From juddi with Apache License 2.0 4 votes vote down vote up
private boolean isOutboundMessage(MessageContext context)
{
    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    return outboundProperty.booleanValue();
}
 
Example 14
Source File: SonosService.java    From subsonic with GNU General Public License v3.0 4 votes vote down vote up
private HttpServletRequest getRequest() {
    MessageContext messageContext = context == null ? null : context.getMessageContext();

    // See org.apache.cxf.transport.http.AbstractHTTPDestination#HTTP_REQUEST
    return messageContext == null ? null : (HttpServletRequest) messageContext.get("HTTP.REQUEST");
}
 
Example 15
Source File: OOBHdrServiceImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
private boolean checkContext() {
    boolean success = false;
    MessageContext ctx = context == null ? null : context.getMessageContext();
    if (ctx.containsKey(Header.HEADER_LIST)) {
        List<?> oobHdr = (List<?>) ctx.get(Header.HEADER_LIST);
        Iterator<?> iter = oobHdr.iterator();
        while (iter.hasNext()) {
            Object hdr = iter.next();
            if (hdr instanceof Header && ((Header) hdr).getObject() instanceof Node) {
                Header hdr1 = (Header) hdr;
                //System.out.println("Node conains : " + hdr1.getObject().toString());
                try {
                    JAXBElement<?> job = (JAXBElement<?>) JAXBContext.newInstance(ObjectFactory.class)
                        .createUnmarshaller()
                        .unmarshal((Node) hdr1.getObject());
                    OutofBandHeader ob = (OutofBandHeader) job.getValue();
                    if ("testOobHeader".equals(ob.getName())
                        && "testOobHeaderValue".equals(ob.getValue())) {
                        if ("testHdrAttribute".equals(ob.getHdrAttribute())) {
                            success = true;
                            iter.remove(); //mark it processed
                        } else if ("dontProcess".equals(ob.getHdrAttribute())) {
                            //we won't remove it so we won't let the runtime know
                            //it's processed.   It SHOULD throw an exception
                            //saying the mustunderstand wasn't processed
                            success = true;
                        }
                    } else {
                        throw new RuntimeException("test failed");
                    }
                } catch (JAXBException ex) {
                    //
                    ex.printStackTrace();
                }
            }
        }
    } else {
        throw new RuntimeException("MessageContext is null or doesnot contain OOBHeaders");
    }

    return success;
}
 
Example 16
Source File: AbstractTraceeHandler.java    From tracee with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private boolean isOutgoing(MessageContext messageContext) {
	Object outboundBoolean = messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
	return outboundBoolean != null && (Boolean) outboundBoolean;
}
 
Example 17
Source File: SonosService.java    From airsonic with GNU General Public License v3.0 4 votes vote down vote up
private HttpServletRequest getRequest() {
    MessageContext messageContext = context == null ? null : context.getMessageContext();

    // See org.apache.cxf.transport.http.AbstractHTTPDestination#HTTP_REQUEST
    return messageContext == null ? null : (HttpServletRequest) messageContext.get("HTTP.REQUEST");
}
 
Example 18
Source File: AttachmentStreamSourceXMLProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
public StreamSource invoke(StreamSource source) {

        MessageContext mc = wsContext.getMessageContext();

        String httpMethod = (String)mc.get(MessageContext.HTTP_REQUEST_METHOD);
        if ("POST".equals(httpMethod)) {

            int count = 0;
            // we really want to verify that a root part is a proper XML as expected
            try {
                Document doc = StaxUtils.read(source);
                count = Integer.parseInt(doc.getDocumentElement().getAttribute("count"));
            } catch (Exception ex) {
                // ignore
            }

            Map<String, DataHandler> dataHandlers = CastUtils.cast(
                (Map<?, ?>)mc.get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS));
            StringBuilder buf = new StringBuilder();
            buf.append("<response>");
            int i = 0;
            for (Map.Entry<String, DataHandler> entry : dataHandlers.entrySet()) {
                if (i++ > count) {
                    break;
                }
                try (ByteArrayOutputStream bous = new ByteArrayOutputStream()) {
                    InputStream is = entry.getValue().getInputStream();
                    IOUtils.copy(is, bous);

                    buf.append("<att contentId=\"" + entry.getKey() + "\">");
                    buf.append(Base64Utility.encode(bous.toByteArray()));
                    buf.append("</att>");

                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            buf.append("</response>");

            Map<String, List<String>> respHeaders = CastUtils
                .cast((Map<?, ?>)mc.get(MessageContext.HTTP_RESPONSE_HEADERS));
            if (respHeaders == null) {
                respHeaders = new HashMap<>();
                mc.put(MessageContext.HTTP_RESPONSE_HEADERS, respHeaders);
            }


            List<String> contentTypeValues = new ArrayList<>();
            contentTypeValues.add("application/xml+custom");
            respHeaders.put(Message.CONTENT_TYPE, contentTypeValues);

            Map<String, DataHandler> outDataHandlers
                = CastUtils.cast((Map<?, ?>)mc.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS));
            byte[] data = new byte[50];
            for (int x = 0; x < data.length; x++) {
                data[x] = (byte)(x + '0');
            }
            DataHandler foo = new DataHandler(new ByteArrayDataSource(data, "application/octet-stream"));
            outDataHandlers.put("foo", foo);

            return new StreamSource(new StringReader(buf.toString()));
        }
        return source;

    }
 
Example 19
Source File: SonosService.java    From airsonic-advanced with GNU General Public License v3.0 4 votes vote down vote up
private HttpServletRequest getRequest() {
    MessageContext messageContext = context == null ? null : context.getMessageContext();

    return messageContext == null ? null : (HttpServletRequest) messageContext.get(AbstractHTTPDestination.HTTP_REQUEST);
}
 
Example 20
Source File: AgentWsImpl.java    From ats-framework with Apache License 2.0 3 votes vote down vote up
private String getAgentHostAddress() {
    
    MessageContext msgx = wsContext.getMessageContext();

    HttpServletRequest request = ((HttpServletRequest) msgx.get(MessageContext.SERVLET_REQUEST));


    return request.getLocalAddr() + ":" + request.getLocalPort();
    
}