Example usage for org.apache.http.protocol ExecutionContext HTTP_REQUEST

List of usage examples for org.apache.http.protocol ExecutionContext HTTP_REQUEST

Introduction

In this page you can find the example usage for org.apache.http.protocol ExecutionContext HTTP_REQUEST.

Prototype

String HTTP_REQUEST

To view the source code for org.apache.http.protocol ExecutionContext HTTP_REQUEST.

Click Source Link

Usage

From source file:org.apache.http.impl.client.DefaultRedirectHandler.java

public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException {
    Args.notNull(response, "HTTP response");
    //get the location header to find out where to redirect to
    final Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }/*w w  w  .jav  a 2 s.  co  m*/
    final String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri;
    try {
        uri = new URI(location);
    } catch (final URISyntaxException ex) {
        throw new ProtocolException("Invalid redirect URI: " + location, ex);
    }

    final HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        final HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        Asserts.notNull(target, "Target host");

        final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

        try {
            final URI requestURI = new URI(request.getRequestLine().getUri());
            final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (final URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        final URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                final HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (final URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:org.apache.http.impl.client.DefaultRequestDirector.java

/**
 * Establish connection either directly or through a tunnel and retry in case of
 * a recoverable I/O failure// www . jav a  2s  . com
 */
private void tryConnect(final RoutedRequest req, final HttpContext context) throws HttpException, IOException {
    final HttpRoute route = req.getRoute();
    final HttpRequest wrapper = req.getRequest();

    int connectCount = 0;
    for (;;) {
        context.setAttribute(ExecutionContext.HTTP_REQUEST, wrapper);
        // Increment connect count
        connectCount++;
        try {
            if (!managedConn.isOpen()) {
                managedConn.open(route, context, params);
            } else {
                managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
            }
            establishRoute(route, context);
            break;
        } catch (final IOException ex) {
            try {
                managedConn.close();
            } catch (final IOException ignore) {
            }
            if (retryHandler.retryRequest(ex, connectCount, context)) {
                if (this.log.isInfoEnabled()) {
                    this.log.info("I/O exception (" + ex.getClass().getName() + ") caught when connecting to "
                            + route + ": " + ex.getMessage());
                    if (this.log.isDebugEnabled()) {
                        this.log.debug(ex.getMessage(), ex);
                    }
                    this.log.info("Retrying connect to " + route);
                }
            } else {
                throw ex;
            }
        }
    }
}

From source file:org.apache.http.impl.client.DefaultRequestDirector.java

/**
 * Creates a tunnel to the target server.
 * The connection must be established to the (last) proxy.
 * A CONNECT request for tunnelling through the proxy will
 * be created and sent, the response received and checked.
 * This method does <i>not</i> update the connection with
 * information about the tunnel, that is left to the caller.
 *
 * @param route     the route to establish
 * @param context   the context for request execution
 *
 * @return  <code>true</code> if the tunnelled route is secure,
 *          <code>false</code> otherwise.
 *          The implementation here always returns <code>false</code>,
 *          but derived classes may override.
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 *///  w w w. ja  v a  2s.  c o m
protected boolean createTunnelToTarget(final HttpRoute route, final HttpContext context)
        throws HttpException, IOException {

    final HttpHost proxy = route.getProxyHost();
    final HttpHost target = route.getTargetHost();
    HttpResponse response = null;

    for (;;) {
        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }

        final HttpRequest connect = createConnectRequest(route, context);
        connect.setParams(this.params);

        // Populate the execution context
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
        context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
        context.setAttribute(ExecutionContext.HTTP_REQUEST, connect);

        this.requestExec.preProcess(connect, this.httpProcessor, context);

        response = this.requestExec.execute(connect, this.managedConn, context);

        response.setParams(this.params);
        this.requestExec.postProcess(response, this.httpProcessor, context);

        final int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }

        if (HttpClientParams.isAuthenticating(this.params)) {
            if (this.authenticator.isAuthenticationRequested(proxy, response, this.proxyAuthStrategy,
                    this.proxyAuthState, context)) {
                if (this.authenticator.authenticate(proxy, response, this.proxyAuthStrategy,
                        this.proxyAuthState, context)) {
                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        final HttpEntity entity = response.getEntity();
                        EntityUtils.consume(entity);
                    } else {
                        this.managedConn.close();
                    }
                } else {
                    break;
                }
            } else {
                break;
            }
        }
    }

    final int status = response.getStatusLine().getStatusCode();

    if (status > 299) {

        // Buffer response content
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }

        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }

    this.managedConn.markReusable();

    // How to decide on security of the tunnelled connection?
    // The socket factory knows only about the segment to the proxy.
    // Even if that is secure, the hop to the target may be insecure.
    // Leave it to derived classes, consider insecure by default here.
    return false;

}

