Example usage for org.apache.http.params DefaultedHttpParams DefaultedHttpParams

List of usage examples for org.apache.http.params DefaultedHttpParams DefaultedHttpParams

Introduction

In this page you can find the example usage for org.apache.http.params DefaultedHttpParams DefaultedHttpParams.

Prototype

public DefaultedHttpParams(HttpParams httpParams, HttpParams httpParams2) 

Source Link

Usage

From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java

private HttpClient setupClient(URL url, SampleResult res) {

    Map<HttpClientKey, HttpClient> mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY
            .get();//from w ww.j a v  a 2  s.co m

    final String host = url.getHost();
    final String proxyHost = getProxyHost();
    final int proxyPort = getProxyPortInt();

    boolean useStaticProxy = isStaticProxy(host);
    boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort);

    // Lookup key - must agree with all the values used to create the HttpClient.
    HttpClientKey key = new HttpClientKey(url, (useStaticProxy || useDynamicProxy),
            useDynamicProxy ? proxyHost : PROXY_HOST, useDynamicProxy ? proxyPort : PROXY_PORT,
            useDynamicProxy ? getProxyUser() : PROXY_USER, useDynamicProxy ? getProxyPass() : PROXY_PASS);

    HttpClient httpClient = mapHttpClientPerHttpClientKey.get(key);

    if (httpClient != null && resetSSLContext
            && HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(url.getProtocol())) {
        ((AbstractHttpClient) httpClient).clearRequestInterceptors();
        ((AbstractHttpClient) httpClient).clearResponseInterceptors();
        httpClient.getConnectionManager().closeIdleConnections(1L, TimeUnit.MICROSECONDS);
        httpClient = null;
        JsseSSLManager sslMgr = (JsseSSLManager) SSLManager.getInstance();
        sslMgr.resetContext();
        resetSSLContext = false;
    }

    if (httpClient == null) { // One-time init for this client

        HttpParams clientParams = new DefaultedHttpParams(new BasicHttpParams(), DEFAULT_HTTP_PARAMS);

        DnsResolver resolver = this.testElement.getDNSResolver();
        if (resolver == null) {
            resolver = new SystemDefaultDnsResolver();
        }
        ClientConnectionManager connManager = new MeasuringConnectionManager(
                SchemeRegistryFactory.createDefault(), resolver);

        httpClient = new DefaultHttpClient(connManager, clientParams) {
            @Override
            protected HttpRequestRetryHandler createHttpRequestRetryHandler() {
                return new DefaultHttpRequestRetryHandler(RETRY_COUNT, false); // set retry count
            }
        };
        if (IDLE_TIMEOUT > 0) {
            ((AbstractHttpClient) httpClient).setKeepAliveStrategy(IDLE_STRATEGY);
        }
        ((AbstractHttpClient) httpClient).addResponseInterceptor(new ResponseContentEncoding());
        ((AbstractHttpClient) httpClient).addResponseInterceptor(METRICS_SAVER); // HACK
        ((AbstractHttpClient) httpClient).addRequestInterceptor(METRICS_RESETTER);

        // Override the defualt schemes as necessary
        SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();

        if (SLOW_HTTP != null) {
            schemeRegistry.register(SLOW_HTTP);
        }

        if (HTTPS_SCHEME != null) {
            schemeRegistry.register(HTTPS_SCHEME);
        }

        // Set up proxy details
        if (useDynamicProxy) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            String proxyUser = getProxyUser();

            if (proxyUser.length() > 0) {
                ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(
                        new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(proxyUser, getProxyPass(), localHost, PROXY_DOMAIN));
            }
        } else if (useStaticProxy) {
            HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT);
            clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            if (PROXY_USER.length() > 0) {
                ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(
                        new AuthScope(PROXY_HOST, PROXY_PORT),
                        new NTCredentials(PROXY_USER, PROXY_PASS, localHost, PROXY_DOMAIN));
            }
        }

        // Bug 52126 - we do our own cookie handling
        clientParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);

        if (log.isDebugEnabled()) {
            log.debug("Created new HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString());
        }

        mapHttpClientPerHttpClientKey.put(key, httpClient); // save the agent for next time round
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Reusing the HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString());
        }
    }

    MeasuringConnectionManager connectionManager = (MeasuringConnectionManager) httpClient
            .getConnectionManager();
    connectionManager.setSample(res);

    // TODO - should this be done when the client is created?
    // If so, then the details need to be added as part of HttpClientKey
    setConnectionAuthorization(httpClient, url, getAuthManager(), key);

    return httpClient;
}

