Example usage for org.apache.http.protocol HTTP CONTENT_TYPE

List of usage examples for org.apache.http.protocol HTTP CONTENT_TYPE

Introduction

In this page you can find the example usage for org.apache.http.protocol HTTP CONTENT_TYPE.

Prototype

String CONTENT_TYPE

To view the source code for org.apache.http.protocol HTTP CONTENT_TYPE.

Click Source Link

Usage

From source file:org.alfresco.json.JSONUtil.java

/**
 * Populate HTTP message call with given content.
 * /* w  ww.j  a v a 2s .c om*/
 * @param json {@link JSONObject} content
 * @return {@link StringEntity} content.
 * @throws UnsupportedEncodingException if unsupported
 */
public static StringEntity setMessageBody(final JSONObject json) throws UnsupportedEncodingException {
    if (json == null || json.toString().isEmpty())
        throw new UnsupportedOperationException("JSON Content is required.");

    StringEntity se = setMessageBody(json.toString());
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, MIME_TYPE_JSON));
    if (logger.isDebugEnabled()) {
        logger.debug("Json string value: " + se);
    }
    return se;
}

From source file:org.apache.axis2.transport.nhttp.HttpCoreNIOSender.java

/**
 * Send the passed in response message, asynchronously
 * @param msgContext the message context to be sent
 * @throws AxisFault on error//from  ww  w. j a v  a2s . c o  m
 */
private void sendAsyncResponse(MessageContext msgContext) throws AxisFault {

    ServerWorker worker = (ServerWorker) msgContext.getProperty(Constants.OUT_TRANSPORT_INFO);
    HttpResponse response = worker.getResponse();

    OMOutputFormat format = Util.getOMOutputFormat(msgContext);

    response.setHeader(HTTP.CONTENT_TYPE,
            Util.getContentType(msgContext) + "; charset=" + format.getCharSetEncoding());

    worker.getServiceHandler().commitResponse(worker.getConn(), response);

    OutputStream out = worker.getOutputStream();
    format.setDoOptimize(msgContext.isDoingMTOM());
    try {
        (msgContext.isDoingREST() ? msgContext.getEnvelope().getBody().getFirstElement()
                : msgContext.getEnvelope()).serializeAndConsume(out, format);
        out.close();
    } catch (XMLStreamException e) {
        handleException("Error serializing response message", e);
    } catch (IOException e) {
        handleException("IO Error sending response message", e);
    }

    try {
        worker.getIs().close();
    } catch (IOException ignore) {
    }
}

From source file:org.apache.axis2.transport.nhttp.ServerWorker.java

/**
 *
 *//*from   ww  w  .  j  a v  a 2 s  .  co  m*/
private void processPost() {

    try {
        HTTPTransportUtils.processHTTPPostRequest(msgContext, is, os,
                (request.getFirstHeader(HTTP.CONTENT_TYPE) != null
                        ? request.getFirstHeader(HTTP.CONTENT_TYPE).getValue()
                        : null),
                (request.getFirstHeader(SOAPACTION) != null ? request.getFirstHeader(SOAPACTION).getValue()
                        : null),
                request.getRequestLine().getUri());
    } catch (AxisFault e) {
        handleException("Error processing POST request ", e);
    }
}

From source file:org.apache.synapse.core.axis2.Axis2FlexibleMEPClient.java

/**
 * Based on the Axis2 client code. Sends the Axis2 Message context out and returns
 * the Axis2 message context for the response.
 * <p/>/*from  w  w  w.j  av  a  2s  . c  o  m*/
 * Here Synapse works as a Client to the service. It would expect 200 ok, 202 ok and
 * 500 internal server error as possible responses.
 *
 * @param endpoint                 the endpoint being sent to, maybe null
 * @param synapseOutMessageContext the outgoing synapse message
 * @throws AxisFault on errors
 */