From source file:org.apache.http.impl.client.DefaultRequestDirector.java

/**
 * Creates a tunnel to the target server.
 * The connection must be established to the (last) proxy.
 * A CONNECT request for tunnelling through the proxy will
 * be created and sent, the response received and checked.
 * This method does <i>not</i> update the connection with
 * information about the tunnel, that is left to the caller.
 *
 * @param route     the route to establish
 * @param context   the context for request execution
 *
 * @return  {@code true} if the tunnelled route is secure,
 *          {@code false} otherwise.//from   w  w w . j a v  a 2s .  c o m
 *          The implementation here always returns {@code false},
 *          but derived classes may override.
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 */
protected boolean createTunnelToTarget(final HttpRoute route, final HttpContext context)
        throws HttpException, IOException {

    final HttpHost proxy = route.getProxyHost();
    final HttpHost target = route.getTargetHost();
    HttpResponse response = null;

    for (;;) {
        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }

        final HttpRequest connect = createConnectRequest(route, context);
        connect.setParams(this.params);

        // Populate the execution context
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
        context.setAttribute(ClientContext.ROUTE, route);
        context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
        context.setAttribute(ExecutionContext.HTTP_REQUEST, connect);

        this.requestExec.preProcess(connect, this.httpProcessor, context);

        response = this.requestExec.execute(connect, this.managedConn, context);

        response.setParams(this.params);
        this.requestExec.postProcess(response, this.httpProcessor, context);

        final int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }

        if (HttpClientParams.isAuthenticating(this.params)) {
            if (this.authenticator.isAuthenticationRequested(proxy, response, this.proxyAuthStrategy,
                    this.proxyAuthState, context)) {
                if (this.authenticator.authenticate(proxy, response, this.proxyAuthStrategy,
                        this.proxyAuthState, context)) {
                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        final HttpEntity entity = response.getEntity();
                        EntityUtils.consume(entity);
                    } else {
                        this.managedConn.close();
                    }
                } else {
                    break;
                }
            } else {
                break;
            }
        }
    }

    final int status = response.getStatusLine().getStatusCode();

    if (status > 299) {

        // Buffer response content
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }

        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }

    this.managedConn.markReusable();

    // How to decide on security of the tunnelled connection?
    // The socket factory knows only about the segment to the proxy.
    // Even if that is secure, the hop to the target may be insecure.
    // Leave it to derived classes, consider insecure by default here.
    return false;

}

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

/**
 * Process a new connection over an existing TCP connection or new
 * // www  .j  a va 2s.c  o m
 * @param conn HTTP connection to be processed
 * @param axis2Req axis2 representation of the message in the connection
 * @throws ConnectionClosedException if the connection is closed 
 */
