Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2011-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   *
   * Licensed under the Apache License, Version 2.0 (the "License").
   * You may not use this file except in compliance with the License.
   * A copy of the License is located at
   *
   *  http://aws.amazon.com/apache2.0
   *
  * or in the "license" file accompanying this file. This file is distributed
  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  * express or implied. See the License for the specific language governing
  * permissions and limitations under the License.
  */
 package com.amazonaws.http;
 
 import static com.amazonaws.SDKGlobalConfiguration.DISABLE_CERT_CHECKING_SYSTEM_PROPERTY;
 
 
 
 
Responsible for creating and configuring instances of Apache HttpClient4.
 
 class HttpClientFactory {


    
Creates a new HttpClient object using the specified AWS ClientConfiguration to configure the client.

Parameters:
config Client configuration options (ex: proxy settings, connection limits, etc).
Returns:
The new, configured HttpClient.
 
     public HttpClient createHttpClient(ClientConfiguration config) {
         /* Set HTTP client parameters */
         HttpParams httpClientParams = new BasicHttpParams();
         HttpConnectionParams.setConnectionTimeout(httpClientParamsconfig.getConnectionTimeout());
         HttpConnectionParams.setSoTimeout(httpClientParamsconfig.getSocketTimeout());
         HttpConnectionParams.setStaleCheckingEnabled(httpClientParamstrue);
         HttpConnectionParams.setTcpNoDelay(httpClientParamstrue);
         HttpConnectionParams.setSoKeepalive(httpClientParamsconfig.useTcpKeepAlive());
 
         int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
         int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
         if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
            HttpConnectionParams.setSocketBufferSize(httpClientParams,
                    Math.max(socketSendBufferSizeHintsocketReceiveBufferSizeHint));
        }
        PoolingClientConnectionManager connectionManager = ConnectionManagerFactory
                .createPoolingClientConnManager(confighttpClientParams);
        SdkHttpClient httpClient = new SdkHttpClient(connectionManagerhttpClientParams);
        httpClient.setRedirectStrategy(new NeverFollowRedirectStrategy());
        if (config.getLocalAddress() != null) {
            ConnRouteParams.setLocalAddress(httpClientParamsconfig.getLocalAddress());
        }
        try {
            Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
            SSLSocketFactory sf = config.getApacheHttpClientConfig().getSslSocketFactory();
            if (sf == null) {
                sf = new SdkTLSSocketFactory(
                        SSLContext.getDefault(),
                        .);
            }
            Scheme https = new Scheme("https", 443, sf);
            SchemeRegistry sr = connectionManager.getSchemeRegistry();
            sr.register(http);
            sr.register(https);
        } catch (NoSuchAlgorithmException e) {
            throw new AmazonClientException("Unable to access default SSL context"e);
        }
        /*
         * If SSL cert checking for endpoints has been explicitly disabled,
         * register a new scheme for HTTPS that won't cause self-signed certs to
         * error out.
         */
        if (System.getProperty() != null) {
            Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
        }
        /* Set proxy if configured */
        String proxyHost = config.getProxyHost();
        int proxyPort = config.getProxyPort();
        if (proxyHost != null && proxyPort > 0) {
            ..info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
            HttpHost proxyHttpHost = new HttpHost(proxyHostproxyPort);
            httpClient.getParams().setParameter(.proxyHttpHost);
            String proxyUsername    = config.getProxyUsername();
            String proxyPassword    = config.getProxyPassword();
            String proxyDomain      = config.getProxyDomain();
            String proxyWorkstation = config.getProxyWorkstation();
            if (proxyUsername != null && proxyPassword != null) {
                httpClient.getCredentialsProvider().setCredentials(
                        new AuthScope(proxyHostproxyPort),
                        new NTCredentials(proxyUsernameproxyPasswordproxyWorkstationproxyDomain));
            }
            // Add a request interceptor that sets up proxy authentication pre-emptively if configured
            if (config.isPreemptiveBasicProxyAuth()){
                httpClient.addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0);
            }
        }
        /* Accept Gzip response if configured */
        if (config.useGzip()) {
            httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
                public void process(final HttpRequest request,
                        final HttpContext contextthrows HttpException,
                        IOException {
                    if (!request.containsHeader("Accept-Encoding")) {
                        request.addHeader("Accept-Encoding""gzip");
                    }
                }
            });
            httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
                public void process(final HttpResponse response,
                        final HttpContext contextthrows HttpException,
                        IOException {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        Header ceheader = entity.getContentEncoding();
                        if (ceheader != null) {
                            HeaderElement[] codecs = ceheader.getElements();
                            for (int i = 0; i < codecs.lengthi++) {
                                if (codecs[i].getName()
                                        .equalsIgnoreCase("gzip")) {
                                    response.setEntity(new GzipDecompressingEntity(
                                            response.getEntity()));
                                    return;
                                }
                            }
                        }
                    }
                }
            });
        }
        return httpClient;
    }


    
