Example usage for org.apache.http.impl.client HttpClientBuilder build

List of usage examples for org.apache.http.impl.client HttpClientBuilder build

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder build.

Prototype

public CloseableHttpClient build() 

Source Link

Usage

From source file:run.var.teamcity.cloud.docker.client.apcon.ApacheConnector.java

/**
 * Create the new Apache HTTP Client connector.
 *
 * @param client JAX-RS client instance for which the connector is being created.
 * @param config client configuration.//ww  w  .j av  a 2s  . c om
 */
ApacheConnector(final Client client, final Configuration config) {
    final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER);
    if (connectionManager != null) {
        if (!(connectionManager instanceof HttpClientConnectionManager)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.CONNECTION_MANAGER,
                            connectionManager.getClass().getName(),
                            HttpClientConnectionManager.class.getName()));
        }
    }

    Object reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG);
    if (reqConfig != null) {
        if (!(reqConfig instanceof RequestConfig)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.REQUEST_CONFIG,
                            reqConfig.getClass().getName(), RequestConfig.class.getName()));
            reqConfig = null;
        }
    }

    final SSLContext sslContext = client.getSslContext();
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    clientBuilder.setConnectionManager(getConnectionManager(client, config, sslContext));
    clientBuilder.setConnectionManagerShared(PropertiesHelper.getValue(config.getProperties(),
            ApacheClientProperties.CONNECTION_MANAGER_SHARED, false, null));
    clientBuilder.setSslcontext(sslContext);

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER);
    if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) {
        clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider);
    }

    final Object proxyUri;
    proxyUri = config.getProperty(ClientProperties.PROXY_URI);
    if (proxyUri != null) {
        final URI u = getProxyUri(proxyUri);
        final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme());
        final String userName;
        userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME,
                String.class);
        if (userName != null) {
            final String password;
            password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD,
                    String.class);

            if (password != null) {
                final CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(u.getHost(), u.getPort()),
                        new UsernamePasswordCredentials(userName, password));
                clientBuilder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        clientBuilder.setProxy(proxy);
    }

    final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties()
            .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION);
    this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false;

    final boolean ignoreCookies = PropertiesHelper.isProperty(config.getProperties(),
            ApacheClientProperties.DISABLE_COOKIES);

    if (reqConfig != null) {
        final RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig);
        if (ignoreCookies) {
            reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = reqConfigBuilder.build();
    } else {
        if (ignoreCookies) {
            requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = requestConfigBuilder.build();
    }

    if (requestConfig.getCookieSpec() == null
            || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) {
        this.cookieStore = new BasicCookieStore();
        clientBuilder.setDefaultCookieStore(cookieStore);
    } else {
        this.cookieStore = null;
    }
    clientBuilder.setDefaultRequestConfig(requestConfig);

    /* DK_CLD: Add our connection reuse strategy. */
    clientBuilder.setConnectionReuseStrategy(new UpgradeAwareConnectionReuseStrategy());
    clientBuilder.setRequestExecutor(new HttpRequestExecutor() {
        protected HttpResponse doReceiveResponse(final HttpRequest request,
                final org.apache.http.HttpClientConnection conn, final HttpContext context)
                throws HttpException, IOException {
            Args.notNull(request, "HTTP request");
            Args.notNull(conn, "Client connection");
            Args.notNull(context, "HTTP context");
            HttpResponse response = null;
            int statusCode = 0;

            while (response == null || (statusCode < HttpStatus.SC_OK
                    // DK_CLD: the original implementation provided this loop to retry the HTTP request as long as
                    // an intermediate response is returned (1xx status). This is however not suitable for the
                    // status code 101 returned from Docker (and more generally, WebSockets) to notify that the
                    // connection has been upgraded to raw TCP streaming. In such case the server ultimate response
                    // is not HTTP anymore.
                    && statusCode != HttpStatus.SC_SWITCHING_PROTOCOLS)) {

                response = conn.receiveResponseHeader();
                if (canResponseHaveBody(request, response)) {
                    conn.receiveResponseEntity(response);
                }
                statusCode = response.getStatusLine().getStatusCode();

            } // while intermediate response

            return response;
        }

        @Override
        protected boolean canResponseHaveBody(HttpRequest request, HttpResponse response) {
            boolean canResponseHaveBody = super.canResponseHaveBody(request, response);
            return canResponseHaveBody
                    || response.getStatusLine().getStatusCode() == HttpStatus.SC_SWITCHING_PROTOCOLS;
        }
    });

    this.client = clientBuilder.build();
}

From source file:org.apache.ambari.view.hive.client.Connection.java

private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException {
    boolean isCookieEnabled = authParams.get(Utils.HiveAuthenticationParams.COOKIE_AUTH) == null
            || (!Utils.HiveAuthenticationParams.COOKIE_AUTH_FALSE
                    .equalsIgnoreCase(authParams.get(Utils.HiveAuthenticationParams.COOKIE_AUTH)));
    String cookieName = authParams.get(Utils.HiveAuthenticationParams.COOKIE_NAME) == null
            ? Utils.HiveAuthenticationParams.DEFAULT_COOKIE_NAMES_HS2
            : authParams.get(Utils.HiveAuthenticationParams.COOKIE_NAME);
    CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null;
    HttpClientBuilder httpClientBuilder;
    // Request interceptor for any request pre-processing logic
    HttpRequestInterceptor requestInterceptor;
    Map<String, String> additionalHttpHeaders = new HashMap<String, String>();

    // Retrieve the additional HttpHeaders
    for (Map.Entry<String, String> entry : authParams.entrySet()) {
        String key = entry.getKey();

        if (key.startsWith(Utils.HiveAuthenticationParams.HTTP_HEADER_PREFIX)) {
            additionalHttpHeaders.put(key.substring(Utils.HiveAuthenticationParams.HTTP_HEADER_PREFIX.length()),
                    entry.getValue());/*  ww w  . j  a v  a  2 s .co  m*/
        }
    }
    // Configure http client for kerberos/password based authentication
    if (isKerberosAuthMode()) {
        /**
         * Add an interceptor which sets the appropriate header in the request.
         * It does the kerberos authentication and get the final service ticket,
         * for sending to the server before every request.
         * In https mode, the entire information is encrypted
         */

        Boolean assumeSubject = Utils.HiveAuthenticationParams.AUTH_KERBEROS_AUTH_TYPE_FROM_SUBJECT
                .equals(authParams.get(Utils.HiveAuthenticationParams.AUTH_KERBEROS_AUTH_TYPE));
        requestInterceptor = new HttpKerberosRequestInterceptor(
                authParams.get(Utils.HiveAuthenticationParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl),
                assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders);
    } else {
        /**
         * Add an interceptor to pass username/password in the header.
         * In https mode, the entire information is encrypted
         */
        requestInterceptor = new HttpBasicAuthInterceptor(
                getAuthParamDefault(Utils.HiveAuthenticationParams.AUTH_USER, getUsername()), getPassword(),
                cookieStore, cookieName, useSsl, additionalHttpHeaders);
    }
    // Configure http client for cookie based authentication
    if (isCookieEnabled) {
        // Create a http client with a retry mechanism when the server returns a status code of 401.
        httpClientBuilder = HttpClients.custom()
                .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {

                    @Override
                    public boolean retryRequest(final HttpResponse response, final int executionCount,
                            final HttpContext context) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        boolean ret = statusCode == 401 && executionCount <= 1;

                        // Set the context attribute to true which will be interpreted by the request interceptor
                        if (ret) {
                            context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE);
                        }
                        return ret;
                    }

                    @Override
                    public long getRetryInterval() {
                        // Immediate retry
                        return 0;
                    }
                });
    } else {
        httpClientBuilder = HttpClientBuilder.create();
    }
    // Add the request interceptor to the client builder
    httpClientBuilder.addInterceptorFirst(requestInterceptor);
    // Configure http client for SSL
    if (useSsl) {
        String useTwoWaySSL = authParams.get(Utils.HiveAuthenticationParams.USE_TWO_WAY_SSL);
        String sslTrustStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE);
        String sslTrustStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore;
        SSLSocketFactory socketFactory;

        /**
         * The code within the try block throws:
         * 1. SSLInitializationException
         * 2. KeyStoreException
         * 3. IOException
         * 4. NoSuchAlgorithmException
         * 5. CertificateException
         * 6. KeyManagementException
         * 7. UnrecoverableKeyException
         * We don't want the client to retry on any of these, hence we catch all
         * and throw a SQLException.
         */
        try {
            if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(Utils.HiveAuthenticationParams.TRUE)) {
                socketFactory = getTwoWaySSLSocketFactory();
            } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) {
                // Create a default socket factory based on standard JSSE trust material
                socketFactory = SSLSocketFactory.getSocketFactory();
            } else {
                // Pick trust store config from the given path
                sslTrustStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_TYPE);
                try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) {
                    sslTrustStore.load(fis, sslTrustStorePassword.toCharArray());
                }
                socketFactory = new SSLSocketFactory(sslTrustStore);
            }
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", socketFactory).build();

            httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        } catch (Exception e) {
            String msg = "Could not create an https connection to " + getServerHttpUrl(useSsl) + ". "
                    + e.getMessage();
            throw new SQLException(msg, " 08S01", e);
        }
    }
    return httpClientBuilder.build();
}