public static void send(

        EndpointDefinition endpoint, org.apache.synapse.MessageContext synapseOutMessageContext)
        throws AxisFault {

    boolean separateListener = false;
    boolean wsSecurityEnabled = false;
    String wsSecPolicyKey = null;
    String inboundWsSecPolicyKey = null;
    String outboundWsSecPolicyKey = null;
    boolean wsRMEnabled = false;
    boolean wsAddressingEnabled = false;
    String wsAddressingVersion = null;

    if (endpoint != null) {
        separateListener = endpoint.isUseSeparateListener();
        wsSecurityEnabled = endpoint.isSecurityOn();
        wsSecPolicyKey = endpoint.getWsSecPolicyKey();
        inboundWsSecPolicyKey = endpoint.getInboundWsSecPolicyKey();
        outboundWsSecPolicyKey = endpoint.getOutboundWsSecPolicyKey();
        wsAddressingEnabled = endpoint.isAddressingOn();
        wsAddressingVersion = endpoint.getAddressingVersion();
    }

    if (log.isDebugEnabled()) {
        String to;
        if (endpoint != null && endpoint.getAddress() != null) {
            to = endpoint.getAddress(synapseOutMessageContext);
        } else {
            to = synapseOutMessageContext.getTo().toString();
        }

        log.debug("Sending [add = " + wsAddressingEnabled + "] [sec = " + wsSecurityEnabled
                + (endpoint != null ? "] [mtom = " + endpoint.isUseMTOM() + "] [swa = " + endpoint.isUseSwa()
                        + "] [format = " + endpoint.getFormat() + "] [force soap11=" + endpoint.isForceSOAP11()
                        + "] [force soap12=" + endpoint.isForceSOAP12() + "] [pox=" + endpoint.isForcePOX()
                        + "] [get=" + endpoint.isForceGET() + "] [encoding=" + endpoint.getCharSetEncoding()
                        : "")
                + "] [to=" + to + "]");
    }

    // save the original message context without altering it, so we can tie the response
    MessageContext originalInMsgCtx = ((Axis2MessageContext) synapseOutMessageContext).getAxis2MessageContext();

    //TODO Temp hack: ESB removes the session id from request in a random manner.
    Map headers = (Map) originalInMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
    String session = (String) synapseOutMessageContext.getProperty("LB_COOKIE_HEADER");
    if (session != null) {
        headers.put("Cookie", session);
    }

    // create a new MessageContext to be sent out as this should not corrupt the original
    // we need to create the response to the original message later on
    String preserveAddressingProperty = (String) synapseOutMessageContext
            .getProperty(SynapseConstants.PRESERVE_WS_ADDRESSING);
    MessageContext axisOutMsgCtx = cloneForSend(originalInMsgCtx, preserveAddressingProperty);

    if (log.isDebugEnabled()) {
        log.debug("Message [Original Request Message ID : " + synapseOutMessageContext.getMessageID() + "]"
                + " [New Cloned Request Message ID : " + axisOutMsgCtx.getMessageID() + "]");
    }
    // set all the details of the endpoint only to the cloned message context
    // so that we can use the original message context for resending through different endpoints
    if (endpoint != null) {

        //get the endpoint encoding attribute
        String strCharSetEncoding = "";
        if (endpoint.getCharSetEncoding() != null) {
            strCharSetEncoding = ";" + endpoint.getCharSetEncoding();
        }

        if (SynapseConstants.FORMAT_POX.equals(endpoint.getFormat())) {
            axisOutMsgCtx.setDoingREST(true);
            axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
                    org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);
            axisOutMsgCtx.setProperty(Constants.Configuration.CONTENT_TYPE,
                    org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);

            Object o = axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            Map _headers = (Map) o;
            if (_headers != null) {
                _headers.remove(HTTP.CONTENT_TYPE);
                _headers.put(HTTP.CONTENT_TYPE,
                        org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML
                                + strCharSetEncoding);
            }

        } else if (SynapseConstants.FORMAT_GET.equals(endpoint.getFormat())) {
            axisOutMsgCtx.setDoingREST(true);
            axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD,
                    Constants.Configuration.HTTP_METHOD_GET);
            axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
                    org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_X_WWW_FORM);

        } else if (SynapseConstants.FORMAT_SOAP11.equals(endpoint.getFormat())) {
            axisOutMsgCtx.setDoingREST(false);
            axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
            // We need to set this explicitly here in case the request was not a POST
            axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD,
                    Constants.Configuration.HTTP_METHOD_POST);
            if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) {
                axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction());
            }
            if (!axisOutMsgCtx.isSOAP11()) {
                SOAPUtils.convertSOAP12toSOAP11(axisOutMsgCtx);
            }
            Object o = axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            Map transportHeaders = (Map) o;
            if (transportHeaders != null) {
                // Fix ESBJAVA-3645 Should not do this for multipart/related
                String trpContentType = (String) transportHeaders.get(HTTP.CONTENT_TYPE);
                if (trpContentType != null
                        && !trpContentType.contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) {
                    transportHeaders.remove(HTTP.CONTENT_TYPE);
                    transportHeaders.put(HTTP.CONTENT_TYPE,
                            org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_TEXT_XML
                                    + strCharSetEncoding);
                }
            }

        } else if (SynapseConstants.FORMAT_SOAP12.equals(endpoint.getFormat())) {
            axisOutMsgCtx.setDoingREST(false);
            axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
            // We need to set this explicitly here in case the request was not a POST
            axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD,
                    Constants.Configuration.HTTP_METHOD_POST);
            if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) {
                axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction());
            }
            if (axisOutMsgCtx.isSOAP11()) {
                SOAPUtils.convertSOAP11toSOAP12(axisOutMsgCtx);
            }
            Object o = axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            Map transportHeaders = (Map) o;
            if (transportHeaders != null) {
                // Fix ESBJAVA-3645 Should not do this for multipart/related
                String trpContentType = (String) transportHeaders.get(HTTP.CONTENT_TYPE);
                if (trpContentType != null
                        && !trpContentType.contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) {
                    transportHeaders.remove(HTTP.CONTENT_TYPE);

                    if (axisOutMsgCtx.getSoapAction() != null) {
                        String actionHeaderPrefix = ";action=\"";
                        String contentTypeWithAction = new StringBuilder(
                                org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML
                                        .length() + axisOutMsgCtx.getSoapAction().length()
                                        + actionHeaderPrefix.length() + 1).append(
                                                org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML)
                                                .append(actionHeaderPrefix)
                                                .append(axisOutMsgCtx.getSoapAction()).append('\"').toString();
                        transportHeaders.put(HTTP.CONTENT_TYPE, contentTypeWithAction + strCharSetEncoding);
                    } else {
                        transportHeaders.put(HTTP.CONTENT_TYPE,
                                org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML
                                        + strCharSetEncoding);
                    }
                }
            }
        } else if (SynapseConstants.FORMAT_REST.equals(endpoint.getFormat())) {
            /*format=rest is kept only backword compatibility. We no longer needed that.*/
            /* Remove Message Type  for GET and DELETE Request */
            if (originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD) != null) {
                if (originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD).toString()
                        .equals(Constants.Configuration.HTTP_METHOD_GET)
                        || originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD).toString()
                                .equals(Constants.Configuration.HTTP_METHOD_DELETE)) {
                    axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
                }
            }
            axisOutMsgCtx.setDoingREST(true);
        } else {
            processWSDL2RESTRequestMessageType(originalInMsgCtx, axisOutMsgCtx);
        }

        if (endpoint.isUseMTOM()) {
            axisOutMsgCtx.setDoingMTOM(true);
            // fix / workaround for AXIS2-1798
            axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
                    org.apache.axis2.Constants.VALUE_TRUE);
            axisOutMsgCtx.setDoingMTOM(true);

        } else if (endpoint.isUseSwa()) {
            axisOutMsgCtx.setDoingSwA(true);
            // fix / workaround for AXIS2-1798
            axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_SWA,
                    org.apache.axis2.Constants.VALUE_TRUE);
            axisOutMsgCtx.setDoingSwA(true);
        }

        if (endpoint.getCharSetEncoding() != null) {
            axisOutMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING,
                    endpoint.getCharSetEncoding());
        }

        // HTTP Endpoint : use the specified HTTP method and remove REST_URL_POSTFIX, it's not supported in HTTP Endpoint
        if (endpoint.isHTTPEndpoint()) {
            axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD,
                    synapseOutMessageContext.getProperty(Constants.Configuration.HTTP_METHOD));
            axisOutMsgCtx.removeProperty(NhttpConstants.REST_URL_POSTFIX);
        }

        // add rest request' suffix URI
        String restSuffix = (String) axisOutMsgCtx.getProperty(NhttpConstants.REST_URL_POSTFIX);
        boolean isRest = SynapseConstants.FORMAT_REST.equals(endpoint.getFormat());

        if (!isRest && !endpoint.isForceSOAP11() && !endpoint.isForceSOAP12()) {
            isRest = isRequestRest(originalInMsgCtx);
        }

        if (endpoint.getAddress() != null) {
            String address = endpoint.getAddress(synapseOutMessageContext);
            if (isRest && restSuffix != null && !"".equals(restSuffix)) {

                String url = "";
                if (!address.endsWith("/") && !restSuffix.startsWith("/") && !restSuffix.startsWith("?")) {
                    url = address + "/" + restSuffix;
                } else if (address.endsWith("/") && restSuffix.startsWith("/")) {
                    url = address + restSuffix.substring(1);
                } else if (address.endsWith("/") && restSuffix.startsWith("?")) {
                    url = address.substring(0, address.length() - 1) + restSuffix;
                } else {
                    if (!address.startsWith("jms")) {
                        url = address + restSuffix;
                    } else {
                        url = address;
                    }
                }
                axisOutMsgCtx.setTo(new EndpointReference(url));

            } else {
                axisOutMsgCtx.setTo(new EndpointReference(address));
            }
            axisOutMsgCtx.setProperty(NhttpConstants.ENDPOINT_PREFIX, address);
            synapseOutMessageContext.setProperty(SynapseConstants.ENDPOINT_PREFIX, address);
        } else {
            // Supporting RESTful invocation
            if (isRest && restSuffix != null && !"".equals(restSuffix)) {
                EndpointReference epr = axisOutMsgCtx.getTo();
                if (epr != null) {
                    String address = epr.getAddress();
                    String url;
                    if (!address.endsWith("/") && !restSuffix.startsWith("/") && !restSuffix.startsWith("?")) {
                        url = address + "/" + restSuffix;
                    } else {
                        url = address + restSuffix;
                    }
                    axisOutMsgCtx.setTo(new EndpointReference(url));
                }
            }
        }

        if (endpoint.isUseSeparateListener()) {
            axisOutMsgCtx.getOptions().setUseSeparateListener(true);
        }
    } else {
        processWSDL2RESTRequestMessageType(originalInMsgCtx, axisOutMsgCtx);
    }

    // only put whttp:location for the REST (GET) requests, otherwise causes issues for POX messages
    if (axisOutMsgCtx.isDoingREST() && HTTPConstants.MEDIA_TYPE_X_WWW_FORM
            .equals(axisOutMsgCtx.getProperty(Constants.Configuration.MESSAGE_TYPE))) {
        if (axisOutMsgCtx.getProperty(WSDL2Constants.ATTR_WHTTP_LOCATION) == null
                && axisOutMsgCtx.getEnvelope().getBody().getFirstElement() != null) {
            axisOutMsgCtx.setProperty(WSDL2Constants.ATTR_WHTTP_LOCATION,
                    axisOutMsgCtx.getEnvelope().getBody().getFirstElement().getQName().getLocalPart());
        }
    }

    if (wsAddressingEnabled) {

        if (wsAddressingVersion != null
                && SynapseConstants.ADDRESSING_VERSION_SUBMISSION.equals(wsAddressingVersion)) {

            axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION,
                    AddressingConstants.Submission.WSA_NAMESPACE);

        } else if (wsAddressingVersion != null
                && SynapseConstants.ADDRESSING_VERSION_FINAL.equals(wsAddressingVersion)) {

            axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION,
                    AddressingConstants.Final.WSA_NAMESPACE);
        }

        axisOutMsgCtx.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE);
    } else {
        axisOutMsgCtx.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE);
    }

    // remove the headers if we don't need to preserve them.
    // determine weather we need to preserve the processed headers
    String preserveHeaderProperty = (String) synapseOutMessageContext
            .getProperty(SynapseConstants.PRESERVE_PROCESSED_HEADERS);
    if (preserveHeaderProperty == null || !Boolean.parseBoolean(preserveHeaderProperty)) {
        // default behaviour is to remove the headers
        MessageHelper.removeProcessedHeaders(axisOutMsgCtx,
                (preserveAddressingProperty != null && Boolean.parseBoolean(preserveAddressingProperty)));
    }

    ConfigurationContext axisCfgCtx = axisOutMsgCtx.getConfigurationContext();
    AxisConfiguration axisCfg = axisCfgCtx.getAxisConfiguration();

    AxisService anoymousService = AnonymousServiceFactory.getAnonymousService(
            synapseOutMessageContext.getConfiguration(), axisCfg, wsAddressingEnabled, wsRMEnabled,
            wsSecurityEnabled);
    // mark the anon services created to be used in the client side of synapse as hidden
    // from the server side of synapse point of view
    anoymousService.getParent().addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true");
    ServiceGroupContext sgc = new ServiceGroupContext(axisCfgCtx,
            (AxisServiceGroup) anoymousService.getParent());
    ServiceContext serviceCtx = sgc.getServiceContext(anoymousService);

    boolean outOnlyMessage = "true".equals(synapseOutMessageContext.getProperty(SynapseConstants.OUT_ONLY));

    // get a reference to the DYNAMIC operation of the Anonymous Axis2 service
    AxisOperation axisAnonymousOperation = anoymousService
            .getOperation(outOnlyMessage ? new QName(AnonymousServiceFactory.OUT_ONLY_OPERATION)
                    : new QName(AnonymousServiceFactory.OUT_IN_OPERATION));

    Options clientOptions = MessageHelper.cloneOptions(originalInMsgCtx.getOptions());
    clientOptions.setUseSeparateListener(separateListener);

    // if security is enabled,
    if (wsSecurityEnabled) {
        // if a WS-Sec policy is specified, use it
        if (wsSecPolicyKey != null) {
            clientOptions.setProperty(SynapseConstants.RAMPART_POLICY,
                    MessageHelper.getPolicy(synapseOutMessageContext, wsSecPolicyKey));
        } else {
            if (inboundWsSecPolicyKey != null) {
                clientOptions.setProperty(SynapseConstants.RAMPART_IN_POLICY,
                        MessageHelper.getPolicy(synapseOutMessageContext, inboundWsSecPolicyKey));
            }
            if (outboundWsSecPolicyKey != null) {
                clientOptions.setProperty(SynapseConstants.RAMPART_OUT_POLICY,
                        MessageHelper.getPolicy(synapseOutMessageContext, outboundWsSecPolicyKey));
            }
        }
        // temporary workaround for https://issues.apache.org/jira/browse/WSCOMMONS-197
        if (axisOutMsgCtx.getEnvelope().getHeader() == null) {
            SOAPFactory fac = axisOutMsgCtx.isSOAP11() ? OMAbstractFactory.getSOAP11Factory()
                    : OMAbstractFactory.getSOAP12Factory();
            fac.createSOAPHeader(axisOutMsgCtx.getEnvelope());
        }
    }

    OperationClient mepClient = axisAnonymousOperation.createClient(serviceCtx, clientOptions);
    mepClient.addMessageContext(axisOutMsgCtx);
    axisOutMsgCtx.setAxisMessage(axisAnonymousOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE));

    // set the SEND_TIMEOUT for transport sender
    if (endpoint != null && endpoint.getEffectiveTimeout() > 0) {
        axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.getEffectiveTimeout());
    }

    // always set a callback as we decide if the send it blocking or non blocking within
    // the MEP client. This does not cause an overhead, as we simply create a 'holder'
    // object with a reference to the outgoing synapse message context
    // synapseOutMessageContext
    AsyncCallback callback = new AsyncCallback(axisOutMsgCtx, synapseOutMessageContext);
    if (!outOnlyMessage) {
        if (endpoint != null) {
            // set the timeout time and the timeout action to the callback, so that the
            // TimeoutHandler can detect timed out callbacks and take appropriate action.
            long endpointTimeout = endpoint.getEffectiveTimeout();
            callback.setTimeOutOn(System.currentTimeMillis() + endpointTimeout);
            callback.setTimeOutAction(endpoint.getTimeoutAction());
            callback.setTimeoutDuration(endpointTimeout);
        } else {
            long globalTimeout = synapseOutMessageContext.getEnvironment().getGlobalTimeout();
            callback.setTimeOutOn(System.currentTimeMillis() + globalTimeout);
            callback.setTimeoutDuration(globalTimeout);
        }

    }
    mepClient.setCallback(callback);
    //
    //        if (Utils.isClientThreadNonBlockingPropertySet(axisOutMsgCtx)) {
    //            SynapseCallbackReceiver synapseCallbackReceiver = (SynapseCallbackReceiver) axisOutMsgCtx.getAxisOperation().getMessageReceiver();
    //            synapseCallbackReceiver.addCallback(axisOutMsgCtx.getMessageID(), new FaultCallback(axisOutMsgCtx, synapseOutMessageContext));
    //        }

    // this is a temporary fix for converting messages from HTTP 1.1 chunking to HTTP 1.0.
    // Without this HTTP transport can block & become unresponsive because we are streaming
    // HTTP 1.1 messages and HTTP 1.0 require the whole message to caculate the content length
    if (originalInMsgCtx.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) {
        synapseOutMessageContext.getEnvelope().toString();
    }

    // with the nio transport, this causes the listener not to write a 202
    // Accepted response, as this implies that Synapse does not yet know if
    // a 202 or 200 response would be written back.
    originalInMsgCtx.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP");

    // if the transport out is explicitly set use it
    Object o = originalInMsgCtx.getProperty("TRANSPORT_OUT_DESCRIPTION");
    if (o != null && o instanceof TransportOutDescription) {
        axisOutMsgCtx.setTransportOut((TransportOutDescription) o);
        clientOptions.setTransportOut((TransportOutDescription) o);
        clientOptions.setProperty("TRANSPORT_OUT_DESCRIPTION", o);
    }

    // clear the message context properties related to endpoint in last service invocation
    Set keySet = synapseOutMessageContext.getPropertyKeySet();
    if (keySet != null) {
        keySet.remove(EndpointDefinition.DYNAMIC_URL_VALUE);
    }

    //at the last point of mediation engine where the client get invoked we reduce concurrent
    // throttling count for OUT_ONLY messages
    if (outOnlyMessage) {
        Boolean isConcurrencyThrottleEnabled = (Boolean) synapseOutMessageContext
                .getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE);
        if (isConcurrencyThrottleEnabled != null && isConcurrencyThrottleEnabled) {
            ConcurrentAccessController concurrentAccessController = (ConcurrentAccessController) synapseOutMessageContext
                    .getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_CONTROLLER);
            int available = concurrentAccessController.incrementAndGet();
            int concurrentLimit = concurrentAccessController.getLimit();
            if (log.isDebugEnabled()) {
                log.debug("Concurrency Throttle : Connection returned" + " :: " + available
                        + " of available of " + concurrentLimit + " connections");
            }
            ConcurrentAccessReplicator concurrentAccessReplicator = (ConcurrentAccessReplicator) synapseOutMessageContext
                    .getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_REPLICATOR);
            String throttleKey = (String) synapseOutMessageContext
                    .getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE_KEY);
            if (concurrentAccessReplicator != null) {
                concurrentAccessReplicator.replicate(throttleKey, concurrentAccessController);
            }
        }
    }

    mepClient.execute(true);
}

