Example usage for javax.xml.ws.handler MessageContext HTTP_REQUEST_HEADERS

List of usage examples for javax.xml.ws.handler MessageContext HTTP_REQUEST_HEADERS

Introduction

In this page you can find the example usage for javax.xml.ws.handler MessageContext HTTP_REQUEST_HEADERS.

Prototype

String HTTP_REQUEST_HEADERS

To view the source code for javax.xml.ws.handler MessageContext HTTP_REQUEST_HEADERS.

Click Source Link

Document

Standard property: HTTP request headers.

Usage

From source file:it.vige.greenarea.gtg.webservice.auth.LDAPauth.java

public static String doAuthentication(WebServiceContext wsContext) throws LDAPException {

    String result;//from   ww w  .java 2  s  .com
    MessageContext mctx = wsContext.getMessageContext();

    Map<String, Object> http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
    List<Object> list = (List) http_headers.get("Authorization");

    if (list == null || list.isEmpty()) {
        result = "Authentication failed! This WS needs BASIC Authentication!";
        throw new LDAPException(ResultCode.AUTH_METHOD_NOT_SUPPORTED, result);
    }

    String userpass = (String) list.get(0);
    userpass = userpass.substring(5);
    byte[] buf = Base64.decodeBase64(userpass.getBytes());// decodeBase64(userpass.getBytes());

    String credentials = StringUtils.newStringUtf8(buf);
    String username;
    String password;

    int p = credentials.indexOf(":");

    if (p > -1) {

        username = credentials.substring(0, p);

        password = credentials.substring(p + 1);

    } else {

        result = "There was an error while decoding the Authentication!";
        throw new LDAPException(ResultCode.DECODING_ERROR, result);
    }
    /*
     * Creazione di una "Identity" Se non mi serve un sottodominio, posso
     * anche usare il costruttore Identity(usr,pwd)
     */
    logger.debug("*** LOG *** username: " + username + " pwd: " + password);
    logger.debug("*** LOG *** username: " + username + " AUTHORIZED!");
    return username;
}

From source file:com.hiperium.integration.access.control.SoapSessionHandler.java

@SuppressWarnings("unchecked")
@Override/*from   www  .  j ava  2  s .  com*/
public boolean handleMessage(SOAPMessageContext context) {
    LOGGER.debug("handleMessage - BEGIN");
    // Only message arriving from the client. Not processing responses.
    Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (!outbound) {
        Map<String, List<String>> map = (Map<String, List<String>>) context
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        List<String> sessionHeader = this.getHTTPHeader(map, CommonsUtil.SESSIONID);
        if (sessionHeader == null) {
            SOAPMessage msg = context.getMessage();
            this.generateFault(msg, Resources.getResourceBundle(EnumI18N.SECURITY, Locale.getDefault())
                    .getString("ilegalAccessResource"));
        }
        // Get the sessionId from the entire HTTP Message
        StringBuffer sessionIdBuffer = new StringBuffer();
        for (String session : sessionHeader) {
            sessionIdBuffer.append(session);
        }
        // Validate that the session ID is valid 
        if (StringUtils.isNotBlank(sessionIdBuffer.toString()) && !this.securityBusinessDelegate
                .getSessionManagerBO().findIfHomeLoggedIn(sessionIdBuffer.toString())) {
            SOAPMessage msg = context.getMessage();
            this.generateFault(msg, Resources.getResourceBundle(EnumI18N.SECURITY, Locale.getDefault())
                    .getString("ilegalAccessResource"));
        }
    }
    LOGGER.debug("handleMessage - END");
    return true; //continue other handler chain
}

From source file:org.grycap.vmrc.service.SecurityService.java