From source file:org.apache.manifoldcf.crawler.connectors.livelink.LivelinkConnector.java

protected void getSession() throws ManifoldCFException, ServiceInterruption {
    getSessionParameters();//from  w  w w  .j  a  va  2s. c o  m
    if (hasConnected == false) {
        int socketTimeout = 900000;
        int connectionTimeout = 300000;

        // Set up connection manager
        connectionManager = new PoolingHttpClientConnectionManager();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        // Set up ingest ssl if indicated
        SSLConnectionSocketFactory myFactory = null;
        if (ingestKeystoreManager != null) {
            myFactory = new SSLConnectionSocketFactory(
                    new InterruptibleSocketFactory(ingestKeystoreManager.getSecureSocketFactory(),
                            connectionTimeout),
                    new BrowserCompatHostnameVerifier());
        }

        // Set up authentication to use
        if (ingestNtlmDomain != null) {
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(ingestNtlmUsername, ingestNtlmPassword, currentHost, ingestNtlmDomain));
        }

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setMaxConnTotal(1).disableAutomaticRetries()
                .setDefaultRequestConfig(RequestConfig.custom().setCircularRedirectsAllowed(true)
                        .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                        .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout)
                        .setConnectionRequestTimeout(socketTimeout).build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(credentialsProvider)
                .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy());

        if (myFactory != null)
            builder.setSSLSocketFactory(myFactory);

        httpClient = builder.build();

        // System.out.println("Connection server object = "+llServer.toString());

        // Establish the actual connection
        int sanityRetryCount = FAILURE_RETRY_COUNT;
        while (true) {
            GetSessionThread t = new GetSessionThread();
            try {
                t.start();
                t.finishUp();
                hasConnected = true;
                break;
            } catch (InterruptedException e) {
                t.interrupt();
                throw new ManifoldCFException("Interrupted: " + e.getMessage(), e,
                        ManifoldCFException.INTERRUPTED);
            } catch (RuntimeException e2) {
                sanityRetryCount = handleLivelinkRuntimeException(e2, sanityRetryCount, true);
            }
        }
    }
    expirationTime = System.currentTimeMillis() + expirationInterval;
}

From source file:crawlercommons.fetcher.http.SimpleHttpFetcher.java

private void init() {
    if (_httpClient == null) {
        synchronized (SimpleHttpFetcher.class) {
            if (_httpClient != null)
                return;

            final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

            // Set the socket and connection timeout to be something
            // reasonable.
            requestConfigBuilder.setSocketTimeout(_socketTimeout);
            requestConfigBuilder.setConnectTimeout(_connectionTimeout);
            requestConfigBuilder.setConnectionRequestTimeout(_connectionRequestTimeout);

            /*//  w  w w.  ja  v a  2  s.com
             * CoreConnectionPNames.TCP_NODELAY='http.tcp.nodelay':
             * determines whether Nagle's algorithm is to be used. Nagle's
             * algorithm tries to conserve bandwidth by minimizing the
             * number of segments that are sent. When applications wish to
             * decrease network latency and increase performance, they can
             * disable Nagle's algorithm (that is enable TCP_NODELAY. Data
             * will be sent earlier, at the cost of an increase in bandwidth
             * consumption. This parameter expects a value of type
             * java.lang.Boolean. If this parameter is not set, TCP_NODELAY
             * will be enabled (no delay).
             */
            // FIXME Could not find this parameter in http-client version
            // 4.5
            // HttpConnectionParams.setTcpNoDelay(params, true);
            // HttpProtocolParams.setVersion(params, _httpVersion);

            httpClientBuilder.setUserAgent(_userAgent.getUserAgentString());

            // HttpProtocolParams.setContentCharset(params, "UTF-8");
            // HttpProtocolParams.setHttpElementCharset(params, "UTF-8");

            /*
             * CoreProtocolPNames.USE_EXPECT_CONTINUE=
             * 'http.protocol.expect-continue': activates the Expect:
             * 100-Continue handshake for the entity enclosing methods. The
             * purpose of the Expect: 100-Continue handshake is to allow the
             * client that is sending a request message with a request body
             * to determine if the origin server is willing to accept the
             * request (based on the request headers) before the client
             * sends the request body. The use of the Expect: 100-continue
             * handshake can result in a noticeable performance improvement
             * for entity enclosing requests (such as POST and PUT) that
             * require the target server's authentication. The Expect:
             * 100-continue handshake should be used with caution, as it may
             * cause problems with HTTP servers and proxies that do not
             * support HTTP/1.1 protocol. This parameter expects a value of
             * type java.lang.Boolean. If this parameter is not set,
             * HttpClient will not attempt to use the handshake.
             */
            requestConfigBuilder.setExpectContinueEnabled(true);

            /*
             * CoreProtocolPNames.WAIT_FOR_CONTINUE=
             * 'http.protocol.wait-for-continue': defines the maximum period
             * of time in milliseconds the client should spend waiting for a
             * 100-continue response. This parameter expects a value of type
             * java.lang.Integer. If this parameter is not set HttpClient
             * will wait 3 seconds for a confirmation before resuming the
             * transmission of the request body.
             */
            // FIXME Could not find this parameter in http-client version
            // 4.5
            // params.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE,
            // 5000);

            // FIXME Could not find this parameter in http-client version
            // 4.5
            // CookieSpecParamBean cookieParams = new
            // CookieSpecParamBean(params);
            // cookieParams.setSingleHeader(false);

            // Create and initialize connection socket factory registry
            RegistryBuilder<ConnectionSocketFactory> registry = RegistryBuilder
                    .<ConnectionSocketFactory>create();
            registry.register("http", PlainConnectionSocketFactory.getSocketFactory());
            SSLConnectionSocketFactory sf = createSSLConnectionSocketFactory();
            if (sf != null) {
                registry.register("https", sf);
            } else {
                LOGGER.warn("No valid SSLContext found for https");
            }

            _connectionManager = new PoolingHttpClientConnectionManager(registry.build());
            _connectionManager.setMaxTotal(_maxThreads);
            _connectionManager.setDefaultMaxPerRoute(getMaxConnectionsPerHost());

            /*
             * CoreConnectionPNames.STALE_CONNECTION_CHECK=
             * 'http.connection.stalecheck': determines whether stale
             * connection check is to be used. Disabling stale connection
             * check may result in a noticeable performance improvement (the
             * check can cause up to 30 millisecond overhead per request) at
             * the risk of getting an I/O error when executing a request
             * over a connection that has been closed at the server side.
             * This parameter expects a value of type java.lang.Boolean. For
             * performance critical operations the check should be disabled.
             * If this parameter is not set, the stale connection check will
             * be performed before each request execution.
             * 
             * We don't need I/O exceptions in case if Server doesn't
             * support Kee-Alive option; our client by default always tries
             * keep-alive.
             */
            // Even with stale checking enabled, a connection can "go stale"
            // between the check and the next request. So we still need to
            // handle the case of a closed socket (from the server side),
            // and disabling this check improves performance.
            // Stale connections will be checked in a separate monitor
            // thread
            _connectionManager.setValidateAfterInactivity(-1);

            httpClientBuilder.setConnectionManager(_connectionManager);
            httpClientBuilder.setRetryHandler(new MyRequestRetryHandler(_maxRetryCount));
            httpClientBuilder.setRedirectStrategy(new MyRedirectStrategy(getRedirectMode()));
            httpClientBuilder.setRequestExecutor(new MyHttpRequestExecutor());

            // FUTURE KKr - support authentication
            // FIXME Could not find this parameter in http-client version
            // 4.5
            // HttpClientParams.setAuthenticating(params, false);

            requestConfigBuilder.setCookieSpec(CookieSpecs.DEFAULT);

            if (getMaxRedirects() == 0) {
                requestConfigBuilder.setRedirectsEnabled(false);
            } else {
                requestConfigBuilder.setRedirectsEnabled(true);
                requestConfigBuilder.setMaxRedirects(getMaxRedirects());
            }

            // Set up default headers. This helps us get back from servers
            // what we want.
            HashSet<Header> defaultHeaders = new HashSet<Header>();
            defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, getAcceptLanguage()));
            defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_CHARSET, DEFAULT_ACCEPT_CHARSET));
            defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, DEFAULT_ACCEPT_ENCODING));
            defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT, DEFAULT_ACCEPT));

            httpClientBuilder.setDefaultHeaders(defaultHeaders);

            httpClientBuilder.setKeepAliveStrategy(new MyConnectionKeepAliveStrategy());

            monitor = new IdleConnectionMonitorThread(_connectionManager);
            monitor.start();

            httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
            _httpClient = httpClientBuilder.build();
        }
    }

}