private void processConnection(final NHttpClientConnection conn, final Axis2HttpRequest axis2Req)
        throws ConnectionClosedException {

    // record start time of request
    ClientConnectionDebug cd = (ClientConnectionDebug) axis2Req.getMsgContext()
            .getProperty(CLIENT_CONNECTION_DEBUG);
    if (cd != null) {
        cd.recordRequestStartTime(conn, axis2Req);
        conn.getContext().setAttribute(CLIENT_CONNECTION_DEBUG, cd);
    }

    try {
        // Reset connection metrics
        conn.getMetrics().reset();

        HttpContext context = conn.getContext();
        ContentOutputBuffer outputBuffer = new SharedOutputBuffer(cfg.getBufferSize(), conn, allocator);
        axis2Req.setOutputBuffer(outputBuffer);
        context.setAttribute(REQUEST_SOURCE_BUFFER, outputBuffer);

        HttpRoute route = axis2Req.getRoute();
        context.setAttribute(AXIS2_HTTP_REQUEST, axis2Req);
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, route.getTargetHost());
        context.setAttribute(OUTGOING_MESSAGE_CONTEXT, axis2Req.getMsgContext());

        HttpRequest request = axis2Req.getRequest();
        request.setParams(new DefaultedHttpParams(request.getParams(), this.params));

        /*
         * Remove Content-Length and Transfer-Encoding headers, if already present.
         * */
        request.removeHeaders(HTTP.TRANSFER_ENCODING);
        request.removeHeaders(HTTP.CONTENT_LEN);

        this.httpProcessor.process(request, context);
        if (proxyauthenticator != null && route.getProxyHost() != null && !route.isTunnelled()) {
            proxyauthenticator.authenticatePreemptively(request, context);
        }
        if (axis2Req.getTimeout() > 0) {
            conn.setSocketTimeout(axis2Req.getTimeout());
        }

        context.setAttribute(NhttpConstants.ENDPOINT_PREFIX, axis2Req.getEndpointURLPrefix());
        context.setAttribute(NhttpConstants.HTTP_REQ_METHOD, request.getRequestLine().getMethod());
        context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
        setServerContextAttribute(NhttpConstants.REQ_DEPARTURE_TIME, System.currentTimeMillis(), conn);
        setServerContextAttribute(NhttpConstants.REQ_TO_BACKEND_WRITE_START_TIME, System.currentTimeMillis(),
                conn);

        conn.submitRequest(request);
    } catch (ConnectionClosedException e) {
        throw e;
    } catch (IOException e) {
        if (metrics != null) {
            metrics.incrementFaultsSending();
        }
        handleException("I/O Error submitting request : " + e.getMessage(), e, conn);
    } catch (HttpException e) {
        if (metrics != null) {
            metrics.incrementFaultsSending();
        }
        handleException("HTTP protocol error submitting request : " + e.getMessage(), e, conn);
    } finally {
        synchronized (axis2Req) {
            axis2Req.setReadyToStream(true);
            axis2Req.notifyAll();
        }
    }
}

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

private static void cleanConnectionReferences(NHttpClientConnection conn) {

    HttpContext ctx = conn.getContext();
    Axis2HttpRequest axis2Req = (Axis2HttpRequest) ctx.getAttribute(ClientHandler.AXIS2_HTTP_REQUEST);
    axis2Req.clear(); // this is linked via the selection key attachment and will free itself
                      // on timeout of the keep alive connection. Till then minimize the
                      // memory usage to a few bytes 

    ctx.removeAttribute(ClientHandler.ATTACHMENT_KEY);
    ctx.removeAttribute(ClientHandler.TUNNEL_HANDLER);
    ctx.removeAttribute(ClientHandler.AXIS2_HTTP_REQUEST);
    ctx.removeAttribute(ClientHandler.OUTGOING_MESSAGE_CONTEXT);
    ctx.removeAttribute(ClientHandler.REQUEST_SOURCE_BUFFER);
    ctx.removeAttribute(ClientHandler.RESPONSE_SINK_BUFFER);

    ctx.removeAttribute(ExecutionContext.HTTP_REQUEST);
    ctx.removeAttribute(ExecutionContext.HTTP_RESPONSE);

    conn.resetOutput();/*w w  w .  j a v  a2s  .c om*/
}

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

/**
 * Process a new incoming request/*from w w w  .  java  2  s .c o  m*/
 * @param conn the connection
 */