Disable http redirect inside Apache HttpClient.
    private static final class NeverFollowRedirectStrategy implements RedirectStrategy {
        @Override
        public boolean isRedirected(HttpRequest requestHttpResponse response,
                HttpContext contextthrows ProtocolException {
            return false;
        }
        @Override
        public HttpUriRequest getRedirect(HttpRequest request,
                HttpResponse responseHttpContext context)
                throws ProtocolException {
            return null;
        }
    }

    
Simple implementation of SchemeSocketFactory (and LayeredSchemeSocketFactory) that bypasses SSL certificate checks. This class is only intended to be used for testing purposes.
    private static class TrustingSocketFactory implements SchemeSocketFactorySchemeLayeredSocketFactory {
        private SSLContext sslcontext = null;
        private static SSLContext createSSLContext() throws IOException {
            try {
                SSLContext context = SSLContext.getInstance("TLS");
                context.init(nullnew TrustManager[] { new TrustingX509TrustManager() }, null);
                return context;
            } catch (Exception e) {
                throw new IOException(e.getMessage(), e);
            }
        }
        private SSLContext getSSLContext() throws IOException {
            if (this. == nullthis. = createSSLContext();
            return this.;
        }
        public Socket createSocket(HttpParams paramsthrows IOException {
            return getSSLContext().getSocketFactory().createSocket();
        }
        public Socket connectSocket(Socket sock,
                InetSocketAddress remoteAddress,
                InetSocketAddress localAddressHttpParams params)
                throws IOExceptionUnknownHostException,
                ConnectTimeoutException {
            int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
            int soTimeout = HttpConnectionParams.getSoTimeout(params);
            SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket(params));
            if (localAddress != nullsslsock.bind(localAddress);
            sslsock.connect(remoteAddressconnTimeout);
            sslsock.setSoTimeout(soTimeout);
            return sslsock;
        }
        public boolean isSecure(Socket sockthrows IllegalArgumentException {
            return true;
        }
        public Socket createLayeredSocket(Socket arg0String arg1int arg2HttpParams arg3)
                throws IOExceptionUnknownHostException {
            return getSSLContext().getSocketFactory().createSocket(arg0arg1arg2true);
        }
    }

    
Simple implementation of X509TrustManager that trusts all certificates. This class is only intended to be used for testing purposes.
    private static class TrustingX509TrustManager implements X509TrustManager {
        private static final X509Certificate[] X509_CERTIFICATES = new X509Certificate[0];
        public X509Certificate[] getAcceptedIssuers() {
            return ;
        }
        public void checkServerTrusted(X509Certificate[] chainString authType)
                throws CertificateException {
            // No-op, to trust all certs
        }
        public void checkClientTrusted(X509Certificate[] chainString authType)
                throws CertificateException {
            // No-op, to trust all certs
        }
    };

    
HttpRequestInterceptor implementation to set up pre-emptive authentication against a defined basic proxy server.
    private static class PreemptiveProxyAuth implements HttpRequestInterceptor {
        private final HttpHost proxyHost;
        public PreemptiveProxyAuth(HttpHost proxyHost) {
            this. = proxyHost;
        }
        public void process(HttpRequest requestHttpContext context) {
            AuthCache authCache;
            // Set up the a Basic Auth scheme scoped for the proxy - we don't
            // want to do this for non-proxy authentication.
            BasicScheme basicScheme = new BasicScheme(.);
            if (context.getAttribute(.) == null) {
                authCache = new BasicAuthCache();
                authCache.put(this.basicScheme);
                context.setAttribute(.authCache);
            } else {
                authCache =
                    (AuthCachecontext.getAttribute(.);
                authCache.put(this.basicScheme);
            }
        }
    }
New to GrepCode? Check out our FAQ X