Example usage for org.apache.http.impl.client BasicCookieStore BasicCookieStore

List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore

Introduction

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

Prototype

public BasicCookieStore() 

Source Link

Usage

From source file:org.xdi.oxauth.ws.rs.SSOWithMultipleBackendServicesHttpTest.java

@Parameters({ "redirectUris", "redirectUri", "userInum", "userEmail", "hostnameVerifier" })
@Test/*from   www .  j  a va2s. c  om*/
public void sessionWorkFlow2(final String redirectUris, final String redirectUri, final String userInum,
        final String userEmail, final String hostnameVerifier) throws Exception {
    showTitle("sessionWorkFlow2");

    // Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(registerResponse.getStatus(), 200,
            "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();

    DefaultHttpClient httpClient = createHttpClient(HostnameVerifierType.fromString(hostnameVerifier));
    CookieStore cookieStore = new BasicCookieStore();
    httpClient.setCookieStore(cookieStore);
    ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);

    // Authorization code flow to authenticate on B1

    AuthorizationRequest authorizationRequest1 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE),
            clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null);

    authorizationRequest1.addCustomParameter("mail", userEmail);
    authorizationRequest1.addCustomParameter("inum", userInum);
    authorizationRequest1.getPrompts().add(Prompt.NONE);
    authorizationRequest1.setState("af0ifjsldkj");
    authorizationRequest1.setAuthorizationMethod(AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER);
    authorizationRequest1.setRequestSessionId(true);

    AuthorizeClient authorizeClient1 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient1.setRequest(authorizationRequest1);
    AuthorizationResponse authorizationResponse1 = authorizeClient1.exec(clientExecutor);

    showClient(authorizeClient1);
    assertEquals(authorizationResponse1.getStatus(), 302,
            "Unexpected response code: " + authorizationResponse1.getStatus());
    assertNotNull(authorizationResponse1.getLocation(), "The location is null");
    assertNotNull(authorizationResponse1.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse1.getSessionId(), "The session id is null");
    assertNotNull(authorizationResponse1.getState(), "The state is null");
    assertNotNull(authorizationResponse1.getScope(), "The scope is null");

    String authorizationCode1 = authorizationResponse1.getCode();
    String sessionId = authorizationResponse1.getSessionId();

    TokenRequest tokenRequest1 = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest1.setCode(authorizationCode1);
    tokenRequest1.setRedirectUri(redirectUri);
    tokenRequest1.setAuthUsername(clientId);
    tokenRequest1.setAuthPassword(clientSecret);
    tokenRequest1.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    TokenClient tokenClient1 = new TokenClient(tokenEndpoint);
    tokenClient1.setRequest(tokenRequest1);
    TokenResponse tokenResponse1 = tokenClient1.exec();

    showClient(tokenClient1);
    assertEquals(tokenResponse1.getStatus(), 200, "Unexpected response code: " + tokenResponse1.getStatus());
    assertNotNull(tokenResponse1.getEntity(), "The entity is null");
    assertNotNull(tokenResponse1.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse1.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse1.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse1.getRefreshToken(), "The refresh token is null");

    // User wants to authenticate on B2 (without sending its credentials)

    AuthorizationRequest authorizationRequest2 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE),
            clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null);

    authorizationRequest2.getPrompts().add(Prompt.NONE);
    authorizationRequest2.setState("af0ifjsldkj");
    authorizationRequest2.setSessionId(sessionId);

    AuthorizeClient authorizeClient2 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient2.setRequest(authorizationRequest2);
    AuthorizationResponse authorizationResponse2 = authorizeClient2.exec(clientExecutor);

    showClient(authorizeClient2);
    assertEquals(authorizationResponse2.getStatus(), 302,
            "Unexpected response code: " + authorizationResponse2.getStatus());
    assertNotNull(authorizationResponse2.getLocation(), "The location is null");
    assertNotNull(authorizationResponse2.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse2.getState(), "The state is null");
    assertNotNull(authorizationResponse2.getScope(), "The scope is null");

    String authorizationCode2 = authorizationResponse2.getCode();

    TokenRequest tokenRequest2 = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest2.setCode(authorizationCode2);
    tokenRequest2.setRedirectUri(redirectUri);
    tokenRequest2.setAuthUsername(clientId);
    tokenRequest2.setAuthPassword(clientSecret);
    tokenRequest2.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    TokenClient tokenClient2 = new TokenClient(tokenEndpoint);
    tokenClient2.setRequest(tokenRequest2);
    TokenResponse tokenResponse2 = tokenClient2.exec();

    showClient(tokenClient2);
    assertEquals(tokenResponse2.getStatus(), 200, "Unexpected response code: " + tokenResponse2.getStatus());
    assertNotNull(tokenResponse2.getEntity(), "The entity is null");
    assertNotNull(tokenResponse2.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse2.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse2.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse2.getRefreshToken(), "The refresh token is null");

    // User wants to authenticate on B3 (without sending its credentials)

    AuthorizationRequest authorizationRequest3 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE),
            clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null);

    authorizationRequest3.getPrompts().add(Prompt.NONE);
    authorizationRequest3.setState("af0ifjsldkj");
    authorizationRequest3.setSessionId(sessionId);

    AuthorizeClient authorizeClient3 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient3.setRequest(authorizationRequest3);
    AuthorizationResponse authorizationResponse3 = authorizeClient2.exec(clientExecutor);

    showClient(authorizeClient3);
    assertEquals(authorizationResponse3.getStatus(), 302,
            "Unexpected response code: " + authorizationResponse3.getStatus());
    assertNotNull(authorizationResponse3.getLocation(), "The location is null");
    assertNotNull(authorizationResponse3.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse3.getState(), "The state is null");
    assertNotNull(authorizationResponse3.getScope(), "The scope is null");

    String authorizationCode3 = authorizationResponse3.getCode();

    TokenRequest tokenRequest3 = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest3.setCode(authorizationCode3);
    tokenRequest3.setRedirectUri(redirectUri);
    tokenRequest3.setAuthUsername(clientId);
    tokenRequest3.setAuthPassword(clientSecret);
    tokenRequest3.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    TokenClient tokenClient3 = new TokenClient(tokenEndpoint);
    tokenClient3.setRequest(tokenRequest3);
    TokenResponse tokenResponse3 = tokenClient3.exec();

    showClient(tokenClient3);
    assertEquals(tokenResponse3.getStatus(), 200, "Unexpected response code: " + tokenResponse3.getStatus());
    assertNotNull(tokenResponse3.getEntity(), "The entity is null");
    assertNotNull(tokenResponse3.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse3.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse3.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse3.getRefreshToken(), "The refresh token is null");
}

