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:ebay.dts.client.BulkDataExchangeCall.java

public BulkDataExchangeServicePort setRequestContext() throws EbayConnectorException {
    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();
        }/*from   w ww.  j av a  2  s . co  m*/
        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 ");
        }
        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("SOAP11"));
        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);
        retrieveHttpHeaders(bp, "Response");
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        throw new EbayConnectorException(ex.getMessage(), ex);
    }
    return port;
}

From source file:com.qubit.solution.fenixedu.bennu.webservices.services.server.BennuWebServiceHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    //for response message only, true for outbound messages, false for inbound
    if (!isRequest) {
        try {/*from w ww  .  ja  v  a  2 s . c  o  m*/

            WebServiceServerConfiguration configuration = getWebServiceServerConfiguration(
                    ((com.sun.xml.ws.api.server.WSEndpoint) context.get("com.sun.xml.ws.api.server.WSEndpoint"))
                            .getImplementationClass().getName());

            SOAPMessage soapMsg = context.getMessage();
            SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
            SOAPHeader soapHeader = soapEnv.getHeader();

            if (!configuration.isActive()) {
                generateSOAPErrorMessage(soapMsg, "Sorry webservice is disabled at application level!");
            }

            if (configuration.isAuthenticatioNeeded()) {

                if (configuration.isUsingWSSecurity()) {
                    if (soapHeader == null) {
                        generateSOAPErrorMessage(soapMsg,
                                "No header in message, unabled to validate security credentials");
                    }

                    String username = null;
                    String password = null;
                    String nonce = null;
                    String created = null;

                    Iterator<SOAPElement> childElements = soapHeader.getChildElements(QNAME_WSSE_SECURITY);
                    if (childElements.hasNext()) {
                        SOAPElement securityElement = childElements.next();
                        Iterator<SOAPElement> usernameTokens = securityElement
                                .getChildElements(QNAME_WSSE_USERNAME_TOKEN);
                        if (usernameTokens.hasNext()) {
                            SOAPElement usernameToken = usernameTokens.next();
                            username = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_USERNAME)
                                    .next()).getValue();
                            password = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_PASSWORD)
                                    .next()).getValue();
                            nonce = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_NONCE).next())
                                    .getValue();
                            created = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_CREATED).next())
                                    .getValue();
                        }
                    }
                    if (username == null || password == null || nonce == null || created == null) {
                        generateSOAPErrorMessage(soapMsg,
                                "Missing information, unabled to validate security credentials");
                    }

                    SecurityHeader securityHeader = new SecurityHeader(configuration, username, password, nonce,
                            created);
                    if (!securityHeader.isValid()) {
                        generateSOAPErrorMessage(soapMsg, "Invalid credentials");
                    } else {
                        context.put(BennuWebService.SECURITY_HEADER, securityHeader);
                        context.setScope(BennuWebService.SECURITY_HEADER, Scope.APPLICATION);
                    }
                } else {
                    com.sun.xml.ws.transport.Headers httpHeader = (Headers) context
                            .get(MessageContext.HTTP_REQUEST_HEADERS);
                    String username = null;
                    String password = null;
                    List<String> list = httpHeader.get("authorization");
                    if (list != null) {
                        for (String value : list) {
                            if (value.startsWith("Basic")) {
                                String[] split = value.split(" ");
                                try {
                                    String decoded = new String(Base64.decodeBase64(split[1]), "UTF-8");
                                    String[] split2 = decoded.split(":");
                                    if (split2.length == 2) {
                                        username = split2[0];
                                        password = split2[1];
                                    }
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                    if (username == null || password == null) {
                        generateSOAPErrorMessage(soapMsg,
                                "Missing information, unabled to validate security credentials");
                    }

                    if (!configuration.validate(username, password)) {
                        generateSOAPErrorMessage(soapMsg, "Invalid credentials");
                    }
                }
            }

        } catch (SOAPException e) {
            System.err.println(e);
        }
    }

    //continue other handler chain
    return true;
}