From source file:lucee.runtime.tag.Http41.java

private void _doEndTag(Struct cfhttp) throws PageException, IOException {
    HttpClientBuilder builder = HttpClients.custom();

    // redirect/*from   w  ww . j  av  a  2  s . c  o  m*/
    if (redirect)
        builder.setRedirectStrategy(new DefaultRedirectStrategy());
    else
        builder.disableRedirectHandling();

    // cookies
    BasicCookieStore cookieStore = new BasicCookieStore();
    builder.setDefaultCookieStore(cookieStore);

    ConfigWeb cw = pageContext.getConfig();
    HttpRequestBase req = null;
    HttpContext httpContext = null;
    //HttpRequestBase req = init(pageContext.getConfig(),this,client,params,url,port);
    {
        if (StringUtil.isEmpty(charset, true))
            charset = ((PageContextImpl) pageContext).getWebCharset().name();
        else
            charset = charset.trim();

        // check if has fileUploads   
        boolean doUploadFile = false;
        for (int i = 0; i < this.params.size(); i++) {
            if ((this.params.get(i)).getType().equalsIgnoreCase("file")) {
                doUploadFile = true;
                break;
            }
        }

        // parse url (also query string)
        int len = this.params.size();
        StringBuilder sbQS = new StringBuilder();
        for (int i = 0; i < len; i++) {
            HttpParamBean param = this.params.get(i);
            String type = param.getType();
            // URL
            if (type.equals("url")) {
                if (sbQS.length() > 0)
                    sbQS.append('&');
                sbQS.append(param.getEncoded() ? HttpImpl.urlenc(param.getName(), charset) : param.getName());
                sbQS.append('=');
                sbQS.append(param.getEncoded() ? HttpImpl.urlenc(param.getValueAsString(), charset)
                        : param.getValueAsString());
            }
        }
        String host = null;
        HttpHost httpHost;
        try {
            URL _url = HTTPUtil.toURL(url, port, encoded);
            httpHost = new HttpHost(_url.getHost(), _url.getPort());
            host = _url.getHost();
            url = _url.toExternalForm();
            if (sbQS.length() > 0) {
                // no existing QS
                if (StringUtil.isEmpty(_url.getQuery())) {
                    url += "?" + sbQS;
                } else {
                    url += "&" + sbQS;
                }
            }
        } catch (MalformedURLException mue) {
            throw Caster.toPageException(mue);
        }

        // select best matching method (get,post, post multpart (file))

        boolean isBinary = false;
        boolean doMultiPart = doUploadFile || this.multiPart;
        HttpPost post = null;
        HttpEntityEnclosingRequest eem = null;

        if (this.method == METHOD_GET) {
            req = new HttpGet(url);
        } else if (this.method == METHOD_HEAD) {
            req = new HttpHead(url);
        } else if (this.method == METHOD_DELETE) {
            isBinary = true;
            req = new HttpDelete(url);
        } else if (this.method == METHOD_PUT) {
            isBinary = true;
            HttpPut put = new HttpPut(url);
            req = put;
            eem = put;

        } else if (this.method == METHOD_TRACE) {
            isBinary = true;
            req = new HttpTrace(url);
        } else if (this.method == METHOD_OPTIONS) {
            isBinary = true;
            req = new HttpOptions(url);
        } else if (this.method == METHOD_PATCH) {
            isBinary = true;
            eem = HTTPPatchFactory.getHTTPPatch(url);
            req = (HttpRequestBase) eem;
        } else {
            isBinary = true;
            post = new HttpPost(url);
            req = post;
            eem = post;
        }

        boolean hasForm = false;
        boolean hasBody = false;
        boolean hasContentType = false;
        // Set http params
        ArrayList<FormBodyPart> parts = new ArrayList<FormBodyPart>();

        StringBuilder acceptEncoding = new StringBuilder();
        java.util.List<NameValuePair> postParam = post != null ? new ArrayList<NameValuePair>() : null;

        for (int i = 0; i < len; i++) {
            HttpParamBean param = this.params.get(i);
            String type = param.getType();

            // URL
            if (type.equals("url")) {
                //listQS.add(new BasicNameValuePair(translateEncoding(param.getName(), http.charset),translateEncoding(param.getValueAsString(), http.charset)));
            }
            // Form
            else if (type.equals("formfield") || type.equals("form")) {
                hasForm = true;
                if (this.method == METHOD_GET)
                    throw new ApplicationException(
                            "httpparam with type formfield can only be used when the method attribute of the parent http tag is set to post");
                if (post != null) {
                    if (doMultiPart) {
                        parts.add(new FormBodyPart(param.getName(),
                                new StringBody(param.getValueAsString(), CharsetUtil.toCharset(charset))));
                    } else {
                        postParam.add(new BasicNameValuePair(param.getName(), param.getValueAsString()));
                    }
                }
                //else if(multi!=null)multi.addParameter(param.getName(),param.getValueAsString());
            }
            // CGI
            else if (type.equals("cgi")) {
                if (param.getEncoded())
                    req.addHeader(HttpImpl.urlenc(param.getName(), charset),
                            HttpImpl.urlenc(param.getValueAsString(), charset));
                else
                    req.addHeader(param.getName(), param.getValueAsString());
            }
            // Header
            else if (type.startsWith("head")) {
                if (param.getName().equalsIgnoreCase("content-type"))
                    hasContentType = true;

                if (param.getName().equalsIgnoreCase("Content-Length")) {
                } else if (param.getName().equalsIgnoreCase("Accept-Encoding")) {
                    acceptEncoding.append(HttpImpl.headerValue(param.getValueAsString()));
                    acceptEncoding.append(", ");
                } else
                    req.addHeader(param.getName(), HttpImpl.headerValue(param.getValueAsString()));
            }
            // Cookie
            else if (type.equals("cookie")) {
                HTTPEngineImpl.addCookie(cookieStore, host, param.getName(), param.getValueAsString(), "/",
                        charset);
            }
            // File
            else if (type.equals("file")) {
                hasForm = true;
                if (this.method == METHOD_GET)
                    throw new ApplicationException(
                            "httpparam type file can't only be used, when method of the tag http equal post");
                String strCT = HttpImpl.getContentType(param);
                ContentType ct = HTTPUtil.toContentType(strCT, null);

                String mt = "text/xml";
                if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true))
                    mt = ct.getMimeType();

                String cs = charset;
                if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true))
                    cs = ct.getCharset();

                if (doMultiPart) {
                    try {
                        Resource res = param.getFile();
                        parts.add(new FormBodyPart(param.getName(),
                                new ResourceBody(res, mt, res.getName(), cs)));
                        //parts.add(new ResourcePart(param.getName(),new ResourcePartSource(param.getFile()),getContentType(param),_charset));
                    } catch (FileNotFoundException e) {
                        throw new ApplicationException("can't upload file, path is invalid", e.getMessage());
                    }
                }
            }
            // XML
            else if (type.equals("xml")) {
                ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null);

                String mt = "text/xml";
                if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true))
                    mt = ct.getMimeType();

                String cs = charset;
                if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true))
                    cs = ct.getCharset();

                hasBody = true;
                hasContentType = true;
                req.addHeader("Content-type", mt + "; charset=" + cs);
                if (eem == null)
                    throw new ApplicationException("type xml is only supported for type post and put");
                HTTPEngineImpl.setBody(eem, param.getValueAsString(), mt, cs);
            }
            // Body
            else if (type.equals("body")) {
                ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null);

                String mt = null;
                if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true))
                    mt = ct.getMimeType();

                String cs = charset;
                if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true))
                    cs = ct.getCharset();

                hasBody = true;
                if (eem == null)
                    throw new ApplicationException("type body is only supported for type post and put");
                HTTPEngineImpl.setBody(eem, param.getValue(), mt, cs);

            } else {
                throw new ApplicationException("invalid type [" + type + "]");
            }

        }

        // post params
        if (postParam != null && postParam.size() > 0)
            post.setEntity(new org.apache.http.client.entity.UrlEncodedFormEntity(postParam, charset));

        if (compression) {
            acceptEncoding.append("gzip");
        } else {
            acceptEncoding.append("deflate;q=0");
            req.setHeader("TE", "deflate;q=0");
        }
        req.setHeader("Accept-Encoding", acceptEncoding.toString());

        // multipart
        if (doMultiPart && eem != null) {
            hasContentType = true;
            boolean doIt = true;
            if (!this.multiPart && parts.size() == 1) {
                ContentBody body = parts.get(0).getBody();
                if (body instanceof StringBody) {
                    StringBody sb = (StringBody) body;
                    try {
                        org.apache.http.entity.ContentType ct = org.apache.http.entity.ContentType
                                .create(sb.getMimeType(), sb.getCharset());
                        String str = IOUtil.toString(sb.getReader());
                        StringEntity entity = new StringEntity(str, ct);
                        eem.setEntity(entity);

                    } catch (IOException e) {
                        throw Caster.toPageException(e);
                    }
                    doIt = false;
                }
            }
            if (doIt) {
                MultipartEntity mpe = new MultipartEntity(HttpMultipartMode.STRICT);
                Iterator<FormBodyPart> it = parts.iterator();
                while (it.hasNext()) {
                    FormBodyPart part = it.next();
                    mpe.addPart(part.getName(), part.getBody());
                }
                eem.setEntity(mpe);
            }
            //eem.setRequestEntity(new MultipartRequestEntityFlex(parts.toArray(new Part[parts.size()]), eem.getParams(),http.multiPartType));
        }

        if (hasBody && hasForm)
            throw new ApplicationException("mixing httpparam  type file/formfield and body/XML is not allowed");

        if (!hasContentType) {
            if (isBinary) {
                if (hasBody)
                    req.addHeader("Content-type", "application/octet-stream");
                else
                    req.addHeader("Content-type", "application/x-www-form-urlencoded; charset=" + charset);
            } else {
                if (hasBody)
                    req.addHeader("Content-type", "text/html; charset=" + charset);
            }
        }

        // set User Agent
        if (!HttpImpl.hasHeaderIgnoreCase(req, "User-Agent"))
            req.setHeader("User-Agent", this.useragent);

        // set timeout
        if (this.timeout > 0L) {
            builder.setConnectionTimeToLive(this.timeout, TimeUnit.MILLISECONDS);
        }

        // set Username and Password
        if (this.username != null) {
            if (this.password == null)
                this.password = "";
            if (AUTH_TYPE_NTLM == this.authType) {
                if (StringUtil.isEmpty(this.workStation, true))
                    throw new ApplicationException(
                            "attribute workstation is required when authentication type is [NTLM]");
                if (StringUtil.isEmpty(this.domain, true))
                    throw new ApplicationException(
                            "attribute domain is required when authentication type is [NTLM]");
                HTTPEngineImpl.setNTCredentials(builder, this.username, this.password, this.workStation,
                        this.domain);
            } else
                httpContext = HTTPEngineImpl.setCredentials(builder, httpHost, this.username, this.password,
                        preauth);
        }

        // set Proxy
        ProxyData proxy = null;
        if (!StringUtil.isEmpty(this.proxyserver)) {
            proxy = ProxyDataImpl.getInstance(this.proxyserver, this.proxyport, this.proxyuser,
                    this.proxypassword);
        }
        if (pageContext.getConfig().isProxyEnableFor(host)) {
            proxy = pageContext.getConfig().getProxyData();
        }
        HTTPEngineImpl.setProxy(builder, req, proxy);

    }

    CloseableHttpClient client = null;
    try {
        if (httpContext == null)
            httpContext = new BasicHttpContext();

        /////////////////////////////////////////// EXECUTE /////////////////////////////////////////////////
        client = builder.build();
        Executor41 e = new Executor41(this, client, httpContext, req, redirect);
        HTTPResponse4Impl rsp = null;
        if (timeout < 0) {
            try {
                rsp = e.execute(httpContext);
            }

            catch (Throwable t) {
                if (!throwonerror) {
                    setUnknownHost(cfhttp, t);
                    return;
                }
                throw toPageException(t);

            }
        } else {
            e.start();
            try {
                synchronized (this) {//print.err(timeout);
                    this.wait(timeout);
                }
            } catch (InterruptedException ie) {
                throw Caster.toPageException(ie);
            }
            if (e.t != null) {
                if (!throwonerror) {
                    setUnknownHost(cfhttp, e.t);
                    return;
                }
                throw toPageException(e.t);
            }

            rsp = e.response;

            if (!e.done) {
                req.abort();
                if (throwonerror)
                    throw new HTTPException("408 Request Time-out", "a timeout occurred in tag http", 408,
                            "Time-out", rsp.getURL());
                setRequestTimeout(cfhttp);
                return;
                //throw new ApplicationException("timeout");   
            }
        }

        /////////////////////////////////////////// EXECUTE /////////////////////////////////////////////////
        Charset responseCharset = CharsetUtil.toCharset(rsp.getCharset());
        // Write Response Scope
        //String rawHeader=httpMethod.getStatusLine().toString();
        String mimetype = null;
        String contentEncoding = null;

        // status code
        cfhttp.set(STATUSCODE, ((rsp.getStatusCode() + " " + rsp.getStatusText()).trim()));
        cfhttp.set(STATUS_CODE, new Double(rsp.getStatusCode()));
        cfhttp.set(STATUS_TEXT, (rsp.getStatusText()));
        cfhttp.set(HTTP_VERSION, (rsp.getProtocolVersion()));

        //responseHeader
        lucee.commons.net.http.Header[] headers = rsp.getAllHeaders();
        StringBuffer raw = new StringBuffer(rsp.getStatusLine() + " ");
        Struct responseHeader = new StructImpl();
        Struct cookie;
        Array setCookie = new ArrayImpl();
        Query cookies = new QueryImpl(
                new String[] { "name", "value", "path", "domain", "expires", "secure", "httpOnly" }, 0,
                "cookies");

        for (int i = 0; i < headers.length; i++) {
            lucee.commons.net.http.Header header = headers[i];
            //print.ln(header);

            raw.append(header.toString() + " ");
            if (header.getName().equalsIgnoreCase("Set-Cookie")) {
                setCookie.append(header.getValue());
                parseCookie(cookies, header.getValue());
            } else {
                //print.ln(header.getName()+"-"+header.getValue());
                Object value = responseHeader.get(KeyImpl.getInstance(header.getName()), null);
                if (value == null)
                    responseHeader.set(KeyImpl.getInstance(header.getName()), header.getValue());
                else {
                    Array arr = null;
                    if (value instanceof Array) {
                        arr = (Array) value;
                    } else {
                        arr = new ArrayImpl();
                        responseHeader.set(KeyImpl.getInstance(header.getName()), arr);
                        arr.appendEL(value);
                    }
                    arr.appendEL(header.getValue());
                }
            }

            // Content-Type
            if (header.getName().equalsIgnoreCase("Content-Type")) {
                mimetype = header.getValue();
                if (mimetype == null)
                    mimetype = NO_MIMETYPE;
            }

            // Content-Encoding
            if (header.getName().equalsIgnoreCase("Content-Encoding")) {
                contentEncoding = header.getValue();
            }

        }
        cfhttp.set(RESPONSEHEADER, responseHeader);
        cfhttp.set(KeyConstants._cookies, cookies);
        responseHeader.set(STATUS_CODE, new Double(rsp.getStatusCode()));
        responseHeader.set(EXPLANATION, (rsp.getStatusText()));
        if (setCookie.size() > 0)
            responseHeader.set(SET_COOKIE, setCookie);

        // is text 
        boolean isText = mimetype == null || mimetype == NO_MIMETYPE || HTTPUtil.isTextMimeType(mimetype);

        // is multipart 
        boolean isMultipart = MultiPartResponseUtils.isMultipart(mimetype);

        cfhttp.set(KeyConstants._text, Caster.toBoolean(isText));

        // mimetype charset
        //boolean responseProvideCharset=false;
        if (!StringUtil.isEmpty(mimetype, true)) {
            if (isText) {
                String[] types = HTTPUtil.splitMimeTypeAndCharset(mimetype, null);
                if (types[0] != null)
                    cfhttp.set(KeyConstants._mimetype, types[0]);
                if (types[1] != null)
                    cfhttp.set(CHARSET, types[1]);

            } else
                cfhttp.set(KeyConstants._mimetype, mimetype);
        } else
            cfhttp.set(KeyConstants._mimetype, NO_MIMETYPE);

        // File
        Resource file = null;

        if (strFile != null && strPath != null) {
            file = ResourceUtil.toResourceNotExisting(pageContext, strPath).getRealResource(strFile);
        } else if (strFile != null) {
            file = ResourceUtil.toResourceNotExisting(pageContext, strFile);
        } else if (strPath != null) {
            file = ResourceUtil.toResourceNotExisting(pageContext, strPath);
            //Resource dir = file.getParentResource();
            if (file.isDirectory()) {
                file = file.getRealResource(req.getURI().getPath());// TODO was getName() ->http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/URI.html#getName()
            }

        }
        if (file != null)
            pageContext.getConfig().getSecurityManager().checkFileLocation(file);

        // filecontent
        InputStream is = null;
        if (isText && getAsBinary != GET_AS_BINARY_YES) {
            String str;
            try {

                // read content
                if (method != METHOD_HEAD) {
                    is = rsp.getContentAsStream();
                    if (is != null && HttpImpl.isGzipEncoded(contentEncoding))
                        is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is)
                                : new GZIPInputStream(is);
                }
                try {
                    try {
                        str = is == null ? "" : IOUtil.toString(is, responseCharset);
                    } catch (EOFException eof) {
                        if (is instanceof CachingGZIPInputStream) {
                            str = IOUtil.toString(is = ((CachingGZIPInputStream) is).getRawData(),
                                    responseCharset);
                        } else
                            throw eof;
                    }
                } catch (UnsupportedEncodingException uee) {
                    str = IOUtil.toString(is, (Charset) null);
                }
            } catch (IOException ioe) {
                throw Caster.toPageException(ioe);
            } finally {
                IOUtil.closeEL(is);
            }

            if (str == null)
                str = "";
            if (resolveurl) {
                //if(e.redirectURL!=null)url=e.redirectURL.toExternalForm();
                str = new URLResolver().transform(str, e.response.getTargetURL(), false);
            }
            cfhttp.set(FILE_CONTENT, str);
            try {
                if (file != null) {
                    IOUtil.write(file, str, ((PageContextImpl) pageContext).getWebCharset(), false);
                }
            } catch (IOException e1) {
            }

            if (name != null) {
                Query qry = CSVParser.toQuery(str, delimiter, textqualifier, columns, firstrowasheaders);
                pageContext.setVariable(name, qry);
            }
        }
        // Binary
        else {
            byte[] barr = null;
            if (HttpImpl.isGzipEncoded(contentEncoding)) {
                if (method != METHOD_HEAD) {
                    is = rsp.getContentAsStream();
                    is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is) : new GZIPInputStream(is);
                }

                try {
                    try {
                        barr = is == null ? new byte[0] : IOUtil.toBytes(is);
                    } catch (EOFException eof) {
                        if (is instanceof CachingGZIPInputStream)
                            barr = IOUtil.toBytes(((CachingGZIPInputStream) is).getRawData());
                        else
                            throw eof;
                    }
                } catch (IOException t) {
                    throw Caster.toPageException(t);
                } finally {
                    IOUtil.closeEL(is);
                }
            } else {
                try {
                    if (method != METHOD_HEAD)
                        barr = rsp.getContentAsByteArray();
                    else
                        barr = new byte[0];
                } catch (IOException t) {
                    throw Caster.toPageException(t);
                }
            }
            //IF Multipart response get file content and parse parts
            if (barr != null) {
                if (isMultipart) {
                    cfhttp.set(FILE_CONTENT, MultiPartResponseUtils.getParts(barr, mimetype));
                } else {
                    cfhttp.set(FILE_CONTENT, barr);
                }
            } else
                cfhttp.set(FILE_CONTENT, "");

            if (file != null) {
                try {
                    if (barr != null)
                        IOUtil.copy(new ByteArrayInputStream(barr), file, true);
                } catch (IOException ioe) {
                    throw Caster.toPageException(ioe);
                }
            }
        }

        // header      
        cfhttp.set(KeyConstants._header, raw.toString());
        if (!HttpImpl.isStatusOK(rsp.getStatusCode())) {
            String msg = rsp.getStatusCode() + " " + rsp.getStatusText();
            cfhttp.setEL(ERROR_DETAIL, msg);
            if (throwonerror) {
                throw new HTTPException(msg, null, rsp.getStatusCode(), rsp.getStatusText(), rsp.getURL());
            }
        }
    } finally {
        if (client != null)
            client.close();
    }

}