public void requestReceived(final NHttpServerConnection conn) {

    HttpContext context = conn.getContext();
    context.setAttribute(NhttpConstants.REQ_ARRIVAL_TIME, System.currentTimeMillis());
    context.setAttribute(NhttpConstants.REQ_FROM_CLIENT_READ_START_TIME, System.currentTimeMillis());
    HttpRequest request = conn.getHttpRequest();
    context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
    context.setAttribute(NhttpConstants.MESSAGE_IN_FLIGHT, "true");

    // prepare to collect debug information
    conn.getContext().setAttribute(ServerHandler.SERVER_CONNECTION_DEBUG, new ServerConnectionDebug(conn));

    NHttpConfiguration cfg = NHttpConfiguration.getInstance();
    try {
        InputStream is;
        // Only create an input buffer and ContentInputStream if the request has content
        if (request instanceof HttpEntityEnclosingRequest) {
            // Mark request as not yet fully read, to detect timeouts from harmless keepalive deaths
            conn.getContext().setAttribute(NhttpConstants.REQUEST_READ, Boolean.FALSE);

            ContentInputBuffer inputBuffer = new SharedInputBuffer(cfg.getBufferSize(), conn, allocator);
            context.setAttribute(REQUEST_SINK_BUFFER, inputBuffer);
            is = new ContentInputStream(inputBuffer);
        } else {
            is = null;
            conn.getContext().removeAttribute(NhttpConstants.REQUEST_READ);
        }

        ContentOutputBuffer outputBuffer = new SharedOutputBuffer(cfg.getBufferSize(), conn, allocator);
        context.setAttribute(RESPONSE_SOURCE_BUFFER, outputBuffer);
        OutputStream os = new ContentOutputStream(outputBuffer);

        // create the default response to this request
        ProtocolVersion httpVersion = request.getRequestLine().getProtocolVersion();
        HttpResponse response = responseFactory.newHttpResponse(httpVersion, HttpStatus.SC_OK, context);

        // create a basic HttpEntity using the source channel of the response pipe
        BasicHttpEntity entity = new BasicHttpEntity();
        if (httpVersion.greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);

        if (metrics != null) {
            metrics.incrementMessagesReceived();
        }
        // hand off processing of the request to a thread off the pool
        ServerWorker worker = new ServerWorker(cfgCtx, scheme.getName(), metrics, conn, this, request, is,
                response, os, listenerContext.isRestDispatching(),
                listenerContext.getHttpGetRequestProcessor());

        if (workerPool != null) {
            workerPool.execute(worker);
        } else if (executor != null) {
            Map<String, String> headers = new HashMap<String, String>();
            for (Header header : request.getAllHeaders()) {
                headers.put(header.getName(), header.getValue());
            }

            EvaluatorContext evaluatorContext = new EvaluatorContext(request.getRequestLine().getUri(),
                    headers);
            int priority = parser.parse(evaluatorContext);
            executor.execute(worker, priority);
        }

        // See if the client expects a 100-Continue
        Header expect = request.getFirstHeader(HTTP.EXPECT_DIRECTIVE);
        if (expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue())) {
            HttpResponse ack = new BasicHttpResponse(request.getProtocolVersion(), HttpStatus.SC_CONTINUE,
                    "Continue");
            conn.submitResponse(ack);
            if (log.isDebugEnabled()) {
                log.debug(conn + ": Expect :100 Continue hit, sending ack back to the server");
            }
            return;
        }

    } catch (Exception e) {
        if (metrics != null) {
            metrics.incrementFaultsReceiving();
        }
        handleException("Error processing request received for : " + request.getRequestLine().getUri(), e,
                conn);
    }
}

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

public void exception(NHttpServerConnection conn, Exception ex) {
    boolean isFault = false;
    if (ex instanceof IOException) {
        logIOException(conn, (IOException) ex);

        metrics.incrementFaultsReceiving();

        ProtocolState state = SourceContext.getState(conn);
        if (state == ProtocolState.REQUEST_BODY || state == ProtocolState.REQUEST_HEAD) {
            informReaderError(conn);/*from   ww  w .ja v  a2  s.c  o m*/
        } else if (state == ProtocolState.RESPONSE_BODY || state == ProtocolState.RESPONSE_HEAD) {
            informWriterError(conn);
        } else if (state == ProtocolState.REQUEST_DONE) {
            informWriterError(conn);
        } else if (state == ProtocolState.RESPONSE_DONE) {
            informWriterError(conn);
        }
        isFault = true;
        SourceContext.updateState(conn, ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
    } else if (ex instanceof HttpException) {
        try {
            if (conn.isResponseSubmitted()) {
                sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
                return;
            }
            HttpContext httpContext = conn.getContext();

            HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST,
                    "Bad request");
            response.setParams(
                    new DefaultedHttpParams(sourceConfiguration.getHttpParams(), response.getParams()));
            response.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);

            // Pre-process HTTP request
            httpContext.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            httpContext.setAttribute(ExecutionContext.HTTP_REQUEST, null);
            httpContext.setAttribute(ExecutionContext.HTTP_RESPONSE, response);

            sourceConfiguration.getHttpProcessor().process(response, httpContext);

            conn.submitResponse(response);
            SourceContext.updateState(conn, ProtocolState.CLOSED);
            conn.close();
        } catch (Exception ex1) {
            log.error(ex.getMessage(), ex);
            SourceContext.updateState(conn, ProtocolState.CLOSED);
            sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
            isFault = true;
        }
    } else {
        log.error("Unexpected error: " + ex.getMessage(), ex);
        SourceContext.updateState(conn, ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
        isFault = true;
    }

    if (isFault) {
        rollbackTransaction(conn);
    }
}

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