From source file:de.cosmocode.palava.salesforce.DefaultSalesforceService.java

@Override
public Soap connect() throws SalesforceException {
    LOG.info("Connecting to Salesforce using {}", wsdl.toExternalForm());
    final SforceService service = new SforceService(wsdl, Salesforce.SERVICE_NAME);
    final Soap endpoint = service.getSoap();

    assert endpoint instanceof WSBindingProvider : String.format("%s should be an instance of %s", endpoint,
            WSBindingProvider.class);

    final WSBindingProvider provider = WSBindingProvider.class.cast(endpoint);
    final Object address = provider.getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
    LOG.debug("Connecting to {}", address);

    LOG.trace("Setting connection timeout to {} {}", connectionTimeout,
            connectionTimeoutUnit.name().toLowerCase());
    final int timeout = (int) connectionTimeoutUnit.toMillis(connectionTimeout);
    provider.getRequestContext().put("com.sun.xml.ws.request.timeout", timeout);

    LOG.trace("Enabling Gzip compression");
    provider.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS,
            Maps.newHashMap(Salesforce.HTTP_HEADERS));

    try {/* w w  w . j a va  2s .c o m*/
        LOG.debug("Attempt to login using {}/***", username);
        final LoginResult result = endpoint.login(username, password + securityToken);

        final String serverUrl = result.getServerUrl();
        LOG.trace("Setting endpoint to {}", serverUrl);
        provider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, serverUrl);

        final SessionHeader sessionHeader = new SessionHeader();
        LOG.trace("Creating new SessionHeader with Id: {}", result.getSessionId());
        sessionHeader.setSessionId(result.getSessionId());

        final Header header = Headers.create(Salesforce.CONTEXT, sessionHeader);
        LOG.trace("Setting Header {} in provider {}", header, provider);
        provider.setOutboundHeaders(header);

        if (LOG.isTraceEnabled()) {
            LOG.trace("Logged in as user with ID {}", result.getUserId());

            final GetUserInfoResult info = result.getUserInfo();
            LOG.trace("Username: {} ({})", info.getUserFullName(), info.getUserName());
            LOG.trace("Email: {}", info.getUserEmail());
            LOG.trace("Organization: {} [{}]", info.getOrganizationName(), info.getOrganizationId());
            LOG.trace("Language: {} / Locale: {}", info.getUserLanguage(), info.getUserLocale());
        }
    } catch (InvalidIdFault e) {
        throw new SalesforceException("Unable to log into Salesforce", e);
    } catch (LoginFault e) {
        throw new SalesforceException("Unable to log into Salesforce", e);
    } catch (UnexpectedErrorFault e) {
        throw new SalesforceException("Unable to log into Salesforce", e);
    }
    return endpoint;
}

From source file:com.wavemaker.runtime.ws.HTTPBindingSupport.java