From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

private HttpClientContext createHttpContext(String requestUrl, boolean isLoginRequest) {
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(new BasicCookieStore());

    //  add security token if needed
    if (!isLoginRequest) {
        context.getCookieStore().addCookie(LWSSO_TOKEN);
    }/*  w  w  w  .ja  v a  2 s  .co  m*/

    //  prepare request config
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD);

    //  configure proxy if needed
    URL parsedUrl = CIPluginSDKUtils.parseURL(requestUrl);
    CIProxyConfiguration proxyConfiguration = configurer.pluginServices.getProxyConfiguration(parsedUrl);
    if (proxyConfiguration != null) {
        logger.debug("proxy will be used with the following setup: " + proxyConfiguration);
        HttpHost proxyHost = new HttpHost(proxyConfiguration.getHost(), proxyConfiguration.getPort());

        if (proxyConfiguration.getUsername() != null && !proxyConfiguration.getUsername().isEmpty()) {
            AuthScope authScope = new AuthScope(proxyHost);
            Credentials credentials = new UsernamePasswordCredentials(proxyConfiguration.getUsername(),
                    proxyConfiguration.getPassword());
            CredentialsProvider credentialsProvider = new SystemDefaultCredentialsProvider();
            credentialsProvider.setCredentials(authScope, credentials);
            context.setCredentialsProvider(credentialsProvider);
        }
        requestConfigBuilder.setProxy(proxyHost);
    }

    context.setRequestConfig(requestConfigBuilder.build());
    return context;
}

From source file:edu.mit.scratch.ScratchCloudSession.java