From source file:org.apache.synapse.mediators.bsf.CommonScriptMessageContext.java

private void handleSpecialProperties(String key, Object value,
        org.apache.axis2.context.MessageContext messageContext) {
    if (org.apache.axis2.Constants.Configuration.MESSAGE_TYPE.equals(key)) {
        messageContext.setProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE, value);
        Object o = messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        Map headers = (Map) o;
        if (headers != null) {
            headers.put(HTTP.CONTENT_TYPE, value);
        }//from  ww  w.j  a  v  a  2  s  . c o  m
    }
}

From source file:org.apache.synapse.transport.nhttp.ClientHandler.java

/**
 * Process a response received for the request sent out
 * /* ww  w.  j av  a2  s .  c  om*/
 * @param conn the connection being processed
 */
public void responseReceived(final NHttpClientConnection conn) {

    setServerContextAttribute(NhttpConstants.RES_FROM_BACKEND_READ_START_TIME, System.currentTimeMillis(),
            conn);

    HttpContext context = conn.getContext();
    HttpResponse response = conn.getHttpResponse();

    ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context.getAttribute(TUNNEL_HANDLER);
    if (tunnelHandler != null && !tunnelHandler.isCompleted()) {
        context.removeAttribute(TUNNEL_HANDLER);
        tunnelHandler.handleResponse(response, conn);
        if (tunnelHandler.isSuccessful()) {
            log.debug(conn + ": Tunnel established");
            conn.resetInput();
            conn.requestOutput();
            return;
        } else {
            Axis2HttpRequest axis2Req = (Axis2HttpRequest) context.getAttribute(ATTACHMENT_KEY);
            context.setAttribute(AXIS2_HTTP_REQUEST, axis2Req);
            context.setAttribute(OUTGOING_MESSAGE_CONTEXT, axis2Req.getMsgContext());
            ContentOutputBuffer outputBuffer = new SharedOutputBuffer(cfg.getBufferSize(), conn, allocator);
            axis2Req.setOutputBuffer(outputBuffer);
            context.setAttribute(REQUEST_SOURCE_BUFFER, outputBuffer);
            context.setAttribute(NhttpConstants.DISCARD_ON_COMPLETE, Boolean.TRUE);
        }
    }

    setServerContextAttribute(NhttpConstants.RES_HEADER_ARRIVAL_TIME, System.currentTimeMillis(), conn);

    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CONTINUE) {
        if (log.isDebugEnabled()) {
            log.debug(conn + ": Received a 100 Continue response");
        }
        // according to the HTTP 1.1 specification HTTP status 100 continue implies that
        // the response will be followed, and the client should just ignore the 100 Continue
        // and wait for the response
        return;
    }

    ClientConnectionDebug ccd = (ClientConnectionDebug) conn.getContext().getAttribute(CLIENT_CONNECTION_DEBUG);
    if (ccd != null) {
        ccd.recordResponseStartTime(response.getStatusLine().toString());
    }

    // Have we sent out our request fully in the first place? if not, forget about it now..
    Axis2HttpRequest req = (Axis2HttpRequest) conn.getContext().getAttribute(AXIS2_HTTP_REQUEST);

    if (req != null) {
        req.setCompleted(true);

        if (log.isDebugEnabled()) {
            log.debug(conn + ": Response Received for Request : " + req);
        }
        if (!req.isSendingCompleted()) {
            req.getMsgContext().setProperty(NhttpConstants.ERROR_CODE, NhttpConstants.SEND_ABORT);
            SharedOutputBuffer outputBuffer = (SharedOutputBuffer) conn.getContext()
                    .getAttribute(REQUEST_SOURCE_BUFFER);
            if (outputBuffer != null) {
                outputBuffer.shutdown();
            }
            if (log.isDebugEnabled()) {
                log.debug(conn + ": Remote server aborted request being sent and replied : " + conn
                        + " for request : " + conn.getContext().getAttribute(NhttpConstants.HTTP_REQ_METHOD));
            }
            context.setAttribute(NhttpConstants.DISCARD_ON_COMPLETE, Boolean.TRUE);
            if (metrics != null) {
                metrics.incrementFaultsSending(NhttpConstants.SEND_ABORT, req.getMsgContext());
            }
        }
    }

    switch (response.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_ACCEPTED: {
        if (log.isDebugEnabled()) {
            log.debug(conn + ": Received a 202 Accepted response");
        }

        // Process response body if Content-Type header is present in the response
        // If Content-Type header is null, We will ignore entity body
        Header contentType = response.getFirstHeader(HTTP.CONTENT_TYPE);
        if (contentType != null) {
            processResponse(conn, context, response);
            return;
        }

        // sometimes, some http clients sends an "\r\n" as the content body with a
        // HTTP 202 OK.. we will just get it into this temp buffer and ignore it..
        ContentInputBuffer inputBuffer = new SharedInputBuffer(8, conn, allocator);
        context.setAttribute(RESPONSE_SINK_BUFFER, inputBuffer);

        // create a dummy message with an empty SOAP envelope and a property
        // NhttpConstants.SC_ACCEPTED set to Boolean.TRUE to indicate this is a
        // placeholder message for the transport to send a HTTP 202 to the
        // client. Should / would be ignored by any transport other than
        // nhttp. For example, JMS would not send a reply message for one-way
        // operations.
        MessageContext outMsgCtx = (MessageContext) context.getAttribute(OUTGOING_MESSAGE_CONTEXT);
        MessageReceiver mr = outMsgCtx.getAxisOperation().getMessageReceiver();

        // the following check is to support the dual channel invocation. Hence the
        // response will be sent as a new request to the client over a different channel
        // client sends back a 202 Accepted response to synapse and we need to neglect that 
        // 202 Accepted message
        if (!outMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) {

            try {
                MessageContext responseMsgCtx = outMsgCtx.getOperationContext()
                        .getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN);
                if (responseMsgCtx == null || outMsgCtx.getOptions().isUseSeparateListener()
                        || outMsgCtx.getOperationContext().isComplete()) {
                    if (responseMsgCtx != null && responseMsgCtx.getProperty("synapse.send") == null) {
                        return;
                    }
                } else if (responseMsgCtx == null || outMsgCtx.getOptions().isUseSeparateListener()) {
                    // Since we need to notify the SynapseCallback receiver to remove the
                    // call backs registered  we set a custom property
                    setHeaders(context, response, outMsgCtx, responseMsgCtx);
                    outMsgCtx.setProperty(NhttpConstants.HTTP_202_RECEIVED, "true");
                    mr.receive(outMsgCtx);
                    return;
                }

                if (responseMsgCtx == null) {
                    return;
                }

                setHeaders(context, response, outMsgCtx, responseMsgCtx);
                responseMsgCtx.setServerSide(true);
                responseMsgCtx.setDoingREST(outMsgCtx.isDoingREST());
                responseMsgCtx.setProperty(MessageContext.TRANSPORT_IN,
                        outMsgCtx.getProperty(MessageContext.TRANSPORT_IN));
                responseMsgCtx.setTransportIn(outMsgCtx.getTransportIn());
                responseMsgCtx.setTransportOut(outMsgCtx.getTransportOut());

                responseMsgCtx.setAxisMessage(
                        outMsgCtx.getAxisOperation().getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE));
                responseMsgCtx.setOperationContext(outMsgCtx.getOperationContext());
                responseMsgCtx.setConfigurationContext(outMsgCtx.getConfigurationContext());
                responseMsgCtx.setTo(null);

                if (!outMsgCtx.isDoingREST() && !outMsgCtx.isSOAP11()) {
                    responseMsgCtx.setEnvelope(new SOAP12Factory().getDefaultEnvelope());
                } else {
                    responseMsgCtx.setEnvelope(new SOAP11Factory().getDefaultEnvelope());
                }
                responseMsgCtx.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES,
                        Boolean.TRUE);
                responseMsgCtx.setProperty(NhttpConstants.SC_ACCEPTED, Boolean.TRUE);
                int statusCode = response.getStatusLine().getStatusCode();
                responseMsgCtx.setProperty(NhttpConstants.HTTP_SC, statusCode);
                mr.receive(responseMsgCtx);

            } catch (org.apache.axis2.AxisFault af) {
                log.debug(conn + ": Unable to report back " + "202 Accepted state to the message receiver");
            }
        }

        return;
    }

    case HttpStatus.SC_OK: {
        processResponse(conn, context, response);
        return;
    }
    case HttpStatus.SC_INTERNAL_SERVER_ERROR: {
        if (warnOnHttp500(response)) {
            log.warn(getErrorMessage(
                    "Received an internal server error : " + response.getStatusLine().getReasonPhrase(), conn));
        }
        processResponse(conn, context, response);
        return;
    }
    default: {
        if (log.isDebugEnabled()) {
            log.debug(conn + ": "
                    + getErrorMessage("HTTP status code received : " + response.getStatusLine().getStatusCode()
                            + " :: " + response.getStatusLine().getReasonPhrase(), conn));
        }

        Header contentType = response.getFirstHeader(HTTP.CONTENT_TYPE);
        if (contentType != null) {
            if ((contentType.getValue().indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) >= 0)
                    || contentType.getValue().indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) >= 0) {

                if (log.isDebugEnabled()) {
                    log.debug(conn + ": Received an unexpected response with a SOAP payload");
                }

            } else if (contentType.getValue().indexOf("html") == -1) {
                if (log.isDebugEnabled()) {
                    log.debug(conn + ": Received an unexpected response with a POX/REST payload");
                }
            } else {
                log.warn(getErrorMessage(
                        "Received an unexpected response - " + "of content type : " + contentType.getValue()
                                + " and status code : " + response.getStatusLine().getStatusCode()
                                + " with reason : " + response.getStatusLine().getReasonPhrase(),
                        conn));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(conn + ": "
                        + getErrorMessage(
                                "Received a response - " + "without a content type with status code : "
                                        + response.getStatusLine().getStatusCode() + " and reason : "
                                        + response.getStatusLine().getReasonPhrase(),
                                conn));
            }
        }

        processResponse(conn, context, response);
    }
    }
}

