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

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

Introduction

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

Prototype

String HTTP_RESPONSE_HEADERS

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

Click Source Link

Document

Standard property: HTTP response headers.

Usage

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

@SuppressWarnings("unchecked")
public static boolean logToSystemOut(SOAPMessageContext smc, String tipoServizio, int versioneServizio,
        Logger log) {//  w  w  w.j a  v a2  s.  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:it.govpay.ejb.ndp.util.wsclient.NodoPerPa.java

@SuppressWarnings("unchecked")
public NodoInviaRPTRisposta nodoInviaRPT(Holder<Map<String, List<String>>> responseHeaders,
        NodoInviaRPT inviaRPT, IntestazionePPT intestazione) throws GovPayException {
    PagamentiTelematiciRPT port = configuraClient("nodoInviaRPT");

    dump(intestazione, objectFactory.createNodoInviaRPT(inviaRPT));
    NodoInviaRPTRisposta nodoInviaRisposta;
    try {/*ww  w.  j a v  a 2s  . c  om*/
        nodoInviaRisposta = port.nodoInviaRPT(inviaRPT, intestazione);
    } catch (Exception e) {
        throw new GovPayException(GovPayExceptionEnum.ERRORE_NDP_WEB, e);
    }
    dump(intestazione, objectFactory.createNodoInviaRPTRisposta(nodoInviaRisposta));
    Map<String, Object> ctx = ((BindingProvider) port).getResponseContext();
    responseHeaders.value = (Map<String, List<String>>) ctx.get(MessageContext.HTTP_RESPONSE_HEADERS);
    return nodoInviaRisposta;
}

From source file:it.govpay.ejb.ndp.util.wsclient.NodoPerPa.java

@SuppressWarnings("unchecked")
public NodoInviaCarrelloRPTRisposta nodoInviaCarrelloRPT(Holder<Map<String, List<String>>> responseHeaders,
        NodoInviaCarrelloRPT inviaCarrelloRPT, IntestazioneCarrelloPPT intestazione) throws GovPayException {
    PagamentiTelematiciRPT port = configuraClient("nodoInviaCarrelloRPT");
    dump(intestazione, objectFactory.createNodoInviaCarrelloRPT(inviaCarrelloRPT));
    NodoInviaCarrelloRPTRisposta nodoInviaCarrelloRPTRisposta;
    try {//from ww  w  .  j a  va 2 s . c  om
        nodoInviaCarrelloRPTRisposta = port.nodoInviaCarrelloRPT(inviaCarrelloRPT, intestazione);
    } catch (Exception e) {
        throw new GovPayException(GovPayExceptionEnum.ERRORE_NDP_WEB, e);
    }
    dump(intestazione, objectFactory.createNodoInviaCarrelloRPTRisposta(nodoInviaCarrelloRPTRisposta));
    Map<String, Object> ctx = ((BindingProvider) port).getResponseContext();
    responseHeaders.value = (Map<String, List<String>>) ctx.get(MessageContext.HTTP_RESPONSE_HEADERS);
    return nodoInviaCarrelloRPTRisposta;
}

From source file:it.govpay.ejb.ndp.util.wsclient.NodoPerPa.java

@SuppressWarnings("unchecked")
public NodoChiediCopiaRTRisposta nodoChiediCopiaRT(Holder<Map<String, List<String>>> responseHeaders,
        NodoChiediCopiaRT nodoChiediCopiaRT) throws GovPayException {
    PagamentiTelematiciRPT port = configuraClient("nodoChiediCopiaRT");
    dump(objectFactory.createNodoChiediCopiaRT(nodoChiediCopiaRT));
    NodoChiediCopiaRTRisposta nodoChiediCopiaRTRisposta;
    try {//  www . j  a  va  2  s  . com
        nodoChiediCopiaRTRisposta = port.nodoChiediCopiaRT(nodoChiediCopiaRT);
    } catch (Exception e) {
        throw new GovPayException(GovPayExceptionEnum.ERRORE_NDP_WEB, e);
    }
    dump(objectFactory.createNodoChiediCopiaRTRisposta(nodoChiediCopiaRTRisposta));
    Map<String, Object> ctx = ((BindingProvider) port).getResponseContext();
    responseHeaders.value = (Map<String, List<String>>) ctx.get(MessageContext.HTTP_RESPONSE_HEADERS);
    return nodoChiediCopiaRTRisposta;
}

From source file:it.govpay.ejb.ndp.util.wsclient.NodoPerPa.java

@SuppressWarnings("unchecked")
public NodoInviaRichiestaStornoRisposta nodoInviaRichiestaStorno(
        Holder<Map<String, List<String>>> responseHeaders, NodoInviaRichiestaStorno nodoInviaRichiestaStorno)
        throws GovPayException {
    PagamentiTelematiciRPT port = configuraClient("nodoInviaRichiestaStorno");
    dump(objectFactory.createNodoInviaRichiestaStorno(nodoInviaRichiestaStorno));
    NodoInviaRichiestaStornoRisposta nodoInviaRichiestaStornoRisposta;
    try {//  w w  w. j  av a 2  s . c om
        nodoInviaRichiestaStornoRisposta = port.nodoInviaRichiestaStorno(nodoInviaRichiestaStorno);
    } catch (Exception e) {
        throw new GovPayException(GovPayExceptionEnum.ERRORE_NDP_WEB, e);
    }
    dump(objectFactory.createNodoInviaRichiestaStornoRisposta(nodoInviaRichiestaStornoRisposta));
    Map<String, Object> ctx = ((BindingProvider) port).getResponseContext();
    responseHeaders.value = (Map<String, List<String>>) ctx.get(MessageContext.HTTP_RESPONSE_HEADERS);
    return nodoInviaRichiestaStornoRisposta;
}

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  .  ja va 2  s  .c  o m
    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  ww w.  ja v  a 2s  . c o  m
    }

    // 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));
}