Example usage for org.apache.http.protocol HttpContext setAttribute

List of usage examples for org.apache.http.protocol HttpContext setAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol HttpContext setAttribute.

Prototype

void setAttribute(String str, Object obj);

Source Link

Usage

From source file:com.doculibre.constellio.opensearch.OpenSearchSolrServer.java

public static Element sendGet(String openSearchServerURLStr, Map<String, String> paramsMap) {
    if (paramsMap == null) {
        paramsMap = new HashMap<String, String>();
    }//from w ww. jav  a 2 s. c  o m

    try {
        HttpParams params = new BasicHttpParams();
        for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
            String paramName = (String) it.next();
            String paramValue = (String) paramsMap.get(paramName);
            params.setParameter(paramName, paramValue);
        }

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, CharSetUtils.UTF_8);
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);
        URL openSearchServerURL = new URL(openSearchServerURLStr);
        String host = openSearchServerURL.getHost();
        int port = openSearchServerURL.getPort();
        if (port == -1) {
            port = 80;
        }
        HttpHost httpHost = new HttpHost(host, port);

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost);

        try {
            boolean firstParam = true;
            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                String paramName = (String) it.next();
                String paramValue = (String) paramsMap.get(paramName);
                if (paramValue != null) {
                    try {
                        paramValue = URLEncoder.encode(paramValue, CharSetUtils.ISO_8859_1);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }

                if (firstParam) {
                    openSearchServerURLStr += "?";
                    firstParam = false;
                } else {
                    openSearchServerURLStr += "&";
                }
                openSearchServerURLStr += paramName + "=" + paramValue;
            }

            if (!conn.isOpen()) {
                Socket socket = new Socket(host, port);
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET",
                    openSearchServerURLStr);
            LOGGER.fine(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.fine("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.fine(entityText);
            LOGGER.fine("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.fine("Connection kept alive...");
            }

            try {
                Document xml = DocumentHelper.parseText(entityText);
                return xml.getRootElement();
            } catch (RuntimeException e) {
                LOGGER.severe("Error caused by text : " + entityText);
                throw e;
            }
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.baidu.qa.service.test.client.SoapReqImpl.java

private static String sendSoap(String hosturl, String ip, int port, String action, String method, String xml,
        boolean isHttps) throws Exception {
    if (isHttps) {
        return sendSoapViaHttps(hosturl, ip, port, action, method, xml);
    }//from  w  w w .  j a v  a2s .c o  m

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");// must be UTF-8
    HttpProtocolParams.setUserAgent(params, "itest-by-HttpCore/4.2");

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    // log.info("ip:port - " + ip + ":" + port );
    HttpHost host = new HttpHost(ip, port);// TODO

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    conn.setSocketTimeout(10000);
    HttpConnectionParams.setSoTimeout(params, 10000);
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    String res = null;

    try {
        // HttpEntity requestBody = new
        // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO
        byte[] b = xml.getBytes("UTF-8"); // must be UTF-8
        InputStream is = new ByteArrayInputStream(b, 0, b.length);

        HttpEntity requestBody = new InputStreamEntity(is, b.length,
                ContentType.create("text/xml;charset=UTF-8"));// must be
        // UTF-8

        // .create("application/xop+xml; charset=UTF-8; type=\"text/xml\""));//
        // TODO

        // RequestEntity re = new InputStreamRequestEntity(is, b.length,
        // "application/xop+xml; charset=UTF-8; type=\"text/xml\"");
        // postmethod.setRequestEntity(re);

        if (!conn.isOpen()) {
            Socket socket = new Socket(host.getHostName(), host.getPort());
            conn.bind(socket, params);
        }
        BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", action);

        // add the 3 headers below
        request.addHeader("Accept-Encoding", "gzip,deflate");
        request.addHeader("SOAPAction", hosturl + action + method);// SOAP action
        request.addHeader("uuid", "itest");// for editor token of DR-Api

        request.setEntity(requestBody);
        log.info(">> Request URI: " + request.getRequestLine().getUri());

        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);

        log.info("<< Response: " + response.getStatusLine());

        String contentEncoding = null;
        Header ce = response.getEntity().getContentEncoding();
        if (ce != null) {
            contentEncoding = ce.getValue();
        }

        if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
            GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent());
            Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            while (in.hasNextLine()) {
                sb.append(in.nextLine()).append(System.getProperty("line.separator"));
            }
            res = sb.toString();
        } else {
            res = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        log.info(res);

        log.info("==============");
        if (!connStrategy.keepAlive(response, context)) {
            conn.close();
        } else {
            log.info("Connection kept alive...");
        }
    } finally {
        try {
            conn.close();
        } catch (IOException e) {
        }
    }
    return res;
}

From source file:net.yacy.cora.federate.solr.instance.RemoteInstance.java

/**
 * @param solraccount eventual user name used to authenticate on the target Solr
 * @param solraccount eventual password used to authenticate on the target Solr
 * @param trustSelfSignedCertificates when true, https connections to an host providing a self-signed certificate are accepted
* @param maxBytesPerReponse//  w  w  w .  j  a v a  2 s  . c  o m
*            maximum acceptable decompressed size in bytes for a response from
*            the remote Solr server. Negative value or Long.MAX_VALUE means no
*            limit.
 * @return a new apache HttpClient instance usable as a custom http client by SolrJ
 */
private static HttpClient buildCustomHttpClient(final int timeout, final MultiProtocolURL u,
        final String solraccount, final String solrpw, final String host,
        final boolean trustSelfSignedCertificates, final long maxBytesPerResponse) {

    /* Important note : use of deprecated Apache classes is required because SolrJ still use them internally (see HttpClientUtil). 
     * Upgrade only when Solr implementation will become compatible */

    org.apache.http.impl.client.DefaultHttpClient result = new org.apache.http.impl.client.DefaultHttpClient(
            CONNECTION_MANAGER) {
        @Override
        protected HttpContext createHttpContext() {
            HttpContext context = super.createHttpContext();
            AuthCache authCache = new org.apache.http.impl.client.BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            HttpHost targetHost = new HttpHost(u.getHost(), u.getPort(), u.getProtocol());
            authCache.put(targetHost, basicAuth);
            context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
            if (trustSelfSignedCertificates && SCHEME_REGISTRY != null) {
                context.setAttribute(ClientContext.SCHEME_REGISTRY, SCHEME_REGISTRY);
            }
            this.setHttpRequestRetryHandler(
                    new org.apache.http.impl.client.DefaultHttpRequestRetryHandler(0, false)); // no retries needed; we expect connections to fail; therefore we should not retry
            return context;
        }
    };
    org.apache.http.params.HttpParams params = result.getParams();
    /* Set the maximum time to establish a connection to the remote server */
    org.apache.http.params.HttpConnectionParams.setConnectionTimeout(params, timeout);
    /* Set the maximum time between data packets reception one a connection has been established */
    org.apache.http.params.HttpConnectionParams.setSoTimeout(params, timeout);
    /* Set the maximum time to get a connection from the shared connections pool */
    HttpClientParams.setConnectionManagerTimeout(params, timeout);
    result.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context) throws IOException {
            if (!request.containsHeader(HeaderFramework.ACCEPT_ENCODING))
                request.addHeader(HeaderFramework.ACCEPT_ENCODING, HeaderFramework.CONTENT_ENCODING_GZIP);
            if (!request.containsHeader(HTTP.CONN_DIRECTIVE))
                request.addHeader(HTTP.CONN_DIRECTIVE, "close"); // prevent CLOSE_WAIT
        }

    });
    result.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(final HttpResponse response, final HttpContext context) throws IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (HeaderElement codec : codecs) {
                        if (codec.getName().equalsIgnoreCase(HeaderFramework.CONTENT_ENCODING_GZIP)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
    });
    if (solraccount != null && !solraccount.isEmpty()) {
        org.apache.http.impl.client.BasicCredentialsProvider credsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(solraccount, solrpw));
        result.setCredentialsProvider(credsProvider);
    }

    if (maxBytesPerResponse >= 0 && maxBytesPerResponse < Long.MAX_VALUE) {
        /*
         * Add in last position the eventual interceptor limiting the response size, so
         * that this is the decompressed amount of bytes that is considered
         */
        result.addResponseInterceptor(new StrictSizeLimitResponseInterceptor(maxBytesPerResponse),
                result.getResponseInterceptorCount());
    }

    return result;
}