From source file:lucee.runtime.tag.Http.java

private void _doEndTag() throws PageException, IOException {

    long start = System.nanoTime();
    HttpClientBuilder builder = HTTPEngine4Impl.getHttpClientBuilder();
    ssl(builder);//from   w  w w .  ja va2  s .  c o  m

    // redirect
    if (redirect)
        builder.setRedirectStrategy(new DefaultRedirectStrategy());
    else
        builder.disableRedirectHandling();

    // cookies
    BasicCookieStore cookieStore = new BasicCookieStore();
    builder.setDefaultCookieStore(cookieStore);

    ConfigWeb cw = pageContext.getConfig();
    HttpRequestBase req = null;
    HttpContext httpContext = null;

    CacheHandler cacheHandler = null;
    String cacheId = null;

    // HttpRequestBase req = init(pageContext.getConfig(),this,client,params,url,port);
    {
        if (StringUtil.isEmpty(charset, true))
            charset = ((PageContextImpl) pageContext).getWebCharset().name();
        else
            charset = charset.trim();

        // check if has fileUploads
        boolean doUploadFile = false;
        for (int i = 0; i < this.params.size(); i++) {
            if ((this.params.get(i)).getType() == HttpParamBean.TYPE_FILE) {
                doUploadFile = true;
                break;
            }
        }

        // parse url (also query string)
        int len = this.params.size();
        StringBuilder sbQS = new StringBuilder();
        for (int i = 0; i < len; i++) {
            HttpParamBean param = this.params.get(i);
            int type = param.getType();
            // URL
            if (type == HttpParamBean.TYPE_URL) {
                if (sbQS.length() > 0)
                    sbQS.append('&');
                sbQS.append(param.getEncoded() ? urlenc(param.getName(), charset) : param.getName());
                sbQS.append('=');
                sbQS.append(param.getEncoded() ? urlenc(param.getValueAsString(), charset)
                        : param.getValueAsString());
            }
        }

        String host = null;
        HttpHost httpHost;
        try {
            URL _url = HTTPUtil.toURL(url, port, encoded);
            httpHost = new HttpHost(_url.getHost(), _url.getPort());
            host = _url.getHost();
            url = _url.toExternalForm();
            if (sbQS.length() > 0) {
                // no existing QS
                if (StringUtil.isEmpty(_url.getQuery())) {
                    url += "?" + sbQS;
                } else {
                    url += "&" + sbQS;
                }
            }
        } catch (MalformedURLException mue) {
            throw Caster.toPageException(mue);
        }

        // cache
        if (cachedWithin != null) {

            cacheId = createCacheId();

            cacheHandler = pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_HTTP, null)
                    .getInstanceMatchingObject(cachedWithin, null);

            if (cacheHandler instanceof CacheHandlerPro) {

                CacheItem cacheItem = ((CacheHandlerPro) cacheHandler).get(pageContext, cacheId, cachedWithin);

                if (cacheItem instanceof HTTPCacheItem) {
                    pageContext.setVariable(result, ((HTTPCacheItem) cacheItem).getData());
                    return;
                }
            } else if (cacheHandler != null) { // TODO this else block can be removed when all cache handlers implement CacheHandlerPro

                CacheItem cacheItem = cacheHandler.get(pageContext, cacheId);

                if (cacheItem instanceof HTTPCacheItem) {
                    pageContext.setVariable(result, ((HTTPCacheItem) cacheItem).getData());
                    return;
                }
            }
        }

        // cache not found, process and cache result if needed

        // select best matching method (get,post, post multpart (file))

        boolean isBinary = false;
        boolean doMultiPart = doUploadFile || this.multiPart;

        HttpEntityEnclosingRequest eeReqPost = null;
        HttpEntityEnclosingRequest eeReq = null;

        if (this.method == METHOD_GET) {
            req = new HttpGetWithBody(url);
            eeReq = (HttpEntityEnclosingRequest) req;
        } else if (this.method == METHOD_HEAD) {
            req = new HttpHead(url);
        } else if (this.method == METHOD_DELETE) {
            isBinary = true;
            req = new HttpDeleteWithBody(url);
            eeReq = (HttpEntityEnclosingRequest) req;
        } else if (this.method == METHOD_PUT) {
            isBinary = true;
            HttpPut put = new HttpPut(url);
            eeReqPost = put;
            req = put;
            eeReq = put;
        } else if (this.method == METHOD_TRACE) {
            isBinary = true;
            req = new HttpTrace(url);
        } else if (this.method == METHOD_OPTIONS) {
            isBinary = true;
            req = new HttpOptions(url);
        } else if (this.method == METHOD_PATCH) {
            isBinary = true;
            eeReq = HTTPPatchFactory.getHTTPPatch(url);
            req = (HttpRequestBase) eeReq;
        } else {
            isBinary = true;
            eeReqPost = new HttpPost(url);
            req = (HttpPost) eeReqPost;
            eeReq = eeReqPost;
        }

        boolean hasForm = false;
        boolean hasBody = false;
        boolean hasContentType = false;
        // Set http params
        ArrayList<FormBodyPart> parts = new ArrayList<FormBodyPart>();

        StringBuilder acceptEncoding = new StringBuilder();
        java.util.List<NameValuePair> postParam = eeReqPost != null ? new ArrayList<NameValuePair>() : null;

        for (int i = 0; i < len; i++) {
            HttpParamBean param = this.params.get(i);
            int type = param.getType();

            // URL
            if (type == HttpParamBean.TYPE_URL) {
                // listQS.add(new BasicNameValuePair(translateEncoding(param.getName(), http.charset),translateEncoding(param.getValueAsString(),
                // http.charset)));
            }
            // Form
            else if (type == HttpParamBean.TYPE_FORM) {
                hasForm = true;
                if (this.method == METHOD_GET)
                    throw new ApplicationException(
                            "httpparam with type formfield can only be used when the method attribute of the parent http tag is set to post");
                if (eeReqPost != null) {
                    if (doMultiPart) {
                        parts.add(new FormBodyPart(param.getName(),
                                new StringBody(param.getValueAsString(), CharsetUtil.toCharset(charset))));
                    } else {
                        postParam.add(new BasicNameValuePair(param.getName(), param.getValueAsString()));
                    }
                }
                // else if(multi!=null)multi.addParameter(param.getName(),param.getValueAsString());
            }
            // CGI
            else if (type == HttpParamBean.TYPE_CGI) {
                if (param.getEncoded())
                    req.addHeader(urlenc(param.getName(), charset), urlenc(param.getValueAsString(), charset));
                else
                    req.addHeader(param.getName(), param.getValueAsString());
            }
            // Header
            else if (type == HttpParamBean.TYPE_HEADER) {
                if (param.getName().equalsIgnoreCase("content-type"))
                    hasContentType = true;

                if (param.getName().equalsIgnoreCase("Content-Length")) {
                } else if (param.getName().equalsIgnoreCase("Accept-Encoding")) {
                    acceptEncoding.append(headerValue(param.getValueAsString()));
                    acceptEncoding.append(", ");
                } else
                    req.addHeader(param.getName(), headerValue(param.getValueAsString()));
            }
            // Cookie
            else if (type == HttpParamBean.TYPE_COOKIE) {
                HTTPEngine4Impl.addCookie(cookieStore, host, param.getName(), param.getValueAsString(), "/",
                        charset);
            }
            // File
            else if (type == HttpParamBean.TYPE_FILE) {
                hasForm = true;
                if (this.method == METHOD_GET)
                    throw new ApplicationException(
                            "httpparam type file can't only be used, when method of the tag http equal post");
                // if(param.getFile()==null) throw new ApplicationException("httpparam type file can't only be used, when method of the tag http equal
                // post");
                String strCT = getContentType(param);
                ContentType ct = HTTPUtil.toContentType(strCT, null);

                String mt = "text/xml";
                if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true))
                    mt = ct.getMimeType();

                String cs = charset;
                if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true))
                    cs = ct.getCharset();

                if (doMultiPart) {
                    try {
                        Resource res = param.getFile();
                        parts.add(new FormBodyPart(param.getName(),
                                new ResourceBody(res, mt, res.getName(), cs)));
                        // parts.add(new ResourcePart(param.getName(),new ResourcePartSource(param.getFile()),getContentType(param),_charset));
                    } catch (FileNotFoundException e) {
                        throw new ApplicationException("can't upload file, path is invalid", e.getMessage());
                    }
                }
            }
            // XML
            else if (type == HttpParamBean.TYPE_XML) {
                ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null);

                String mt = "text/xml";
                if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true))
                    mt = ct.getMimeType();

                String cs = charset;
                if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true))
                    cs = ct.getCharset();

                hasBody = true;
                hasContentType = true;
                req.addHeader("Content-type", mt + "; charset=" + cs);
                if (eeReq == null)
                    throw new ApplicationException(
                            "type xml is only supported for methods get, delete, post, and put");
                HTTPEngine4Impl.setBody(eeReq, param.getValueAsString(), mt, cs);
            }
            // Body
            else if (type == HttpParamBean.TYPE_BODY) {
                ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null);

                String mt = null;
                if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true))
                    mt = ct.getMimeType();

                String cs = charset;
                if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true))
                    cs = ct.getCharset();

                hasBody = true;
                if (eeReq == null)
                    throw new ApplicationException(
                            "type body is only supported for methods get, delete, post, and put");
                HTTPEngine4Impl.setBody(eeReq, param.getValue(), mt, cs);

            } else {
                throw new ApplicationException("invalid type [" + type + "]");
            }

        }

        // post params
        if (postParam != null && postParam.size() > 0)
            eeReqPost.setEntity(new org.apache.http.client.entity.UrlEncodedFormEntity(postParam, charset));

        if (compression) {
            acceptEncoding.append("gzip");
        } else {
            acceptEncoding.append("deflate;q=0");
            req.setHeader("TE", "deflate;q=0");
        }
        req.setHeader("Accept-Encoding", acceptEncoding.toString());

        // multipart
        if (doMultiPart && eeReq != null) {
            hasContentType = true;
            boolean doIt = true;
            if (!this.multiPart && parts.size() == 1) {
                ContentBody body = parts.get(0).getBody();
                if (body instanceof StringBody) {
                    StringBody sb = (StringBody) body;
                    try {
                        org.apache.http.entity.ContentType ct = org.apache.http.entity.ContentType
                                .create(sb.getMimeType(), sb.getCharset());
                        String str = IOUtil.toString(sb.getReader());
                        StringEntity entity = new StringEntity(str, ct);
                        eeReq.setEntity(entity);

                    } catch (IOException e) {
                        throw Caster.toPageException(e);
                    }
                    doIt = false;
                }
            }

            if (doIt) {

                MultipartEntityBuilder mpeBuilder = MultipartEntityBuilder.create().setStrictMode();

                // enabling the line below will append charset=... to the Content-Type header
                // if (!StringUtil.isEmpty(charset, true))
                // mpeBuilder.setCharset(CharsetUtil.toCharset(charset));

                Iterator<FormBodyPart> it = parts.iterator();
                while (it.hasNext()) {
                    FormBodyPart part = it.next();
                    mpeBuilder.addPart(part);
                }

                eeReq.setEntity(mpeBuilder.build());
            }
            // eem.setRequestEntity(new MultipartRequestEntityFlex(parts.toArray(new Part[parts.size()]), eem.getParams(),http.multiPartType));
        }

        if (hasBody && hasForm)
            throw new ApplicationException("mixing httpparam  type file/formfield and body/XML is not allowed");

        if (!hasContentType) {
            if (isBinary) {
                if (hasBody)
                    req.addHeader("Content-type", "application/octet-stream");
                else
                    req.addHeader("Content-type", "application/x-www-form-urlencoded; charset=" + charset);
            } else {
                if (hasBody)
                    req.addHeader("Content-type", "text/html; charset=" + charset);
            }
        }

        // set User Agent
        if (!hasHeaderIgnoreCase(req, "User-Agent"))
            req.setHeader("User-Agent", this.useragent);

        // set timeout
        setTimeout(builder, checkRemainingTimeout());

        // set Username and Password
        if (this.username != null) {
            if (this.password == null)
                this.password = "";
            if (AUTH_TYPE_NTLM == this.authType) {
                if (StringUtil.isEmpty(this.workStation, true))
                    throw new ApplicationException(
                            "attribute workstation is required when authentication type is [NTLM]");
                if (StringUtil.isEmpty(this.domain, true))
                    throw new ApplicationException(
                            "attribute domain is required when authentication type is [NTLM]");

                HTTPEngine4Impl.setNTCredentials(builder, this.username, this.password, this.workStation,
                        this.domain);
            } else
                httpContext = HTTPEngine4Impl.setCredentials(builder, httpHost, this.username, this.password,
                        preauth);
        }

        // set Proxy
        ProxyData proxy = null;
        if (!StringUtil.isEmpty(this.proxyserver)) {
            proxy = ProxyDataImpl.getInstance(this.proxyserver, this.proxyport, this.proxyuser,
                    this.proxypassword);
        }
        if (pageContext.getConfig().isProxyEnableFor(host)) {
            proxy = pageContext.getConfig().getProxyData();
        }
        HTTPEngine4Impl.setProxy(builder, req, proxy);

    }

    CloseableHttpClient client = null;
    try {
        if (httpContext == null)
            httpContext = new BasicHttpContext();

        Struct cfhttp = new StructImpl();
        cfhttp.setEL(ERROR_DETAIL, "");
        pageContext.setVariable(result, cfhttp);

        /////////////////////////////////////////// EXECUTE /////////////////////////////////////////////////
        client = builder.build();
        Executor4 e = new Executor4(pageContext, this, client, httpContext, req, redirect);
        HTTPResponse4Impl rsp = null;

        if (timeout == null || timeout.getMillis() <= 0) {
            try {
                rsp = e.execute(httpContext);
            }

            catch (Throwable t) {
                ExceptionUtil.rethrowIfNecessary(t);
                if (!throwonerror) {
                    if (t instanceof SocketTimeoutException)
                        setRequestTimeout(cfhttp);
                    else
                        setUnknownHost(cfhttp, t);
                    return;
                }
                throw toPageException(t, rsp);

            }
        } else {
            e.start();
            try {
                synchronized (this) {// print.err(timeout);
                    this.wait(timeout.getMillis());
                }
            } catch (InterruptedException ie) {
                throw Caster.toPageException(ie);
            }
            if (e.t != null) {
                if (!throwonerror) {
                    setUnknownHost(cfhttp, e.t);
                    return;
                }
                throw toPageException(e.t, rsp);
            }

            rsp = e.response;

            if (!e.done) {
                req.abort();
                if (throwonerror)
                    throw new HTTPException("408 Request Time-out", "a timeout occurred in tag http", 408,
                            "Time-out", rsp == null ? null : rsp.getURL());
                setRequestTimeout(cfhttp);
                return;
                // throw new ApplicationException("timeout");
            }
        }

        /////////////////////////////////////////// EXECUTE /////////////////////////////////////////////////
        Charset responseCharset = CharsetUtil.toCharset(rsp.getCharset());
        int statCode = 0;
        // Write Response Scope
        // String rawHeader=httpMethod.getStatusLine().toString();
        String mimetype = null;
        String contentEncoding = null;

        // status code
        cfhttp.set(STATUSCODE, ((rsp.getStatusCode() + " " + rsp.getStatusText()).trim()));
        cfhttp.set(STATUS_CODE, new Double(statCode = rsp.getStatusCode()));
        cfhttp.set(STATUS_TEXT, (rsp.getStatusText()));
        cfhttp.set(HTTP_VERSION, (rsp.getProtocolVersion()));

        // responseHeader
        lucee.commons.net.http.Header[] headers = rsp.getAllHeaders();
        StringBuffer raw = new StringBuffer(rsp.getStatusLine() + " ");
        Struct responseHeader = new StructImpl();
        Struct cookie;
        Array setCookie = new ArrayImpl();
        Query cookies = new QueryImpl(
                new String[] { "name", "value", "path", "domain", "expires", "secure", "httpOnly" }, 0,
                "cookies");

        for (int i = 0; i < headers.length; i++) {
            lucee.commons.net.http.Header header = headers[i];
            // print.ln(header);

            raw.append(header.toString() + " ");
            if (header.getName().equalsIgnoreCase("Set-Cookie")) {
                setCookie.append(header.getValue());
                parseCookie(cookies, header.getValue());
            } else {
                // print.ln(header.getName()+"-"+header.getValue());
                Object value = responseHeader.get(KeyImpl.getInstance(header.getName()), null);
                if (value == null)
                    responseHeader.set(KeyImpl.getInstance(header.getName()), header.getValue());
                else {
                    Array arr = null;
                    if (value instanceof Array) {
                        arr = (Array) value;
                    } else {
                        arr = new ArrayImpl();
                        responseHeader.set(KeyImpl.getInstance(header.getName()), arr);
                        arr.appendEL(value);
                    }
                    arr.appendEL(header.getValue());
                }
            }

            // Content-Type
            if (header.getName().equalsIgnoreCase("Content-Type")) {
                mimetype = header.getValue();
                if (mimetype == null)
                    mimetype = NO_MIMETYPE;
            }

            // Content-Encoding
            if (header.getName().equalsIgnoreCase("Content-Encoding")) {
                contentEncoding = header.getValue();
            }

        }
        cfhttp.set(RESPONSEHEADER, responseHeader);
        cfhttp.set(KeyConstants._cookies, cookies);
        responseHeader.set(STATUS_CODE, new Double(statCode = rsp.getStatusCode()));
        responseHeader.set(EXPLANATION, (rsp.getStatusText()));
        if (setCookie.size() > 0)
            responseHeader.set(SET_COOKIE, setCookie);

        // is text
        boolean isText = mimetype == null || mimetype == NO_MIMETYPE || HTTPUtil.isTextMimeType(mimetype);

        // is multipart
        boolean isMultipart = MultiPartResponseUtils.isMultipart(mimetype);

        cfhttp.set(KeyConstants._text, Caster.toBoolean(isText));

        // mimetype charset
        // boolean responseProvideCharset=false;
        if (!StringUtil.isEmpty(mimetype, true)) {
            if (isText) {
                String[] types = HTTPUtil.splitMimeTypeAndCharset(mimetype, null);
                if (types[0] != null)
                    cfhttp.set(KeyConstants._mimetype, types[0]);
                if (types[1] != null)
                    cfhttp.set(CHARSET, types[1]);

            } else
                cfhttp.set(KeyConstants._mimetype, mimetype);
        } else
            cfhttp.set(KeyConstants._mimetype, NO_MIMETYPE);

        // File
        Resource file = null;

        if (strFile != null && strPath != null) {
            file = ResourceUtil.toResourceNotExisting(pageContext, strPath).getRealResource(strFile);
        } else if (strFile != null) {
            file = ResourceUtil.toResourceNotExisting(pageContext, strFile);
        } else if (strPath != null) {
            file = ResourceUtil.toResourceNotExisting(pageContext, strPath);
            // Resource dir = file.getParentResource();
            if (file.isDirectory()) {
                file = file.getRealResource(req.getURI().getPath());// TODO was getName()
                // ->http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/URI.html#getName()
            }

        }
        if (file != null)
            pageContext.getConfig().getSecurityManager().checkFileLocation(file);

        // filecontent
        InputStream is = null;
        if (isText && getAsBinary != GET_AS_BINARY_YES) {
            String str;
            try {

                // read content
                if (method != METHOD_HEAD) {
                    is = rsp.getContentAsStream();
                    if (is != null && isGzipEncoded(contentEncoding))
                        is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is)
                                : new GZIPInputStream(is);
                }
                try {
                    try {
                        str = is == null ? ""
                                : IOUtil.toString(is, responseCharset, checkRemainingTimeout().getMillis());
                    } catch (EOFException eof) {
                        if (is instanceof CachingGZIPInputStream) {
                            str = IOUtil.toString(is = ((CachingGZIPInputStream) is).getRawData(),
                                    responseCharset, checkRemainingTimeout().getMillis());
                        } else
                            throw eof;
                    }
                } catch (UnsupportedEncodingException uee) {
                    str = IOUtil.toString(is, (Charset) null, checkRemainingTimeout().getMillis());
                }
            } catch (IOException ioe) {
                throw Caster.toPageException(ioe);
            } finally {
                IOUtil.closeEL(is);
            }

            if (str == null)
                str = "";
            if (resolveurl) {
                // if(e.redirectURL!=null)url=e.redirectURL.toExternalForm();
                str = new URLResolver().transform(str, e.response.getTargetURL(), false);
            }
            cfhttp.set(KeyConstants._filecontent, str);
            try {
                if (file != null) {
                    IOUtil.write(file, str, ((PageContextImpl) pageContext).getWebCharset(), false);
                }
            } catch (IOException e1) {
            }

            if (name != null) {
                Query qry = CSVParser.toQuery(str, delimiter, textqualifier, columns, firstrowasheaders);
                pageContext.setVariable(name, qry);
            }
        }
        // Binary
        else {
            byte[] barr = null;
            if (isGzipEncoded(contentEncoding)) {
                if (method != METHOD_HEAD) {
                    is = rsp.getContentAsStream();
                    is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is) : new GZIPInputStream(is);
                }

                try {
                    try {
                        barr = is == null ? new byte[0] : IOUtil.toBytes(is);
                    } catch (EOFException eof) {
                        if (is instanceof CachingGZIPInputStream)
                            barr = IOUtil.toBytes(((CachingGZIPInputStream) is).getRawData());
                        else
                            throw eof;
                    }
                } catch (IOException t) {
                    throw Caster.toPageException(t);
                } finally {
                    IOUtil.closeEL(is);
                }
            } else {
                try {
                    if (method != METHOD_HEAD)
                        barr = rsp.getContentAsByteArray();
                    else
                        barr = new byte[0];
                } catch (IOException t) {
                    throw Caster.toPageException(t);
                }
            }
            // IF Multipart response get file content and parse parts
            if (barr != null) {
                if (isMultipart) {
                    cfhttp.set(KeyConstants._filecontent, MultiPartResponseUtils.getParts(barr, mimetype));
                } else {
                    cfhttp.set(KeyConstants._filecontent, barr);
                }
            } else
                cfhttp.set(KeyConstants._filecontent, "");

            if (file != null) {
                try {
                    if (barr != null)
                        IOUtil.copy(new ByteArrayInputStream(barr), file, true);
                } catch (IOException ioe) {
                    throw Caster.toPageException(ioe);
                }
            }
        }

        // header
        cfhttp.set(KeyConstants._header, raw.toString());
        if (!isStatusOK(rsp.getStatusCode())) {
            String msg = rsp.getStatusCode() + " " + rsp.getStatusText();
            cfhttp.setEL(ERROR_DETAIL, msg);
            if (throwonerror) {
                throw new HTTPException(msg, null, rsp.getStatusCode(), rsp.getStatusText(), rsp.getURL());
            }
        }

        // TODO: check if we can use statCode instead of rsp.getStatusCode() everywhere and cleanup the code
        if (cacheHandler != null && rsp.getStatusCode() == 200) {
            // add to cache
            cacheHandler.set(pageContext, cacheId, cachedWithin,
                    new HTTPCacheItem(cfhttp, url, System.nanoTime() - start));
        }
    } finally {
        if (client != null)
            client.close();
    }
}