public User getUserFromContext(WebServiceContext webServiceContext) throws ServiceException {
    try {/*from   www .jav a2s .c o  m*/
        MessageContext messageContext = webServiceContext.getMessageContext();
        Map<String, Object> httpHeaders = (Map<String, Object>) messageContext
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        List<?> userList = (List<?>) httpHeaders.get("Username");
        List<?> passList = (List<?>) httpHeaders.get("Password");

        String clientUserName = (userList != null) ? userList.get(0).toString() : "anonymous";
        String clientPassword = (passList != null) ? passList.get(0).toString() : "";

        return new User(clientUserName, clientPassword);
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:com.hiperium.integration.access.control.SoapSignatureHandler.java

@SuppressWarnings("unchecked")
@Override//www  .j  a  v a  2s  .com
public boolean handleMessage(SOAPMessageContext context) {
    LOGGER.debug("handleMessage - BEGIN");
    // Only message arriving from the client. Not processing responses.
    Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (!outbound) {
        // Get the sessionId from the entire HTTP Message
        StringBuffer sessionIdBuffer = new StringBuffer();
        Map<String, List<String>> map = (Map<String, List<String>>) context
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        for (String session : this.getHTTPHeader(map, CommonsUtil.SESSIONID)) {
            sessionIdBuffer.append(session);
        }
        // Try to get SOAP header values from the SOAP message
        try {
            SOAPMessage msg = context.getMessage();
            if (LOGGER.isDebugEnabled()) {
                System.out.println("REQUEST:");
                msg.writeTo(System.out);
                System.out.println();
            }
            Node node = msg.getSOAPHeader().getFirstChild();

            // Header values
            NodeList nodeList = node.getChildNodes(); // Name, TimeStamp, Signature.
            if (nodeList.getLength() < 3) {
                this.generateFault(msg, "Too few header nodes!");
            }

            // Extract the required attributes.
            Long homeId = Long.valueOf(nodeList.item(0).getFirstChild().getNodeValue());
            String signature = nodeList.item(1).getFirstChild().getNodeValue();
            String timestamp = nodeList.item(2).getFirstChild().getNodeValue();
            if (StringUtils.isBlank(timestamp) || StringUtils.isBlank(signature)) {
                this.generateFault(msg, "Missing header key/value pairs!");
            }

            // Validates that the user Token exists in the DB for valid registered external Application.
            String token = this.securityBusinessDelegate.getHomeGatewayBO().findTokenInSession(homeId,
                    sessionIdBuffer.toString());
            if (StringUtils.isBlank(token)) {
                this.generateFault(msg, homeId.toString().concat(" not registered!"));
            }

            // Generate comparison signature and compare against what's sent.
            byte[] secretBytes = Signature.getBytes(token);
            String localSignature = Signature.createSignature(homeId, timestamp, secretBytes);
            if (!this.verify(signature, localSignature)) {
                this.generateFault(msg, "HMAC signatures do not match.");
            }
        } catch (Exception e) {
            throw new RuntimeException("SOAPException thrown.", e);
        }
    }
    LOGGER.debug("handleMessage - END");
    return true; //continue other handler chain
}

From source file:com.vmware.identity.sts.ws.handlers.SoapMsgMetricsCollector.java

private void reportTime(MessageContext context, PerfMeasurementInterface itf) {
    long delta = System.currentTimeMillis() - msgStartTs.get().longValue();

    List<String> actions = ((Headers) context.get(MessageContext.HTTP_REQUEST_HEADERS)).get("soapaction");
    assert actions.size() == 1;

    //remove the double quote
    String action = actions.get(0);
    String canonicalAction = action.startsWith("\"") ? action.substring(1, action.length() - 1) : action;

    try {// ww w.  ja v a 2s .c  om
        reportProcessingTime(delta, canonicalAction,
                MessageExtractionUtil.extractUsernameFromMsgContext(context), itf);
    } catch (Exception e) { //log & swallow
        logger.error("exception occurred when reporting performance measurement data on itf {}: {}", itf,
                e.getMessage());
    }
}

From source file:it.govpay.web.handler.MessageLoggingHandlerUtils.java

@SuppressWarnings("unchecked")
public static boolean logToSystemOut(SOAPMessageContext smc, String tipoServizio, int versioneServizio,
        Logger log) {/*from  w w w.  ja v  a2s  .  c om*/
    Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    GpContext ctx = null;
    Message msg = new Message();

    SOAPMessage message = smc.getMessage();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        message.writeTo(baos);
        msg.setContent(baos.toByteArray());
    } catch (Exception e) {
        log.error("Exception in handler: " + e);
    }

    Map<String, List<String>> httpHeaders = null;

    if (outboundProperty.booleanValue()) {
        ctx = GpThreadLocal.get();
        httpHeaders = (Map<String, List<String>>) smc.get(MessageContext.HTTP_RESPONSE_HEADERS);
        msg.setType(MessageType.RESPONSE_OUT);
        ctx.getContext().getResponse().setOutDate(new Date());
        ctx.getContext().getResponse().setOutSize(Long.valueOf(baos.size()));
    } else {
        try {
            ctx = new GpContext(smc, tipoServizio, versioneServizio);
            ThreadContext.put("op", ctx.getTransactionId());
            GpThreadLocal.set(ctx);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
        httpHeaders = (Map<String, List<String>>) smc.get(MessageContext.HTTP_REQUEST_HEADERS);
        msg.setType(MessageType.REQUEST_IN);
        msg.setContentType(((HttpServletRequest) smc.get(MessageContext.SERVLET_REQUEST)).getContentType());

        ctx.getContext().getRequest().setInDate(new Date());
        ctx.getContext().getRequest().setInSize(Long.valueOf(baos.size()));
    }

    if (httpHeaders != null) {
        for (String key : httpHeaders.keySet()) {
            if (httpHeaders.get(key) != null) {
                if (key == null)
                    msg.addHeader(new Property("Status-line", httpHeaders.get(key).get(0)));
                else if (httpHeaders.get(key).size() == 1)
                    msg.addHeader(new Property(key, httpHeaders.get(key).get(0)));
                else
                    msg.addHeader(new Property(key, ArrayUtils.toString(httpHeaders.get(key))));
            }
        }
    }

    ctx.log(msg);

    return true;
}

From source file:com.vmware.identity.sts.ws.handlers.LogContextHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    Validate.notNull(context, "SOAPMessageContext should not be null.");

    Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    if (outbound != null && outbound.equals(Boolean.TRUE)) {
        return true;
    } else {/*w w  w  .  j a v a  2 s  . c  o  m*/
        String tenant = null;
        String correlationId = null;

        // http://docs.oracle.com/javase/7/docs/api/javax/xml/ws/handler/MessageContext.html :
        //     static final String HTTP_REQUEST_HEADERS
        //         Standard property: HTTP request headers.
        //         Type: java.util.Map<java.lang.String, java.util.List<java.lang.String>>
        //
        //     static final String SERVLET_REQUEST
        //         Standard property: servlet request object.
        //         Type: javax.servlet.http.HttpServletRequest

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

        Validate.notNull(request, "HttpServletRequest should not be null.");

        @SuppressWarnings("unchecked")
        Map<String, List<String>> headers = (Map<String, List<String>>) (context
                .get(MessageContext.HTTP_REQUEST_HEADERS));
        if (headers != null) {
            List<String> correlationIds = headers.get(WsConstants.ACTIVITY_CORRELATION_ID_CUSTOM_HEADER);
            if ((correlationIds != null) && (correlationIds.size() > 1)) {
                correlationId = correlationIds.get(0);
                correlationId = LogContextHandler.removeNewline(correlationId);
                correlationId = LogContextHandler.truncate(correlationId, 200);
            }
        }

        if ((correlationId == null) || (correlationId.isEmpty())) {
            correlationId = UUID.randomUUID().toString();
            logger.debug("unable to extract correlation id from request. generated new correllation id [{}]",
                    correlationId);
        } else {
            logger.debug("extracted correlation id [{}] from the request", correlationId);
        }

        try {
            tenant = TenantExtractor.extractTenantName(request.getPathInfo());
            tenant = LogContextHandler.removeNewline(tenant);
            tenant = LogContextHandler.truncate(tenant, 200);
            logger.debug("extracted tenant [{}] from the request", tenant);
        } catch (NoSuchIdPException ex) {
            logger.error("failed to extract tenant from the request", ex);
        }

        if ((tenant == null) || (tenant.isEmpty())) {
            tenant = WsConstants.DEFAULT_TENANT;
            logger.debug(
                    "unable to extract explicit tenant name from request. Using default tenant marker [{}].",
                    tenant);
        } else {
            logger.debug("extracted tenant name [{}] from the request", tenant);
        }

        this._diagCtxt = DiagnosticsContextFactory.createContext(correlationId, tenant);
    }

    return true;
}

From source file:ebay.dts.client.FileTransferCall.java

public FileTransferServicePort setFTSMessageContext() throws EbayConnectorException {
    FileTransferServicePort port = null;
    FileTransferService service = new FileTransferService();

    try {/*  w  w w.j ava  2 s . c o  m*/

        port = service.getFileTransferServiceSOAP();
        BindingProvider bp = (BindingProvider) port;
        bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, this.serverURL);
        List handlerList = bp.getBinding().getHandlerChain();
        if (handlerList == null) {
            handlerList = new ArrayList();
        }
        LoggingHandler loggingHandler = new LoggingHandler();
        handlerList.add(loggingHandler);
        // register the handerList
        bp.getBinding().setHandlerChain(handlerList);
        // initialize WS operation arguments here
        Map requestProperties = bp.getRequestContext();
        // set http address
        if (this.serverURL == null) {
            throw new Exception(" serverURL can't be null ");

        }
        int timeout = 100;
        requestProperties.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, serverURL);
        requestProperties.put(JAXWSProperties.CONNECT_TIMEOUT, timeout);

        Map<String, List<String>> httpHeaders = new HashMap<String, List<String>>();
        httpHeaders.put("X-EBAY-SOA-MESSAGE-PROTOCOL", Collections.singletonList("SOAP12"));
        httpHeaders.put("X-EBAY-SOA-OPERATION-NAME", Collections.singletonList(this.callName));
        httpHeaders.put("X-EBAY-SOA-SECURITY-TOKEN", Collections.singletonList(this.userToken));

        requestProperties.put(MessageContext.HTTP_REQUEST_HEADERS, httpHeaders);

    } catch (Exception e) {
        throw new EbayConnectorException("Errore nel setup uplink: " + e.getMessage(), e);
    }

    return port;

}