@SuppressWarnings("unchecked")
private static <T extends Object> T getResponse(QName serviceQName, QName portQName, String endpointAddress,
        HTTPRequestMethod method, T postSource, BindingProperties bindingProperties, Class<T> type,
        Map<String, Object> headerParams) throws WebServiceException {

    Service service = Service.create(serviceQName);
    URI endpointURI;/*from   www  .j  a v  a  2s. c o m*/
    try {
        if (bindingProperties != null) {
            // if BindingProperties had endpointAddress defined, then use
            // it instead of the endpointAddress passed in from arguments.
            String endAddress = bindingProperties.getEndpointAddress();
            if (endAddress != null) {
                endpointAddress = endAddress;
            }
        }
        endpointURI = new URI(endpointAddress);
    } catch (URISyntaxException e) {
        throw new WebServiceException(e);
    }

    String endpointPath = null;
    String endpointQueryString = null;
    if (endpointURI != null) {
        endpointPath = endpointURI.getRawPath();
        endpointQueryString = endpointURI.getRawQuery();
    }

    service.addPort(portQName, HTTPBinding.HTTP_BINDING, endpointAddress);

    Dispatch<T> d = service.createDispatch(portQName, type, Service.Mode.MESSAGE);

    Map<String, Object> requestContext = d.getRequestContext();
    requestContext.put(MessageContext.HTTP_REQUEST_METHOD, method.toString());
    requestContext.put(MessageContext.QUERY_STRING, endpointQueryString);
    requestContext.put(MessageContext.PATH_INFO, endpointPath);

    Map<String, List<String>> reqHeaders = null;
    if (bindingProperties != null) {
        String httpBasicAuthUsername = bindingProperties.getHttpBasicAuthUsername();
        if (httpBasicAuthUsername != null) {
            requestContext.put(BindingProvider.USERNAME_PROPERTY, httpBasicAuthUsername);
            String httpBasicAuthPassword = bindingProperties.getHttpBasicAuthPassword();
            requestContext.put(BindingProvider.PASSWORD_PROPERTY, httpBasicAuthPassword);
        }

        int connectionTimeout = bindingProperties.getConnectionTimeout();
        requestContext.put(JAXWSProperties.CONNECT_TIMEOUT, Integer.valueOf(connectionTimeout));

        int requestTimeout = bindingProperties.getRequestTimeout();
        requestContext.put(JAXWSProperties.REQUEST_TIMEOUT, Integer.valueOf(requestTimeout));

        Map<String, List<String>> httpHeaders = bindingProperties.getHttpHeaders();
        if (httpHeaders != null && !httpHeaders.isEmpty()) {
            reqHeaders = (Map<String, List<String>>) requestContext.get(MessageContext.HTTP_REQUEST_HEADERS);
            if (reqHeaders == null) {
                reqHeaders = new HashMap<String, List<String>>();
                requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, reqHeaders);
            }
            for (Entry<String, List<String>> entry : httpHeaders.entrySet()) {
                reqHeaders.put(entry.getKey(), entry.getValue());
            }
        }
    }

    // Parameters to pass in http header
    if (headerParams != null && headerParams.size() > 0) {
        if (null == reqHeaders) {
            reqHeaders = new HashMap<String, List<String>>();
        }
        Set<Entry<String, Object>> entries = headerParams.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            List<String> valList = new ArrayList<String>();
            valList.add((String) entry.getValue());
            reqHeaders.put(entry.getKey(), valList);
            requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, reqHeaders);
        }
    }

    logger.info("Invoking HTTP '" + method + "' request with URL: " + endpointAddress);

    T result = d.invoke(postSource);
    return result;
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