From source file:org.apache.gobblin.service.modules.orchestration.AzkabanClient.java

/**
 * Create a {@link CloseableHttpClient} used to communicate with Azkaban server.
 * Derived class can configure different http client by overriding this method.
 *
 * @return A closeable http client.//from   w w w. j av  a 2s . c  o m
 */
protected CloseableHttpClient getClient() throws AzkabanClientException {
    try {
        // SSLSocketFactory using custom TrustStrategy that ignores warnings about untrusted certificates
        // Self sign SSL
        SSLContextBuilder sslcb = new SSLContextBuilder();
        sslcb.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcb.build());

        HttpClientBuilder builder = HttpClientBuilder.create();
        RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(10000)
                .setConnectTimeout(10000).setConnectionRequestTimeout(10000).build();

        builder.disableCookieManagement().useSystemProperties().setDefaultRequestConfig(requestConfig)
                .setConnectionManager(new BasicHttpClientConnectionManager()).setSSLSocketFactory(sslsf);

        return builder.build();
    } catch (Exception e) {
        throw new AzkabanClientException("HttpClient cannot be created", e);
    }
}

From source file:org.apache.hadoop.hbase.thrift2.client.ThriftConnection.java

public synchronized HttpClient getHttpClient() {
    if (httpClient != null) {
        return httpClient;
    }//from  www  .j  av  a2  s  .  co  m
    int retry = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
            HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
    long pause = conf.getLong(HConstants.HBASE_CLIENT_PAUSE, 5);
    HttpClientBuilder builder = HttpClientBuilder.create();
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(getConnectTimeout());
    requestBuilder = requestBuilder.setSocketTimeout(getOperationTimeout());
    builder.setRetryHandler(new DelayRetryHandler(retry, pause));
    builder.setDefaultRequestConfig(requestBuilder.build());
    httpClient = builder.build();
    httpClientCreated = true;
    return httpClient;
}