From source file:ebay.dts.client.BulkDataExchangeCall.java

public BulkDataExchangeServicePort setRequestContext(String callName) throws EbayConnectorException {

    if (this.serverURL == null && this.serverURL.length() == 0) {
        logger.error("BulkDataExchangeService endpoint URL is not set");
        return null;
    }/* ww w  .  j a  v a2 s .  c  om*/

    BulkDataExchangeServicePort port = null;
    try { // Call Web Service Operation
        BulkDataExchangeService service = new BulkDataExchangeService();
        port = service.getBulkDataExchangeServiceSOAP();
        bp = (BindingProvider) port;
        // Add the logging handler
        List handlerList = bp.getBinding().getHandlerChain();
        if (handlerList == null) {
            handlerList = new ArrayList();
        }
        LoggingHandler loggingHandler = new LoggingHandler();
        handlerList.add(loggingHandler);
        // register the handerList
        bp.getBinding().setHandlerChain(handlerList);
        // initialize WS operation arguments here
        Map requestProperties = bp.getRequestContext();
        requestProperties.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, this.serverURL);
        if (this.userToken == null) {
            throw new Exception(" userToken can't be null ");
        }
        Map<String, List<String>> httpHeaders = new HashMap<String, List<String>>();
        httpHeaders.put("X-EBAY-SOA-MESSAGE-PROTOCOL", Collections.singletonList("SOAP11"));
        httpHeaders.put("X-EBAY-SOA-OPERATION-NAME", Collections.singletonList(callName));
        httpHeaders.put("X-EBAY-SOA-SECURITY-TOKEN", Collections.singletonList(this.userToken));
        requestProperties.put(MessageContext.HTTP_REQUEST_HEADERS, httpHeaders);
        //http://developer.ebay.com/DevZone/bulk-data-exchange/CallRef/createUploadJob.html#Request.uploadJobType

    } catch (Exception ex) {
        logger.error(ex.getMessage());
        throw new EbayConnectorException(ex.getMessage(), ex);
    }

    return port;

}