From source file:de.escidoc.core.common.util.service.ConnectionUtility.java

/**
 * Get a new {@link HttpClient} instance. Each instance will use the same {@link ThreadSafeClientConnManager}. New
 * instances are being created because of possible configurations done on the {@link HttpClient}. See
 * {@link ConnectionUtility#setAuthentication(DefaultHttpClient, URL, String, String)} for example. If multiple
 * threads are using the same {@link HttpClient} instance, they could overwrite the credentials and everything else
 * of the {@link HttpClient} causing the {@link HttpClient} instance to become unusable for other threads. Therefore
 * new instances will be returned.<br/>
 * The {@link HttpClient} instance will be initialized with {@link DefaultedHttpParams}, which delegates resolution
 * of a parameter to the given default {@link HttpParams} instance, which is read-only, if the parameter is not
 * present in the local one.<br/>//from   ww  w .j  av a2  s  . co  m
 * <br/>
 * <b>Note:</b> A user of the returned {@link HttpClient} instance shall not modify the configurations on the
 * {@link ClientConnectionManager} of this instance, because this will affect all other users of the
 * {@link HttpClient} instances returned by this ConnectionUtility. If you need to change the behavior of the
 * {@link ClientConnectionManager}, then use the configuration of the {@link HttpClient} because {@link HttpParams}
 * will be handled in a hierarchy. <br/>
 * <br/>
 * <b>TODO:</b> return {@link HttpClient} instead of {@link DefaultHttpClient}.
 * 
 * @return DefaultHttpClient
 */
public DefaultHttpClient getHttpClient() {
    return new DefaultHttpClient(CONN_MANAGER,
            new DefaultedHttpParams(new BasicHttpParams(), DEFAULT_HTTP_PARAMS));
}

From source file:de.escidoc.core.common.util.service.ConnectionUtility.java

/**
 * Get a new {@link HttpClient} instance overwriting the default configuration by the parameters in
 * <tt>overwriteParams</tt>. Each instance will use the same {@link ThreadSafeClientConnManager}. New instances are
 * being created because of possible configurations done on the {@link HttpClient}. See
 * {@link ConnectionUtility#setAuthentication(DefaultHttpClient, URL, String, String)} for example. If multiple
 * threads are using the same {@link HttpClient} instance, they could overwrite the credentials and everything else
 * of the {@link HttpClient} causing the {@link HttpClient} instance to become unusable for other threads. Therefore
 * new instances will be returned.<br/>
 * The {@link HttpClient} instance will be initialized with {@link DefaultedHttpParams}, which delegates resolution
 * of a parameter to the given default {@link HttpParams} instance, which is read-only, if the parameter is not
 * present in the local one.<br/>//from   ww  w  .j ava 2 s.  c  o  m
 * <br/>
 * <b>Note:</b> A user of the returned {@link HttpClient} instance shall not modify the configurations on the
 * {@link ClientConnectionManager} of this instance, because this will affect all other users of the
 * {@link HttpClient} instances returned by this ConnectionUtility. If you need to change the behavior of the
 * {@link ClientConnectionManager}, then use the configuration of the {@link HttpClient} because {@link HttpParams}
 * will be handled in a hierarchy. <br/>
 * <br/>
 * <b>TODO:</b> return {@link HttpClient} instead of {@link DefaultHttpClient}.
 * 
 * @return DefaultHttpClient
 */