From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOSender.java

/**
 * Send the passed in response message, asynchronously
 * @param msgContext the message context to be sent
 * @throws AxisFault on error/*  www  . ja  v  a 2s .  c o m*/
 */
private void sendAsyncResponse(MessageContext msgContext) throws AxisFault {

    int contentLength = extractContentLength(msgContext);

    // remove unwanted HTTP headers (if any from the current message)
    removeUnwantedHeaders(msgContext);
    Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);

    ServerWorker worker = (ServerWorker) msgContext.getProperty(Constants.OUT_TRANSPORT_INFO);
    HttpResponse response = worker.getResponse();

    OMOutputFormat format = NhttpUtil.getOMOutputFormat(msgContext);
    MessageFormatter messageFormatter = MessageFormatterDecoratorFactory
            .createMessageFormatterDecorator(msgContext);
    Boolean noEntityBody = (Boolean) msgContext.getProperty(NhttpConstants.NO_ENTITY_BODY);
    if (noEntityBody == null || Boolean.FALSE == noEntityBody) {
        response.setHeader(HTTP.CONTENT_TYPE,
                messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
    } else if (Boolean.TRUE == noEntityBody) {
        ((BasicHttpEntity) response.getEntity()).setChunked(false);
        ((BasicHttpEntity) response.getEntity()).setContentLength(0);

        // Since HTTP HEAD request doesn't contain message body content length of the is set to be 0. To handle
        // content length 0 while serving head method, content length of the backend response is set as the content
        // as synapse cannot calculate content length without providing message body.
        if (transportHeaders.get(NhttpConstants.HTTP_REQUEST_METHOD) != null
                && NhttpConstants.HTTP_HEAD.equals(transportHeaders.get(NhttpConstants.HTTP_REQUEST_METHOD))
                && transportHeaders.get(NhttpConstants.ORIGINAL_CONTENT_LEN) != null) {

            ((BasicHttpEntity) response.getEntity()).setContentLength(
                    Long.parseLong(String.valueOf(transportHeaders.get(NhttpConstants.ORIGINAL_CONTENT_LEN))));
            transportHeaders.remove(NhttpConstants.ORIGINAL_CONTENT_LEN);
            transportHeaders.remove(NhttpConstants.HTTP_REQUEST_METHOD);
        }
    }
    response.setStatusCode(determineHttpStatusCode(msgContext, response));

    //Override the Standard Reason Phrase
    if (msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE) != null
            && !msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE).equals("")) {
        response.setReasonPhrase(msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE).toString());
    }

    // set any transport headers
    if (transportHeaders != null && !transportHeaders.values().isEmpty()) {
        Iterator iter = transportHeaders.keySet().iterator();
        while (iter.hasNext()) {
            Object header = iter.next();
            Object value = transportHeaders.get(header);
            if (value != null && header instanceof String && value instanceof String) {
                response.addHeader((String) header, (String) value);

                String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;

                Map map = (Map) msgContext.getProperty(excessProp);
                if (map != null && map.get(header) != null) {
                    log.debug("Number of excess values for " + header + " header is : "
                            + ((Collection) (map.get(header))).size());

                    for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
                        String key = (String) iterator.next();

                        for (String excessVal : (Collection<String>) map.get(key)) {
                            if (header.equals(key)) {
                                response.addHeader((String) header, (String) excessVal);
                            }
                        }

                    }
                }
            }
        }
    }

    boolean forceContentLength = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH);
    boolean forceContentLengthCopy = msgContext
            .isPropertyTrue(NhttpConstants.COPY_CONTENT_LENGTH_FROM_INCOMING);

    BasicHttpEntity entity = (BasicHttpEntity) response.getEntity();

    MetricsCollector lstMetrics = worker.getServiceHandler().getMetrics();
    try {
        if (forceContentLength) {
            entity.setChunked(false);
            if (forceContentLengthCopy && contentLength > 0) {
                entity.setContentLength(contentLength);
            } else {
                setStreamAsTempData(entity, messageFormatter, msgContext, format);
            }
        }

        worker.getServiceHandler().commitResponse(worker.getConn(), response);
        lstMetrics.reportResponseCode(response.getStatusLine().getStatusCode());
        OutputStream out = worker.getOutputStream();

        /*
         * if this is a dummy message to handle http 202 case with non-blocking IO
         * write an empty byte array as body
         */
        if (msgContext.isPropertyTrue(NhttpConstants.SC_ACCEPTED) || Boolean.TRUE == noEntityBody) {
            out.write(new byte[0]);
        } else {
            if (forceContentLength) {
                if (forceContentLengthCopy && contentLength > 0) {
                    messageFormatter.writeTo(msgContext, format, out, false);
                } else {
                    writeMessageFromTempData(out, msgContext);
                }
            } else {
                messageFormatter.writeTo(msgContext, format, out, false);
            }
        }
        out.close();
        if (lstMetrics != null) {
            lstMetrics.incrementMessagesSent();
        }

    } catch (ProtocolException e) {
        log.error(e + " (Synapse may be trying to send an exact response more than once )");
    } catch (HttpException e) {
        if (lstMetrics != null) {
            lstMetrics.incrementFaultsSending();
        }
        handleException("Unexpected HTTP protocol error sending response to : " + worker.getRemoteAddress(), e);
    } catch (ConnectionClosedException e) {
        if (lstMetrics != null) {
            lstMetrics.incrementFaultsSending();
        }
        log.warn("Connection closed by client : " + worker.getRemoteAddress());
    } catch (IllegalStateException e) {
        if (lstMetrics != null) {
            lstMetrics.incrementFaultsSending();
        }
        log.warn("Connection closed by client : " + worker.getRemoteAddress());
    } catch (IOException e) {
        if (lstMetrics != null) {
            lstMetrics.incrementFaultsSending();
        }
        handleException("IO Error sending response message to : " + worker.getRemoteAddress(), e);
    } catch (Exception e) {
        if (lstMetrics != null) {
            lstMetrics.incrementFaultsSending();
        }
        handleException("General Error sending response message to : " + worker.getRemoteAddress(), e);
    }

    InputStream is = worker.getIs();
    if (is != null) {
        try {
            is.close();
        } catch (IOException ignore) {
        }
    }
}