From source file:com.msopentech.thali.utilities.universal.ThaliClientToDeviceHubUtilities.java

/**
 * This is a horrible hack used by clients to get the server key for the local Thali Device Hub. Eventually we'll
 * introduce something actually reasonably secure for this purposes.
 * @param  httpClient/*from  w  ww .ja  v a2 s  . c o  m*/
 * @return
 * @throws java.io.IOException
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws KeyManagementException
 */
public static PublicKey getServersRootPublicKey(org.apache.http.client.HttpClient httpClient)
        throws IOException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException {
    // Taken from http://stackoverflow.com/questions/13273305/apache-httpclient-get-server-certificate
    // And yes we should do this with a request interceptor since it would work in all cases where we get a SSL
    // connection even if the HTTP request fails and I'm too lazy to rewrite it.
    ((AbstractHttpClient) httpClient).addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(org.apache.http.HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            Object unTypedHttpConnection = context.getAttribute(ExecutionContext.HTTP_CONNECTION);

            // Android doesn't return an object that supports the HttpRoutedConnection interface which makes no sense!
            // What it does return is BasicPooledConnAdapter but that is supposed to support HttpRoutedConnection! But doesn't.
            if (unTypedHttpConnection instanceof BasicPooledConnAdapter) {
                BasicPooledConnAdapter basicPooledConnAdapter = (BasicPooledConnAdapter) unTypedHttpConnection;
                if (basicPooledConnAdapter.isSecure()) {
                    java.security.cert.Certificate[] certificates = basicPooledConnAdapter.getSSLSession()
                            .getPeerCertificates();
                    context.setAttribute(PEER_CERT_ATTRIBUTE, certificates);
                }
                return;
            }

            if (unTypedHttpConnection instanceof HttpRoutedConnection) {
                HttpRoutedConnection httpRoutedConnection = (HttpRoutedConnection) unTypedHttpConnection;
                if (httpRoutedConnection.isSecure()) {
                    java.security.cert.Certificate[] certificates = httpRoutedConnection.getSSLSession()
                            .getPeerCertificates();
                    context.setAttribute(PEER_CERT_ATTRIBUTE, certificates);
                }
                return;
            }

            throw new RuntimeException("Unexpected HTTP_CONNECTION: " + unTypedHttpConnection.toString());
        }
    });
    HttpContext httpContext = new BasicHttpContext();
    HttpUriRequest httpUriRequest = new HttpGet("/");
    org.apache.http.HttpResponse apacheHttpResponse = httpClient.execute(httpUriRequest, httpContext);
    java.security.cert.Certificate[] certificates = (java.security.cert.Certificate[]) httpContext
            .getAttribute(PEER_CERT_ATTRIBUTE);
    // TODO: Where is it written that the last cert is the server's root cert? Are certs guaranteed to be returned in order from leaf to root?
    return certificates[certificates.length - 1].getPublicKey();
}