From source file:org.apache.hive.jdbc.HiveConnection.java

private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException {
    boolean isCookieEnabled = sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH) == null
            || (!JdbcConnectionParams.COOKIE_AUTH_FALSE
                    .equalsIgnoreCase(sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH)));
    String cookieName = sessConfMap.get(JdbcConnectionParams.COOKIE_NAME) == null
            ? JdbcConnectionParams.DEFAULT_COOKIE_NAMES_HS2
            : sessConfMap.get(JdbcConnectionParams.COOKIE_NAME);
    CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null;
    HttpClientBuilder httpClientBuilder;
    // Request interceptor for any request pre-processing logic
    HttpRequestInterceptor requestInterceptor;
    Map<String, String> additionalHttpHeaders = new HashMap<String, String>();

    // Retrieve the additional HttpHeaders
    for (Map.Entry<String, String> entry : sessConfMap.entrySet()) {
        String key = entry.getKey();

        if (key.startsWith(JdbcConnectionParams.HTTP_HEADER_PREFIX)) {
            additionalHttpHeaders.put(key.substring(JdbcConnectionParams.HTTP_HEADER_PREFIX.length()),
                    entry.getValue());//  www  . j a  va2s. co m
        }
    }
    // Configure http client for kerberos/password based authentication
    if (isKerberosAuthMode()) {
        /**
         * Add an interceptor which sets the appropriate header in the request.
         * It does the kerberos authentication and get the final service ticket,
         * for sending to the server before every request.
         * In https mode, the entire information is encrypted
         */
        requestInterceptor = new HttpKerberosRequestInterceptor(
                sessConfMap.get(JdbcConnectionParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl),
                assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders);
    } else {
        // Check for delegation token, if present add it in the header
        String tokenStr = getClientDelegationToken(sessConfMap);
        if (tokenStr != null) {
            requestInterceptor = new HttpTokenAuthInterceptor(tokenStr, cookieStore, cookieName, useSsl,
                    additionalHttpHeaders);
        } else {
            /**
             * Add an interceptor to pass username/password in the header.
             * In https mode, the entire information is encrypted
             */
            requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword(), cookieStore,
                    cookieName, useSsl, additionalHttpHeaders);
        }
    }
    // Configure http client for cookie based authentication
    if (isCookieEnabled) {
        // Create a http client with a retry mechanism when the server returns a status code of 401.
        httpClientBuilder = HttpClients.custom()
                .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
                    @Override
                    public boolean retryRequest(final HttpResponse response, final int executionCount,
                            final HttpContext context) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        boolean ret = statusCode == 401 && executionCount <= 1;

                        // Set the context attribute to true which will be interpreted by the request
                        // interceptor
                        if (ret) {
                            context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE);
                        }
                        return ret;
                    }

                    @Override
                    public long getRetryInterval() {
                        // Immediate retry
                        return 0;
                    }
                });
    } else {
        httpClientBuilder = HttpClientBuilder.create();
    }
    // In case the server's idletimeout is set to a lower value, it might close it's side of
    // connection. However we retry one more time on NoHttpResponseException
    httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > 1) {
                LOG.info("Retry attempts to connect to server exceeded.");
                return false;
            }
            if (exception instanceof org.apache.http.NoHttpResponseException) {
                LOG.info("Could not connect to the server. Retrying one more time.");
                return true;
            }
            return false;
        }
    });

    // Add the request interceptor to the client builder
    httpClientBuilder.addInterceptorFirst(requestInterceptor);

    // Add an interceptor to add in an XSRF header
    httpClientBuilder.addInterceptorLast(new XsrfHttpRequestInterceptor());

    // Configure http client for SSL
    if (useSsl) {
        String useTwoWaySSL = sessConfMap.get(JdbcConnectionParams.USE_TWO_WAY_SSL);
        String sslTrustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE);
        String sslTrustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore;
        SSLConnectionSocketFactory socketFactory;
        SSLContext sslContext;
        /**
         * The code within the try block throws: SSLInitializationException, KeyStoreException,
         * IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException &
         * UnrecoverableKeyException. We don't want the client to retry on any of these,
         * hence we catch all and throw a SQLException.
         */
        try {
            if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(JdbcConnectionParams.TRUE)) {
                socketFactory = getTwoWaySSLSocketFactory();
            } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) {
                // Create a default socket factory based on standard JSSE trust material
                socketFactory = SSLConnectionSocketFactory.getSocketFactory();
            } else {
                // Pick trust store config from the given path
                sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE);
                try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) {
                    sslTrustStore.load(fis, sslTrustStorePassword.toCharArray());
                }
                sslContext = SSLContexts.custom().loadTrustMaterial(sslTrustStore, null).build();
                socketFactory = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier(null));
            }
            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", socketFactory).build();
            httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        } catch (Exception e) {
            String msg = "Could not create an https connection to " + jdbcUriString + ". " + e.getMessage();
            throw new SQLException(msg, " 08S01", e);
        }
    }
    return httpClientBuilder.build();
}