From source file:ebay.dts.client.FileTransferCall.java

public FileTransferServicePort setFTSMessageContext(String callName) throws EbayConnectorException {

    logger.trace("FileTransferActions.setFTSMessageContext(String callName ) ...... ");

    FileTransferServicePort port = null;
    FileTransferService service = new FileTransferService();

    port = service.getFileTransferServiceSOAP();
    BindingProvider bp = (BindingProvider) port;

    bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, serverURL);
    List handlerList = bp.getBinding().getHandlerChain();
    if (handlerList == null) {
        handlerList = new ArrayList();
    }/*  w w w  .  ja  va2 s  .  com*/
    LoggingHandler loggingHandler = new LoggingHandler();
    handlerList.add(loggingHandler);
    // register the handerList
    bp.getBinding().setHandlerChain(handlerList);
    // initialize WS operation arguments here
    Map requestProperties = bp.getRequestContext();

    // set http address
    logger.trace("serverURL :" + this.serverURL);

    if (this.serverURL == null) {
        throw new EbayConnectorException(" serverURL can't be null ");
    }
    if (this.userToken == null) {
        throw new EbayConnectorException(" User Token can't be null ");
    }

    requestProperties.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, serverURL);
    Map<String, List<String>> httpHeaders = new HashMap<String, List<String>>();
    httpHeaders.put("X-EBAY-SOA-MESSAGE-PROTOCOL", Collections.singletonList("SOAP12"));
    httpHeaders.put("X-EBAY-SOA-OPERATION-NAME", Collections.singletonList(callName));
    httpHeaders.put("X-EBAY-SOA-SECURITY-TOKEN", Collections.singletonList(this.userToken));
    requestProperties.put(MessageContext.HTTP_REQUEST_HEADERS, httpHeaders);

    return port;

}