From source file:com.strato.hidrive.api.HttpClientManager.java

public HttpContext getLocalHttpContext() {
    if (localHttpContext == null) {
        CookieStore cookieStore = new BasicCookieStore();
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    }/*from  ww w. ja  v  a  2  s  .  c o m*/
    return localHttpContext;
}

From source file:org.sonatype.nexus.internal.httpclient.RepositoryPageContext.java

/**
 * Equips context with repository.//from w w  w  . j a  va2 s  .  co  m
 */
@Override
public HttpContext createHttpContext(final HttpUriRequest httpRequest) throws IOException {
    final HttpContext httpContext = super.createHttpContext(httpRequest);
    httpContext.setAttribute(HttpClientFactory.HTTP_CTX_KEY_REPOSITORY, getProxyRepository());
    return httpContext;
}

From source file:com.google.cloud.trace.apachehttp.TraceResponseInterceptorTest.java

@Test
public void testProcess_WithContext() throws IOException, HttpException {
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute("TRACE-CONTEXT", testContext);
    responseInterceptor.process(response, httpContext);

    ArgumentCaptor<HttpResponse> responseCaptor = ArgumentCaptor.forClass(HttpResponse.class);
    ArgumentCaptor<TraceContext> contextCaptor = ArgumentCaptor.forClass(TraceContext.class);
    verify(mockDelegate).process(responseCaptor.capture(), contextCaptor.capture());

    HttpResponse response = responseCaptor.getValue();
    TraceContext traceContext = contextCaptor.getValue();
    assertThat(traceContext).isEqualTo(testContext);
    assertThat(response.getHeader("Content-Length")).isEqualTo("123");
    assertThat(response.getStatus()).isEqualTo(200);
}

From source file:com.alibaba.openapi.client.rpc.AliNHttpRequstExecutionHandler.java

public void initalizeContext(HttpContext context, Object attachment) {
    context.setAttribute(CONTEXT_ATTACHMENT, attachment);
}

From source file:com.subgraph.vega.internal.http.requests.RequestCopyHeadersInterceptor.java

@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    final HttpRequest copy = copyRequest(request);
    context.setAttribute(HttpRequestEngine.VEGA_SENT_REQUEST, copy);
}

From source file:org.wso2.appserver.integration.tests.webapp.spring.SpringScopeTestCase.java

@Test(groups = "wso2.as", description = "Verfiy Spring Request scope")
public void testSpringRequestScope() throws Exception {

    String endpoint = webAppURL + "/" + webAppMode.getWebAppName() + "/scope/request";
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    HttpGet httpget = new HttpGet(endpoint);
    HttpResponse response1 = httpClient.execute(httpget, httpContext);
    String responseMsg1 = new BasicResponseHandler().handleResponse(response1);
    HttpResponse response2 = httpClient.execute(httpget, httpContext);
    String responseMsg2 = new BasicResponseHandler().handleResponse(response2);
    httpClient.close();/*ww w.  j a  v  a2 s  . c o m*/

    assertTrue(!responseMsg1.equalsIgnoreCase(responseMsg2), "Failed: Responses should not be the same");
}