From source file:org.apache.synapse.transport.passthru.ClientWorker.java

public void run() {

    CustomLogSetter.getInstance().clearThreadLocalContent();
    if (responseMsgCtx == null) {
        return;/*from ww  w . j  a  v a 2  s .  co  m*/
    }
    if (responseMsgCtx.getProperty(PassThroughConstants.PASS_THROUGH_SOURCE_CONNECTION) != null) {
        ((NHttpServerConnection) responseMsgCtx
                .getProperty(PassThroughConstants.PASS_THROUGH_SOURCE_CONNECTION)).getContext().setAttribute(
                        PassThroughConstants.CLIENT_WORKER_START_TIME, System.currentTimeMillis());
    }
    try {
        if (expectEntityBody) {
            String cType = response.getHeader(HTTP.CONTENT_TYPE);
            if (cType == null) {
                cType = response.getHeader(HTTP.CONTENT_TYPE.toLowerCase());
            }
            String contentType;
            if (cType != null) {
                // This is the most common case - Most of the time servers send the Content-Type
                contentType = cType;
            } else {
                // Server hasn't sent the header - Try to infer the content type
                contentType = inferContentType();
            }

            responseMsgCtx.setProperty(Constants.Configuration.CONTENT_TYPE, contentType);

            String charSetEnc = BuilderUtil.getCharSetEncoding(contentType);
            if (charSetEnc == null) {
                charSetEnc = MessageContext.DEFAULT_CHAR_SET_ENCODING;
            }
            if (contentType != null) {
                responseMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING,
                        contentType.indexOf("charset") > 0 ? charSetEnc
                                : MessageContext.DEFAULT_CHAR_SET_ENCODING);
            }

            responseMsgCtx.setServerSide(false);
            SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
            SOAPEnvelope envelope = fac.getDefaultEnvelope();
            try {
                responseMsgCtx.setEnvelope(envelope);
            } catch (AxisFault axisFault) {
                log.error("Error setting SOAP envelope", axisFault);
            }

            responseMsgCtx.setServerSide(true);
        } else {
            // there is no response entity-body
            responseMsgCtx.setProperty(PassThroughConstants.NO_ENTITY_BODY, Boolean.TRUE);
            responseMsgCtx.setEnvelope(new SOAP11Factory().getDefaultEnvelope());
        }

        // copy the HTTP status code as a message context property with the key HTTP_SC to be
        // used at the sender to set the proper status code when passing the message
        int statusCode = this.response.getStatus();
        responseMsgCtx.setProperty(PassThroughConstants.HTTP_SC, statusCode);
        responseMsgCtx.setProperty(PassThroughConstants.HTTP_SC_DESC, response.getStatusLine());
        if (statusCode >= 400) {
            responseMsgCtx.setProperty(PassThroughConstants.FAULT_MESSAGE, PassThroughConstants.TRUE);
        } /*else if (statusCode == 202 && responseMsgCtx.getOperationContext().isComplete()) {
          // Handle out-only invocation scenario
          responseMsgCtx.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);
          }*/
        responseMsgCtx.setProperty(PassThroughConstants.NON_BLOCKING_TRANSPORT, true);

        // process response received
        try {
            AxisEngine.receive(responseMsgCtx);
        } catch (AxisFault af) {
            log.error("Fault processing response message through Axis2", af);
        }

    } catch (AxisFault af) {
        log.error("Fault creating response SOAP envelope", af);
    }
}