public List<String> getVariables() throws ScratchProjectException {
    final List<String> list = new ArrayList<>();

    try {/*from  w w w  . jav  a2  s.c  o  m*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/varserver/" + this.getProjectID())
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*//*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        final JSONObject jsonOBJ = new JSONObject(result.toString().trim());

        final Iterator<?> keys = ((JSONArray) jsonOBJ.get("variables")).iterator();

        while (keys.hasNext()) {
            final JSONObject o = new JSONObject(StringEscapeUtils.unescapeJson("" + keys.next()));
            final String k = o.get("name") + "";
            list.add(k);
        }
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    return list;
}

From source file:org.apache.abdera2.common.protocol.BasicClient.java

/**
 * Get the underlying HTTP Client's Cookie Store, optionally creating it
 * if it does not already exist/*from  w ww  . j  a v  a  2 s .com*/
 */
public CookieStore getCookieStore(boolean create) {
    CookieStore store = getDefaultHttpClient().getCookieStore();
    if (store == null && create) {
        synchronized (this) {
            store = new BasicCookieStore();
            getDefaultHttpClient().setCookieStore(store);
        }
    }
    return store;
}

From source file:test.integ.be.e_contract.cdi.crossconversation.CrossConversationScopedTest.java

@Test
public void testAndroidSessionSeparation() throws Exception {
    String webBrowserTestLocation = this.baseURL + "browser";
    String webBrowserValueLocation = this.baseURL + "value";
    LOGGER.debug("location: {}", webBrowserTestLocation);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCookieStore(new BasicCookieStore());
    HttpClient webBrowserHttpClient1 = httpClientBuilder.build();

    httpClientBuilder.setDefaultCookieStore(new BasicCookieStore());
    HttpClient webBrowserHttpClient2 = httpClientBuilder.build();

    HttpContext webBrowserHttpContext1 = new BasicHttpContext();
    String webBrowserCode1 = doGet(webBrowserHttpClient1, webBrowserHttpContext1, webBrowserTestLocation);
    String webBrowserValue1 = doGet(webBrowserHttpClient1, webBrowserHttpContext1, webBrowserValueLocation);

    HttpContext webBrowserHttpContext2 = new BasicHttpContext();
    String webBrowserCode2 = doGet(webBrowserHttpClient2, webBrowserHttpContext2, webBrowserTestLocation);
    String webBrowserValue2 = doGet(webBrowserHttpClient2, webBrowserHttpContext2, webBrowserValueLocation);

    assertNotEquals(webBrowserCode1, webBrowserCode2);
    assertNotEquals(webBrowserValue1, webBrowserValue2);

    String androidLocation1 = this.baseURL + "android?androidCode=" + webBrowserCode1;
    String androidValueLocation1 = webBrowserValueLocation + "?androidCode=" + webBrowserCode1;

    HttpClient androidHttpClient = httpClientBuilder.build();

    HttpContext androidHttpContext1 = new BasicHttpContext();
    String androidCode1 = doGet(androidHttpClient, androidHttpContext1, androidLocation1);
    String androidValue1 = doGet(androidHttpClient, androidHttpContext1, androidValueLocation1);

    assertEquals(webBrowserCode1, androidCode1);
    assertEquals(webBrowserValue1, androidValue1);

    String androidLocation2 = this.baseURL + "android?androidCode=" + webBrowserCode2;
    String androidValueLocation2 = webBrowserValueLocation + "?androidCode=" + webBrowserCode2;

    HttpContext androidHttpContext2 = new BasicHttpContext();
    String androidCode2 = doGet(androidHttpClient, androidHttpContext2, androidLocation2);
    String androidValue2 = doGet(androidHttpClient, androidHttpContext2, androidValueLocation2);

    assertEquals(webBrowserCode2, androidCode2);
    assertEquals(webBrowserValue2, androidValue2);
}

From source file:MinimalServerTest.java

License:asdf

public void testEndOfSession() throws Exception {
    //Create client
    HttpClient client = new DefaultHttpClient();
    HttpPost mockRequest = new HttpPost("http://localhost:5555/login");
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    mockRequest.setHeader("Content-type", "application/x-www-form-urlencoded");

    //Add parameters
    List<NameValuePair> urlParameters = new ArrayList<>();
    urlParameters.add(new BasicNameValuePair("email", "test"));
    urlParameters.add(new BasicNameValuePair("deviceUID", "BD655C43-3A73-4DFB-AA1F-074A4F0B0DCE"));
    mockRequest.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
    //Execute the request
    HttpResponse mockResponse = client.execute(mockRequest, httpContext);

    //Test if normal login is successful
    BufferedReader rd = new BufferedReader(new InputStreamReader(mockResponse.getEntity().getContent()));
    rd.close();//  w w  w  .  j av  a 2s.c  om
    HttpPost mockRequest2 = new HttpPost("http://localhost:5555/start");
    mockRequest2.setHeader("Content-type", "application/x-www-form-urlencoded");
    //Add parameters
    HttpResponse mockResponse2 = client.execute(mockRequest2, httpContext);
    rd = new BufferedReader(new InputStreamReader(mockResponse2.getEntity().getContent()));
    rd.close();
    HttpPost mockRequest1 = new HttpPost("http://localhost:5555/nextImage");
    mockRequest2.setHeader("Content-type", "application/x-www-form-urlencoded");
    //Add parameters
    List<NameValuePair> urlParameters1 = new ArrayList<>();
    urlParameters1.add(new BasicNameValuePair("deviceUID", "BD655C43-3A73-4DFB-AA1F-074A4F0B0DCE"));
    urlParameters1.add(new BasicNameValuePair("comment", "asdf"));
    urlParameters1.add(new BasicNameValuePair("result", "3"));
    mockRequest1.setEntity(new UrlEncodedFormEntity(urlParameters1, "UTF-8"));
    HttpResponse mockResponse1 = client.execute(mockRequest1, httpContext);
    rd = new BufferedReader(new InputStreamReader(mockResponse1.getEntity().getContent()));
    System.out.println("++++ " + rd.readLine());
    //                "status": "1", //0 if the app should keep waiting, 1 for success, 2 if the votong session has fininshed
    //              "sessionType": "normal", //alternatively Yes/No or winner
    //              "rangeBottom": "0",
    //              "rangeTop": "15",
    //              "description": "image discription here",
    //              "comments": "True",  //True if comments are allowed, False if not
    //              "imgPath": "path/to/image.jpg" //the path where the image resides on the server

    assertEquals("Testing if login was correctly failed due to incorrect username", true, true);
}

From source file:org.opendatakit.briefcase.util.WebUtils.java

public static HttpContext createHttpContext() {
    // set up one context for all HTTP requests so that authentication
    // and cookies can be retained.
    HttpContext localContext = new SyncBasicHttpContext(new BasicHttpContext());

    // establish a local cookie store for this attempt at downloading...
    CookieStore cookieStore = new BasicCookieStore();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    // and establish a credentials provider...
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);

    return localContext;
}

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());/*from w ww.  j  ava2  s . c  o 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.cxf.transport.http.asyncclient.AsyncHTTPConduitFactory.java

public synchronized void setupNIOClient(HTTPClientPolicy clientPolicy) throws IOReactorException {
    if (client != null) {
        return;/*w ww.  jav a 2s .c  om*/
    }

    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(ioThreadCount)
            .setSelectInterval(selectInterval).setInterestOpQueued(interestOpQueued).setSoLinger(soLinger)
            .setSoTimeout(soTimeout).setSoKeepAlive(soKeepalive).setTcpNoDelay(tcpNoDelay).build();

    Registry<SchemeIOSessionStrategy> ioSessionFactoryRegistry = RegistryBuilder
            .<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE)
            .register("https", SSLIOSessionStrategy.getSystemDefaultStrategy()).build();

    ManagedNHttpClientConnectionFactory connectionFactory = new ManagedNHttpClientConnectionFactory() {

        @Override
        public ManagedNHttpClientConnection create(final IOSession iosession, final ConnectionConfig config) {
            ManagedNHttpClientConnection conn = super.create(iosession, config);
            return conn;
        }
    };

    DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(config);
    connectionManager = new PoolingNHttpClientConnectionManager(ioreactor, connectionFactory,
            ioSessionFactoryRegistry, DefaultSchemePortResolver.INSTANCE, SystemDefaultDnsResolver.INSTANCE,
            connectionTTL, TimeUnit.MILLISECONDS);

    connectionManager.setDefaultMaxPerRoute(maxPerRoute);
    connectionManager.setMaxTotal(maxConnections);

    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setBufferSize(clientPolicy.getChunkLength() > 0 ? clientPolicy.getChunkLength() : 16332).build();

    connectionManager.setDefaultConnectionConfig(connectionConfig);

    RedirectStrategy redirectStrategy = new RedirectStrategy() {

        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {
            return false;
        }

        public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {
            return null;
        }
    };

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom()
            .setConnectionManager(connectionManager).setRedirectStrategy(redirectStrategy)
            .setDefaultCookieStore(new BasicCookieStore() {
                private static final long serialVersionUID = 1L;

                public void addCookie(Cookie cookie) {
                }
            });

    adaptClientBuilder(httpAsyncClientBuilder);

    client = httpAsyncClientBuilder.build();
    // Start the client thread
    client.start();
    if (this.connectionTTL == 0) {
        //if the connection does not have an expiry deadline
        //use the ConnectionMaxIdle to close the idle connection
        new CloseIdleConnectionThread(connectionManager, client).start();
    }
}