private void createDispatch(WebServiceDispatcherProperties webServiceDispatcherProperties,
        DispatchContainer dispatchContainer) throws Exception {
    String wsdlUrl = webServiceDispatcherProperties.getWsdlUrl();
    String username = webServiceDispatcherProperties.getUsername();
    String password = webServiceDispatcherProperties.getPassword();
    String serviceName = webServiceDispatcherProperties.getService();
    String portName = webServiceDispatcherProperties.getPort();

    /*//w w w  .  j av a2 s  .c  om
     * The dispatch needs to be created if it hasn't been created yet (null). It needs to be
     * recreated if any of the above variables are different than what were used to create the
     * current dispatch object. This could happen if variables are being used for these
     * properties.
     */
    if (dispatchContainer.getDispatch() == null
            || !StringUtils.equals(wsdlUrl, dispatchContainer.getCurrentWsdlUrl())
            || !StringUtils.equals(username, dispatchContainer.getCurrentUsername())
            || !StringUtils.equals(password, dispatchContainer.getCurrentPassword())
            || !StringUtils.equals(serviceName, dispatchContainer.getCurrentServiceName())
            || !StringUtils.equals(portName, dispatchContainer.getCurrentPortName())) {
        dispatchContainer.setCurrentWsdlUrl(wsdlUrl);
        dispatchContainer.setCurrentUsername(username);
        dispatchContainer.setCurrentPassword(password);
        dispatchContainer.setCurrentServiceName(serviceName);
        dispatchContainer.setCurrentPortName(portName);

        URL endpointUrl = getWsdlUrl(dispatchContainer);
        QName serviceQName = QName.valueOf(serviceName);
        QName portQName = QName.valueOf(portName);

        // create the service and dispatch
        logger.debug("Creating web service: url=" + endpointUrl.toString() + ", service=" + serviceQName
                + ", port=" + portQName);
        Service service = Service.create(endpointUrl, serviceQName);

        Dispatch<SOAPMessage> dispatch = service.createDispatch(portQName, SOAPMessage.class,
                Service.Mode.MESSAGE);

        if (timeout > 0) {
            dispatch.getRequestContext().put("com.sun.xml.internal.ws.connect.timeout", timeout);
            dispatch.getRequestContext().put("com.sun.xml.internal.ws.request.timeout", timeout);
            dispatch.getRequestContext().put("com.sun.xml.ws.connect.timeout", timeout);
            dispatch.getRequestContext().put("com.sun.xml.ws.request.timeout", timeout);
        }

        Map<String, List<String>> requestHeaders = (Map<String, List<String>>) dispatch.getRequestContext()
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        if (requestHeaders == null) {
            requestHeaders = new HashMap<String, List<String>>();
        }
        dispatchContainer.setDefaultRequestHeaders(requestHeaders);

        dispatchContainer.setDispatch(dispatch);
    }
}

From source file:io.hummer.util.ws.WebServiceClient.java

private InvocationResult doInvokeSOAP(Element request, List<Element> headers, int retries, String protocol,
        int connectTimeoutMS, int requestTimeoutMS) throws Exception {
    if (retries < 0)
        throw new Exception("Invocation to " + endpointURL + " failed: " + xmlUtil.toString(request));

    // if the service is null here because the WSDL is unavailable, 
    // create a plain HTTP POST invocation..
    if (service == null) {
        return doInvokePOST(request, new HashMap<String, String>(), retries);
    }/*from ww  w  . ja v a 2  s  .  c o  m*/

    Dispatch<SOAPMessage> dispatch = null;
    synchronized (service) {
        dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);
    }

    dispatch.getRequestContext().put("com.sun.xml.ws.connect.timeout", connectTimeoutMS);
    dispatch.getRequestContext().put("com.sun.xml.ws.request.timeout", requestTimeoutMS);
    dispatch.getRequestContext().put("com.sun.xml.internal.ws.connect.timeout", connectTimeoutMS);
    dispatch.getRequestContext().put("com.sun.xml.internal.ws.request.timeout", requestTimeoutMS);
    dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS,
            Collections.singletonMap("Connection", Collections.singletonList("close")));

    try {
        SOAPMessage message = createSOAPMessage(request, headers, protocol);
        String tmpID = PerformanceInterceptor.event(EventType.START_SEND_INVOCATION);
        SOAPMessage response = dispatch.invoke(message);
        PerformanceInterceptor.event(EventType.FINISH_SEND_INVOCATION, tmpID);
        InvocationResult result = new InvocationResult(response.getSOAPBody());
        return result;
    } catch (Exception e) {
        if (!(e.getCause() instanceof ThreadDeath)) {
            //logger.warn("Exception in invocation; to: " + endpointURL + "; " + e);
        }

        if (retries <= 0) {
            throw new Exception("Invocation to " + endpointURL + " failed: " + xmlUtil.toString(request), e);
        }
        if (e instanceof BindException || e.getCause() instanceof BindException) {
            long sleep = 200L + (long) (Math.random() * 800);
            logger.warn("Cannot bind to (client) port, sleeping " + sleep);
            Thread.sleep(sleep);
        }
        request = xmlUtil.clone(request);
        return doInvokeSOAP(request, headers, retries - 1, protocol, connectTimeoutMS, requestTimeoutMS);
    } finally {
        //PerformanceInterceptor.event(EventType.FINISH_INVOCATION, eID);
        //System.out.println(eID + " finished " + endpointURL);
    }
}