/**
 * Starts the response by writing the headers
 * @param conn connection//from ww  w .  j  a  v a 2 s  .  c om
 * @throws java.io.IOException if an error occurs
 * @throws org.apache.http.HttpException if an error occurs
 */
public void start(NHttpServerConnection conn) throws IOException, HttpException {
    // create the response
    response = sourceConfiguration.getResponseFactory().newHttpResponse(request.getVersion(), this.status,
            request.getConnection().getContext());

    if (statusLine != null) {
        response.setStatusLine(version, status, statusLine);
    } else {
        response.setStatusCode(status);
    }

    BasicHttpEntity entity = null;

    if (canResponseHaveBody(request.getRequest(), response)) {
        entity = new BasicHttpEntity();

        int contentLength = -1;
        String contentLengthHeader = null;
        if (headers.get(HTTP.CONTENT_LEN) != null && headers.get(HTTP.CONTENT_LEN).size() > 0) {
            contentLengthHeader = headers.get(HTTP.CONTENT_LEN).first();
        }

        if (contentLengthHeader != null) {
            contentLength = Integer.parseInt(contentLengthHeader);
            headers.remove(HTTP.CONTENT_LEN);
        }

        if (contentLength != -1) {
            entity.setChunked(false);
            entity.setContentLength(contentLength);
        } else {
            entity.setChunked(true);
        }

    }

    response.setEntity(entity);

    // set any transport headers
    Set<Map.Entry<String, TreeSet<String>>> entries = headers.entrySet();

    for (Map.Entry<String, TreeSet<String>> entry : entries) {
        if (entry.getKey() != null) {
            Iterator<String> i = entry.getValue().iterator();
            while (i.hasNext()) {
                response.addHeader(entry.getKey(), i.next());
            }
        }
    }
    response.setParams(new DefaultedHttpParams(response.getParams(), sourceConfiguration.getHttpParams()));

    SourceContext.updateState(conn, ProtocolState.RESPONSE_HEAD);

    // Pre-process HTTP response
    conn.getContext().setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    conn.getContext().setAttribute(ExecutionContext.HTTP_RESPONSE, response);
    conn.getContext().setAttribute(ExecutionContext.HTTP_REQUEST, SourceContext.getRequest(conn).getRequest());

    sourceConfiguration.getHttpProcessor().process(response, conn.getContext());
    conn.submitResponse(response);

    // Handle non entity body responses
    if (entity == null) {
        hasEntity = false;
        // Reset connection state
        sourceConfiguration.getSourceConnections().releaseConnection(conn);
        // Make ready to deal with a new request
        conn.requestInput();
    }
}

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