From source file:org.apache.synapse.transport.passthru.ClientWorker.java

private String inferContentType() {
    //Check whether server sent Content-Type in different case
    Map<String, String> headers = response.getHeaders();
    for (String header : headers.keySet()) {
        if (HTTP.CONTENT_TYPE.equalsIgnoreCase(header)) {
            return headers.get(header);
        }// w w  w  .  j ava 2  s .  c o  m
    }
    String cType = response.getHeader("content-type");
    if (cType != null) {
        return cType;
    }
    cType = response.getHeader("Content-type");
    if (cType != null) {
        return cType;
    }

    // Try to get the content type from the message context
    Object cTypeProperty = responseMsgCtx.getProperty(PassThroughConstants.CONTENT_TYPE);
    if (cTypeProperty != null) {
        return cTypeProperty.toString();
    }
    // Try to get the content type from the axis configuration
    Parameter cTypeParam = targetConfiguration.getConfigurationContext().getAxisConfiguration()
            .getParameter(PassThroughConstants.CONTENT_TYPE);
    if (cTypeParam != null) {
        return cTypeParam.getValue().toString();
    }

    // When the response from backend does not have the body(Content-Length is 0 )
    // and Content-Type is not set; ESB should not do any modification to the response and pass-through as it is.
    if (headers.get(HTTP.CONTENT_LEN) == null || "0".equals(headers.get(HTTP.CONTENT_LEN))) {
        return null;
    }

    // Unable to determine the content type - Return default value
    return PassThroughConstants.DEFAULT_CONTENT_TYPE;
}