From source file:com.tremolosecurity.provisioning.sharepoint.SharePointGroups.java

private UserGroupSoap getConnection(URL url) throws Exception {
    UserGroup ss = new UserGroup(wsdl.toURI().toURL(), SERVICE);
    UserGroupSoap port = ss.getUserGroupSoap12();

    BindingProvider provider = (BindingProvider) port;

    if (authType == AuthType.UnisonLastMile) {
        DateTime now = new DateTime();
        DateTime future = now.plusMillis(this.skew);
        now = now.minusMillis(skew);/*  ww  w .  ja  v  a 2s .c  o  m*/
        com.tremolosecurity.lastmile.LastMile lastmile = new com.tremolosecurity.lastmile.LastMile(
                url.getPath(), now, future, 0, "chainName");
        lastmile.getAttributes().add(new Attribute("userPrincipalName", this.administratorUPN));

        SecretKey sk = this.cfg.getSecretKey(this.keyAlias);
        Map<String, List<String>> headers = (Map<String, List<String>>) provider.getRequestContext()
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        if (headers == null) {
            headers = new HashMap<String, List<String>>();
        }

        headers.put(this.headerName, Collections.singletonList(lastmile.generateLastMileToken(sk)));

        provider.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, headers);
    } else if (authType == AuthType.NTLM) {
        NtlmAuthenticator authenticator = new NtlmAuthenticator(this.administratorUPN,
                this.administratorPassword);
        Authenticator.setDefault(authenticator);

    }

    provider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url.toString());

    return port;
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    WebServiceDispatcherProperties webServiceDispatcherProperties = (WebServiceDispatcherProperties) connectorProperties;

    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.SENDING));

    String responseData = null;/* w w w  .j av  a2s.c om*/
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    try {
        long dispatcherId = getDispatcherId();
        DispatchContainer dispatchContainer = dispatchContainers.get(dispatcherId);
        if (dispatchContainer == null) {
            dispatchContainer = new DispatchContainer();
            dispatchContainers.put(dispatcherId, dispatchContainer);
        }

        /*
         * Initialize the dispatch object if it hasn't been initialized yet, or create a new one
         * if the connector properties have changed due to variables.
         */
        createDispatch(webServiceDispatcherProperties, dispatchContainer);

        Dispatch<SOAPMessage> dispatch = dispatchContainer.getDispatch();

        configuration.configureDispatcher(this, webServiceDispatcherProperties, dispatch.getRequestContext());

        SOAPBinding soapBinding = (SOAPBinding) dispatch.getBinding();

        if (webServiceDispatcherProperties.isUseAuthentication()) {
            String currentUsername = dispatchContainer.getCurrentUsername();
            String currentPassword = dispatchContainer.getCurrentPassword();

            dispatch.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, currentUsername);
            dispatch.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, currentPassword);
            logger.debug("Using authentication: username=" + currentUsername + ", password length="
                    + currentPassword.length());
        }

        // See: http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528
        String soapAction = webServiceDispatcherProperties.getSoapAction();

        if (StringUtils.isNotEmpty(soapAction)) {
            dispatch.getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY, true); // MIRTH-2109
            dispatch.getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY, soapAction);
        }

        // Get default headers
        Map<String, List<String>> requestHeaders = new HashMap<String, List<String>>(
                dispatchContainer.getDefaultRequestHeaders());

        // Add custom headers
        if (MapUtils.isNotEmpty(webServiceDispatcherProperties.getHeaders())) {
            for (Entry<String, List<String>> entry : webServiceDispatcherProperties.getHeaders().entrySet()) {
                List<String> valueList = requestHeaders.get(entry.getKey());

                if (valueList == null) {
                    valueList = new ArrayList<String>();
                    requestHeaders.put(entry.getKey(), valueList);
                }

                valueList.addAll(entry.getValue());
            }
        }

        dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, requestHeaders);

        // build the message
        logger.debug("Creating SOAP envelope.");
        AttachmentHandlerProvider attachmentHandlerProvider = getAttachmentHandlerProvider();
        String content = attachmentHandlerProvider.reAttachMessage(webServiceDispatcherProperties.getEnvelope(),
                connectorMessage);
        Source source = new StreamSource(new StringReader(content));
        SOAPMessage message = soapBinding.getMessageFactory().createMessage();
        message.getSOAPPart().setContent(source);

        if (webServiceDispatcherProperties.isUseMtom()) {
            soapBinding.setMTOMEnabled(true);

            List<String> attachmentIds = webServiceDispatcherProperties.getAttachmentNames();
            List<String> attachmentContents = webServiceDispatcherProperties.getAttachmentContents();
            List<String> attachmentTypes = webServiceDispatcherProperties.getAttachmentTypes();

            for (int i = 0; i < attachmentIds.size(); i++) {
                String attachmentContentId = attachmentIds.get(i);
                String attachmentContentType = attachmentTypes.get(i);
                String attachmentContent = attachmentHandlerProvider.reAttachMessage(attachmentContents.get(i),
                        connectorMessage);

                AttachmentPart attachment = message.createAttachmentPart();
                attachment.setBase64Content(new ByteArrayInputStream(attachmentContent.getBytes("UTF-8")),
                        attachmentContentType);
                attachment.setContentId(attachmentContentId);
                message.addAttachmentPart(attachment);
            }
        }

        message.saveChanges();

        if (StringUtils.isNotBlank(webServiceDispatcherProperties.getLocationURI())) {
            dispatch.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                    webServiceDispatcherProperties.getLocationURI());
        }

        boolean redirect = false;
        int tryCount = 0;

        /*
         * Attempt the invocation until we hit the maximum allowed redirects. The redirections
         * we handle are when the scheme changes (i.e. from HTTP to HTTPS).
         */
        do {
            redirect = false;
            tryCount++;

            try {
                DispatchTask<SOAPMessage> task = new DispatchTask<SOAPMessage>(dispatch, message,
                        webServiceDispatcherProperties.isOneWay());
                SOAPMessage result;

                /*
                 * If the timeout is set to zero, we need to do the invocation in a separate
                 * thread. This is because there's no way to get a reference to the underlying
                 * JAX-WS socket, so there's no way to forcefully halt the dispatch. If the
                 * socket is truly hung and the user halts the channel, the best we can do is
                 * just interrupt and ignore the thread. This means that a thread leak is
                 * potentially introduced, so we need to notify the user appropriately.
                 */
                if (timeout == 0) {
                    // Submit the task to an executor so that it's interruptible
                    Future<SOAPMessage> future = executor.submit(task);
                    // Keep track of the task by adding it to our set
                    dispatchTasks.add(task);
                    result = future.get();
                } else {
                    // Call the task directly
                    result = task.call();
                }

                if (webServiceDispatcherProperties.isOneWay()) {
                    responseStatusMessage = "Invoked one way operation successfully.";
                } else {
                    responseData = sourceToXmlString(result.getSOAPPart().getContent());
                    responseStatusMessage = "Invoked two way operation successfully.";
                }
                logger.debug("Finished invoking web service, got result.");

                // Automatically accept message; leave it up to the response transformer to find SOAP faults
                responseStatus = Status.SENT;
            } catch (Throwable e) {
                // Unwrap the exception if it came from the executor
                if (e instanceof ExecutionException && e.getCause() != null) {
                    e = e.getCause();
                }

                // If the dispatch was interrupted, make sure to reset the interrupted flag
                if (e instanceof InterruptedException) {
                    Thread.currentThread().interrupt();
                }

                Integer responseCode = null;
                String location = null;

                if (dispatch.getResponseContext() != null) {
                    responseCode = (Integer) dispatch.getResponseContext()
                            .get(MessageContext.HTTP_RESPONSE_CODE);

                    Map<String, List<String>> headers = (Map<String, List<String>>) dispatch
                            .getResponseContext().get(MessageContext.HTTP_RESPONSE_HEADERS);
                    if (MapUtils.isNotEmpty(headers)) {
                        List<String> locations = headers.get("Location");
                        if (CollectionUtils.isNotEmpty(locations)) {
                            location = locations.get(0);
                        }
                    }
                }

                if (tryCount < MAX_REDIRECTS && responseCode != null && responseCode >= 300
                        && responseCode < 400 && StringUtils.isNotBlank(location)) {
                    redirect = true;

                    // Replace the endpoint with the redirected URL
                    dispatch.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, location);
                } else {
                    // Leave the response status as QUEUED for NoRouteToHostException and ConnectException, otherwise ERROR
                    if (e instanceof NoRouteToHostException
                            || ((e.getCause() != null) && (e.getCause() instanceof NoRouteToHostException))) {
                        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("HTTP transport error",
                                e);
                        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                                "HTTP transport error", e);
                        eventController.dispatchEvent(
                                new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(),
                                        ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                                        connectorProperties.getName(), "HTTP transport error.", e));
                    } else if ((e.getClass() == ConnectException.class) || ((e.getCause() != null)
                            && (e.getCause().getClass() == ConnectException.class))) {
                        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Connection refused.",
                                e);
                        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR,
                                getDestinationName(), connectorProperties.getName(), "Connection refused.", e));
                    } else {
                        if (e instanceof SOAPFaultException) {
                            try {
                                responseData = new DonkeyElement(((SOAPFaultException) e).getFault()).toXml();
                            } catch (DonkeyElementException e2) {
                            }
                        }
                        responseStatus = Status.ERROR;
                        responseStatusMessage = ErrorMessageBuilder
                                .buildErrorResponse("Error invoking web service", e);
                        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                                "Error invoking web service", e);
                        eventController.dispatchEvent(
                                new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(),
                                        ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                                        connectorProperties.getName(), "Error invoking web service.", e));
                    }
                }
            }
        } while (redirect && tryCount < MAX_REDIRECTS);
    } catch (Exception e) {
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error creating web service dispatch",
                e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error creating web service dispatch", e);
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error creating web service dispatch.", e));
    } finally {
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:org.apache.juddi.xlt.util.LoggingHandler.java

private void logMessage(SOAPMessageContext context) {
    boolean isOutbound = isOutboundMessage(context);

    // optionally append the HTTP request/response headers
    String headersKey = isOutbound ? MessageContext.HTTP_REQUEST_HEADERS : MessageContext.HTTP_RESPONSE_HEADERS;
    StringBuilder httpHeaders = new StringBuilder();
    Map<Object, Object> headers = (Map<Object, Object>) context.get(headersKey);
    if (headers != null && headers.size() > 0) {
        for (Entry<Object, Object> entry : headers.entrySet()) {
            httpHeaders.append("- " + entry.getKey() + " = " + entry.getValue() + "\n");
        }/*from  w  ww.  jav  a  2s.c om*/
    }

    // append the SOAP message
    String soapMessage = DomUtils.prettyPrintNode(context.getMessage().getSOAPPart());

    // append the message context properties
    StringBuilder messageContextProperties = new StringBuilder();
    TreeMap<String, Object> sortedContextProperties = new TreeMap<String, Object>(context);
    for (Entry<String, Object> entry : sortedContextProperties.entrySet()) {
        messageContextProperties.append("- " + entry.getKey() + " = " + entry.getValue() + "\n");
    }

    // finally log all
    String format = isOutbound ? OUTBOUND_MESSAGE_FORMAT : INBOUND_MESSAGE_FORMAT;
    LOG.debug(String.format(format, httpHeaders, soapMessage, messageContextProperties));
}