public void start(NHttpClientConnection conn) throws IOException, HttpException {
    if (pipe != null) {
        TargetContext.get(conn).setWriter(pipe);
    }//  w  w  w.  j  a  v  a2s .c  om

    String path = fullUrl || (route.getProxyHost() != null && !route.isTunnelled()) ? url.toString()
            : url.getPath() + (url.getQuery() != null ? "?" + url.getQuery() : "");

    long contentLength = -1;
    String contentLengthHeader = null;
    if (headers.get(HTTP.CONTENT_LEN) != null && headers.get(HTTP.CONTENT_LEN).size() > 0) {
        contentLengthHeader = headers.get(HTTP.CONTENT_LEN).first();
    }

    if (contentLengthHeader != null) {
        contentLength = Integer.parseInt(contentLengthHeader);
        headers.remove(HTTP.CONTENT_LEN);
    }

    MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx();

    if (requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH) != null) {
        contentLength = (Long) requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH);
    }

    //fix for  POST_TO_URI
    if (requestMsgCtx.isPropertyTrue(NhttpConstants.POST_TO_URI)) {
        path = url.toString();
    }

    //fix GET request empty body
    if ((("GET").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))
            || (("DELETE").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))) {
        hasEntityBody = false;
        MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(requestMsgCtx);
        OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(requestMsgCtx);
        if (formatter != null && format != null) {
            URL _url = formatter.getTargetAddress(requestMsgCtx, format, url);
            if (_url != null && !_url.toString().isEmpty()) {
                if (requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI) != null && Boolean.TRUE.toString()
                        .equals(requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI))) {
                    path = _url.toString();
                } else {
                    path = _url.getPath()
                            + ((_url.getQuery() != null && !_url.getQuery().isEmpty()) ? ("?" + _url.getQuery())
                                    : "");
                }

            }
            headers.remove(HTTP.CONTENT_TYPE);
        }
    }

    Object o = requestMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (o != null && o instanceof TreeMap) {
        Map _headers = (Map) o;
        String trpContentType = (String) _headers.get(HTTP.CONTENT_TYPE);
        if (trpContentType != null && !trpContentType.equals("")) {
            if (!trpContentType.contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) {
                addHeader(HTTP.CONTENT_TYPE, trpContentType);
            }

        }

    }

    if (hasEntityBody) {
        request = new BasicHttpEntityEnclosingRequest(method, path,
                version != null ? version : HttpVersion.HTTP_1_1);

        BasicHttpEntity entity = new BasicHttpEntity();

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

        if (forceContentLength) {
            entity.setChunked(false);
            if (forceContentLengthCopy && contentLength > 0) {
                entity.setContentLength(contentLength);
            }
        } else {
            if (contentLength != -1) {
                entity.setChunked(false);
                entity.setContentLength(contentLength);
            } else {
                entity.setChunked(chunk);
            }
        }

        ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);

    } else {
        request = new BasicHttpRequest(method, path, version != null ? version : HttpVersion.HTTP_1_1);
    }

    Set<Map.Entry<String, TreeSet<String>>> entries = headers.entrySet();
    for (Map.Entry<String, TreeSet<String>> entry : entries) {
        if (entry.getKey() != null) {
            Iterator<String> i = entry.getValue().iterator();
            while (i.hasNext()) {
                request.addHeader(entry.getKey(), i.next());
            }
        }
    }

    //setup wsa action..
    if (request != null) {

        String soapAction = requestMsgCtx.getSoapAction();
        if (soapAction == null) {
            soapAction = requestMsgCtx.getWSAAction();
        }
        if (soapAction == null) {
            requestMsgCtx.getAxisOperation().getInputAction();
        }

        if (requestMsgCtx.isSOAP11() && soapAction != null && soapAction.length() > 0) {
            Header existingHeader = request.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
            if (existingHeader != null) {
                request.removeHeader(existingHeader);
            }
            MessageFormatter messageFormatter = MessageFormatterDecoratorFactory
                    .createMessageFormatterDecorator(requestMsgCtx);
            request.setHeader(HTTPConstants.HEADER_SOAP_ACTION,
                    messageFormatter.formatSOAPAction(requestMsgCtx, null, soapAction));
            //request.setHeader(HTTPConstants.USER_AGENT,"Synapse-PT-HttpComponents-NIO");
        }
    }

    request.setParams(new DefaultedHttpParams(request.getParams(), targetConfiguration.getHttpParams()));

    //Chucking is not performed for request has "http 1.0" and "GET" http method
    if (!((request.getProtocolVersion().equals(HttpVersion.HTTP_1_0))
            || (("GET").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))
            || (("DELETE").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))))) {
        this.processChunking(conn, requestMsgCtx);
    }

    if (!keepAlive) {
        request.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
    }

    // Pre-process HTTP request
    conn.getContext().setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    conn.getContext().setAttribute(ExecutionContext.HTTP_TARGET_HOST, new HttpHost(url.getHost(), port));
    conn.getContext().setAttribute(ExecutionContext.HTTP_REQUEST, request);

    // start the request
    targetConfiguration.getHttpProcessor().process(request, conn.getContext());

    if (targetConfiguration.getProxyAuthenticator() != null && route.getProxyHost() != null
            && !route.isTunnelled()) {
        targetConfiguration.getProxyAuthenticator().authenticatePreemptively(request, conn.getContext());
    }

    conn.submitRequest(request);

    if (hasEntityBody) {
        TargetContext.updateState(conn, ProtocolState.REQUEST_HEAD);
    } else {
        TargetContext.updateState(conn, ProtocolState.REQUEST_DONE);
    }
}