public DefaultHttpClient getHttpClient(final HttpParams overwriteParams) {
    final HttpParams params = overwriteParams == null ? new BasicHttpParams() : overwriteParams;
    return new DefaultHttpClient(CONN_MANAGER, new DefaultedHttpParams(params, DEFAULT_HTTP_PARAMS));
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

private HttpClient setupClient(URL url, SampleResult res) {

    Map<HttpClientKey, HttpClient> mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY
            .get();/*from   ww w . j ava  2 s.  c o  m*/

    final String host = url.getHost();
    String proxyHost = getProxyHost();
    int proxyPort = getProxyPortInt();
    String proxyPass = getProxyPass();
    String proxyUser = getProxyUser();

    // static proxy is the globally define proxy eg command line or properties
    boolean useStaticProxy = isStaticProxy(host);
    // dynamic proxy is the proxy defined for this sampler
    boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort);
    boolean useProxy = useStaticProxy || useDynamicProxy;

    // if both dynamic and static are used, the dynamic proxy has priority over static
    if (!useDynamicProxy) {
        proxyHost = PROXY_HOST;
        proxyPort = PROXY_PORT;
        proxyUser = PROXY_USER;
        proxyPass = PROXY_PASS;
    }

    // Lookup key - must agree with all the values used to create the HttpClient.
    HttpClientKey key = new HttpClientKey(url, useProxy, proxyHost, proxyPort, proxyUser, proxyPass);

    HttpClient httpClient = null;
    if (this.testElement.isConcurrentDwn()) {
        httpClient = (HttpClient) JMeterContextService.getContext().getSamplerContext().get(HTTPCLIENT_TOKEN);
    }

    if (httpClient == null) {
        httpClient = mapHttpClientPerHttpClientKey.get(key);
    }

    if (httpClient != null && resetSSLContext
            && HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(url.getProtocol())) {
        ((AbstractHttpClient) httpClient).clearRequestInterceptors();
        ((AbstractHttpClient) httpClient).clearResponseInterceptors();
        httpClient.getConnectionManager().closeIdleConnections(1L, TimeUnit.MICROSECONDS);
        httpClient = null;
        JsseSSLManager sslMgr = (JsseSSLManager) SSLManager.getInstance();
        sslMgr.resetContext();
        resetSSLContext = false;
    }

    if (httpClient == null) { // One-time init for this client

        HttpParams clientParams = new DefaultedHttpParams(new BasicHttpParams(), DEFAULT_HTTP_PARAMS);

        DnsResolver resolver = this.testElement.getDNSResolver();
        if (resolver == null) {
            resolver = SystemDefaultDnsResolver.INSTANCE;
        }
        MeasuringConnectionManager connManager = new MeasuringConnectionManager(createSchemeRegistry(),
                resolver, TIME_TO_LIVE, VALIDITY_AFTER_INACTIVITY_TIMEOUT);

        // Modern browsers use more connections per host than the current httpclient default (2)
        // when using parallel download the httpclient and connection manager are shared by the downloads threads
        // to be realistic JMeter must set an higher value to DefaultMaxPerRoute
        if (this.testElement.isConcurrentDwn()) {
            try {
                int maxConcurrentDownloads = Integer.parseInt(this.testElement.getConcurrentPool());
                connManager.setDefaultMaxPerRoute(
                        Math.max(maxConcurrentDownloads, connManager.getDefaultMaxPerRoute()));
            } catch (NumberFormatException nfe) {
                // no need to log -> will be done by the sampler
            }
        }

        httpClient = new DefaultHttpClient(connManager, clientParams) {
            @Override
            protected HttpRequestRetryHandler createHttpRequestRetryHandler() {
                return new DefaultHttpRequestRetryHandler(RETRY_COUNT, false); // set retry count
            }
        };

        if (IDLE_TIMEOUT > 0) {
            ((AbstractHttpClient) httpClient).setKeepAliveStrategy(IDLE_STRATEGY);
        }
        // see https://issues.apache.org/jira/browse/HTTPCORE-397
        ((AbstractHttpClient) httpClient).setReuseStrategy(DefaultClientConnectionReuseStrategy.INSTANCE);
        ((AbstractHttpClient) httpClient).addResponseInterceptor(RESPONSE_CONTENT_ENCODING);
        ((AbstractHttpClient) httpClient).addResponseInterceptor(METRICS_SAVER); // HACK
        ((AbstractHttpClient) httpClient).addRequestInterceptor(METRICS_RESETTER);

        // Override the default schemes as necessary
        SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();

        if (SLOW_HTTP != null) {
            schemeRegistry.register(SLOW_HTTP);
        }

        // Set up proxy details
        if (useProxy) {

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (proxyUser.length() > 0) {
                ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(
                        new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(proxyUser, proxyPass, localHost, PROXY_DOMAIN));
            }
        }

        // Bug 52126 - we do our own cookie handling
        clientParams.setParameter(ClientPNames.COOKIE_POLICY, CookieSpecs.IGNORE_COOKIES);

        if (log.isDebugEnabled()) {
            log.debug("Created new HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString());
        }

        mapHttpClientPerHttpClientKey.put(key, httpClient); // save the agent for next time round
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Reusing the HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString());
        }
    }

    if (this.testElement.isConcurrentDwn()) {
        JMeterContextService.getContext().getSamplerContext().put(HTTPCLIENT_TOKEN, httpClient);
    }

    // TODO - should this be done when the client is created?
    // If so, then the details need to be added as part of HttpClientKey
    setConnectionAuthorization(httpClient, url, getAuthManager(), key);

    return httpClient;
}

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