From source file:org.apache.synapse.transport.passthru.PassThroughHttpSender.java

public void submitResponse(MessageContext msgContext) throws IOException, HttpException {
    SourceConfiguration sourceConfiguration = (SourceConfiguration) msgContext
            .getProperty(PassThroughConstants.PASS_THROUGH_SOURCE_CONFIGURATION);

    NHttpServerConnection conn = (NHttpServerConnection) msgContext
            .getProperty(PassThroughConstants.PASS_THROUGH_SOURCE_CONNECTION);
    if (conn == null) {
        ServerWorker serverWorker = (ServerWorker) msgContext.getProperty(Constants.OUT_TRANSPORT_INFO);
        if (serverWorker != null) {
            MessageContext requestContext = serverWorker.getRequestContext();
            conn = (NHttpServerConnection) requestContext
                    .getProperty(PassThroughConstants.PASS_THROUGH_SOURCE_CONNECTION);
            sourceConfiguration = (SourceConfiguration) requestContext
                    .getProperty(PassThroughConstants.PASS_THROUGH_SOURCE_CONFIGURATION);
        } else {//from  ww w  . j  av a2 s .c om
            throw new IllegalStateException("Unable to correlate the response to a request");
        }
    }

    // Handle ETag caching
    if (msgContext.getProperty(PassThroughConstants.HTTP_ETAG_ENABLED) != null
            && (Boolean) msgContext.getProperty(PassThroughConstants.HTTP_ETAG_ENABLED)) {

        try {
            RelayUtils.buildMessage(msgContext);
        } catch (IOException e) {
            handleException("IO Error occurred while building the message", e);
        } catch (XMLStreamException e) {
            handleException("XML Error occurred while building the message", e);
        }

        String hash = digestGenerator.getDigest(msgContext);
        Map headers = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
        headers.put(HttpHeaders.ETAG, "\"" + hash + "\"");
    }

    SourceRequest sourceRequest = SourceContext.getRequest(conn);

    SourceResponse sourceResponse = SourceResponseFactory.create(msgContext, sourceRequest,
            sourceConfiguration);
    sourceResponse.checkResponseChunkDisable(msgContext);

    SourceContext.setResponse(conn, sourceResponse);

    Boolean noEntityBody = (Boolean) msgContext.getProperty(PassThroughConstants.NO_ENTITY_BODY);
    Pipe pipe = (Pipe) msgContext.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
    if ((noEntityBody == null || !noEntityBody) || pipe != null) {
        if (pipe == null) {
            pipe = new Pipe(sourceConfiguration.getBufferFactory().getBuffer(), "Test", sourceConfiguration);
            msgContext.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
            msgContext.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);
        }

        pipe.attachConsumer(conn);
        sourceResponse.connect(pipe);
    }

    Integer errorCode = (Integer) msgContext.getProperty(PassThroughConstants.ERROR_CODE);
    if (errorCode != null) {
        sourceResponse.setStatus(HttpStatus.SC_BAD_GATEWAY);
        SourceContext.get(conn).setShutDown(true);
    }

    ProtocolState state = SourceContext.getState(conn);
    if (state != null && state.compareTo(ProtocolState.REQUEST_DONE) <= 0) {
        // start sending the response if we

        boolean noEntityBodyResponse = false;
        if (noEntityBody != null && Boolean.TRUE == noEntityBody && pipe != null) {
            OutputStream out = pipe.getOutputStream();
            out.write(new byte[0]);
            pipe.setRawSerializationComplete(true);
            out.close();
            noEntityBodyResponse = true;
        }

        if (!noEntityBodyResponse && msgContext.isPropertyTrue(PassThroughConstants.MESSAGE_BUILDER_INVOKED)
                && pipe != null) {
            OutputStream out = pipe.getOutputStream();
            /*if (msgContext.isPropertyTrue(NhttpConstants.SC_ACCEPTED)) {
            out.write(new byte[0]);
            }else {*/

            //This is to support MTOM in response path for requests sent without a SOAPAction. The reason is
            //axis2 selects application/xml formatter as the formatter for formatting the ESB to client response
            //when there is no SOAPAction.
            if (Constants.VALUE_TRUE.equals(msgContext.getProperty(Constants.Configuration.ENABLE_MTOM))) {
                msgContext.setProperty(Constants.Configuration.CONTENT_TYPE,
                        PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED);
                msgContext.setProperty(Constants.Configuration.MESSAGE_TYPE,
                        PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED);
            }

            MessageFormatter formatter = MessageFormatterDecoratorFactory
                    .createMessageFormatterDecorator(msgContext);
            OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(msgContext);

            Object contentTypeInMsgCtx = msgContext
                    .getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE);
            boolean isContentTypeSetFromMsgCtx = false;

            // If ContentType header is set in the axis2 message context, use it.
            if (contentTypeInMsgCtx != null) {
                String contentTypeValueInMsgCtx = contentTypeInMsgCtx.toString();
                // Skip multipart/related as it should be taken from formatter.
                if (!contentTypeValueInMsgCtx.contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) {

                    if (format != null) {
                        String encoding = format.getCharSetEncoding();
                        if (encoding != null) {
                            sourceResponse.removeHeader(HTTP.CONTENT_TYPE);
                            contentTypeValueInMsgCtx += "; charset=" + encoding;
                        }
                    }

                    sourceResponse.addHeader(HTTP.CONTENT_TYPE, contentTypeValueInMsgCtx);
                    isContentTypeSetFromMsgCtx = true;
                }
            }

            // If ContentType is not set from msg context, get the formatter ContentType
            if (!isContentTypeSetFromMsgCtx) {
                sourceResponse.removeHeader(HTTP.CONTENT_TYPE);
                sourceResponse.addHeader(HTTP.CONTENT_TYPE,
                        formatter.getContentType(msgContext, format, msgContext.getSoapAction()));
            }

            try {
                formatter.writeTo(msgContext, format, out, false);
            } catch (RemoteException fault) {
                IOUtils.closeQuietly(out);
                throw fault;
            }
            pipe.setSerializationComplete(true);
            out.close();
        }

        conn.requestOutput();
    } else {
        // nothing much to do as we have started the response already
        if (errorCode != null) {
            if (log.isDebugEnabled()) {
                log.warn("A Source connection is closed because of an " + "error in target: " + conn);
            }
        } else {
            log.debug("A Source Connection is closed, because source handler "
                    + "is already in the process of writing a response while "
                    + "another response is submitted: " + conn);
        }

        SourceContext.updateState(conn, ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
    }
}