/**
 * Process a new connection over an existing TCP connection or new
 * //from  w ww . jav a2 s . c om
 * @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.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  w w  w. j  a  v a 2s  .  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/*w ww .  j a v a 2 s  . co m*/
 * @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);
    }/*from ww w .j  a  v a 2 s . co  m*/

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

From source file:org.siddhiesb.transport.passthru.SourceHandler.java

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

        org.siddhiesb.transport.passthru.ProtocolState state = org.siddhiesb.transport.passthru.SourceContext
                .getState(conn);//from   ww  w .  ja  v a  2 s.c  o m
        if (state == org.siddhiesb.transport.passthru.ProtocolState.REQUEST_BODY
                || state == org.siddhiesb.transport.passthru.ProtocolState.REQUEST_HEAD) {
            informReaderError(conn);
        } else if (state == org.siddhiesb.transport.passthru.ProtocolState.RESPONSE_BODY
                || state == org.siddhiesb.transport.passthru.ProtocolState.RESPONSE_HEAD) {
            informWriterError(conn);
        } else if (state == org.siddhiesb.transport.passthru.ProtocolState.REQUEST_DONE) {
            informWriterError(conn);
        } else if (state == org.siddhiesb.transport.passthru.ProtocolState.RESPONSE_DONE) {
            informWriterError(conn);
        }

        org.siddhiesb.transport.passthru.SourceContext.updateState(conn,
                org.siddhiesb.transport.passthru.ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn);
    } else if (ex instanceof HttpException) {
        try {
            if (conn.isResponseSubmitted()) {
                sourceConfiguration.getSourceConnections().shutDownConnection(conn);
                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);
            org.siddhiesb.transport.passthru.SourceContext.updateState(conn,
                    org.siddhiesb.transport.passthru.ProtocolState.CLOSED);
            conn.close();
        } catch (Exception ex1) {
            log.error(ex.getMessage(), ex);
            org.siddhiesb.transport.passthru.SourceContext.updateState(conn,
                    org.siddhiesb.transport.passthru.ProtocolState.CLOSED);
            sourceConfiguration.getSourceConnections().shutDownConnection(conn);
        }
    } else {
        log.error("Unexoected error: " + ex.getMessage(), ex);
        org.siddhiesb.transport.passthru.SourceContext.updateState(conn,
                org.siddhiesb.transport.passthru.ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn);
    }
}