Example usage for org.apache.http.ssl SSLContextBuilder SSLContextBuilder

List of usage examples for org.apache.http.ssl SSLContextBuilder SSLContextBuilder

Introduction

In this page you can find the example usage for org.apache.http.ssl SSLContextBuilder SSLContextBuilder.

Prototype

public SSLContextBuilder() 

Source Link

Usage

From source file:org.springframework.xd.shell.security.SecuredShellAccessWithSslTests.java

@Test
public void testSpringXDTemplate() throws Exception {
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "whosThere"));
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(new SSLContextBuilder()
                            .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()))
                    .build());//from   w w  w .j ava  2  s.  c o m
    SpringXDTemplate template = new SpringXDTemplate(requestFactory, new URI("https://localhost:" + adminPort));
    PagedResources<ModuleDefinitionResource> moduleDefinitions = template.moduleOperations()
            .list(RESTModuleType.sink);
    assertThat(moduleDefinitions.getLinks().size(), greaterThan(0));
}

From source file:sachin.spider.WebSpider.java

/**
 *
 * @param config/*w ww  . ja  v  a  2 s.  c  om*/
 * @param latch
 */
@SuppressWarnings("deprecation")
public void setValues(SpiderConfig config, CountDownLatch latch) {
    try {
        this.config = config;
        this.latch = latch;
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setUserAgent(config.getUserAgentString());
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws java.security.cert.CertificateException {
                return true;
            }
        }).build();
        builder.setSslcontext(sslContext);
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setDefaultMaxPerRoute(config.getTotalSpiders() * 2);
        cm.setMaxTotal(config.getTotalSpiders() * 2);
        if (config.isAuthenticate()) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(config.getUsername(), config.getPassword()));
            httpclient = HttpClients.custom().setUserAgent(config.getUserAgentString())
                    .setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(cm).build();

        } else {
            httpclient = HttpClients.custom().setConnectionManager(cm).setUserAgent(config.getUserAgentString())
                    .build();
        }
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

/**
 * no-arg constructor for client//from  ww w. ja  v a  2s .com
 */
public TankHttpClient4() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception e) {
        LOG.error("Error setting accept all: " + e, e);
    }

    httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000)
            .setCircularRedirectsAllowed(true).setAuthenticationEnabled(true).setRedirectsEnabled(true)
            .setMaxRedirects(100).build();

    // Make sure the same context is used to execute logically related
    // requests
    context = HttpClientContext.create();
    context.setCredentialsProvider(new BasicCredentialsProvider());
    context.setCookieStore(new BasicCookieStore());
    context.setRequestConfig(requestConfig);
}

From source file:org.ensembl.gti.seqstore.database.cramstore.EnaCramSubmitter.java

protected static HttpClient getHttpsClient() {
    try {/*from w  w  w . j  a v a 2  s .co  m*/
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.ow2.proactive.scheduling.api.graphql.service.AuthenticationService.java

@PostConstruct
protected void init() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    schedulerLoginFetchUrl = createLoginFetchUrl(schedulerRestUrl);

    sessionCache = CacheBuilder.newBuilder().maximumSize(Integer.parseInt(sessionCacheMaxSize))
            .expireAfterWrite(Integer.parseInt(sessionCacheExpireAfter), TimeUnit.MILLISECONDS)
            .build(new CacheLoader<String, String>() {
                @Override// w w w .j  a v a2s.c  o  m
                public String load(String sessionId) throws Exception {
                    return getLoginFromSessionId(sessionId);
                }
            });

    if (schedulerLoginFetchUrl.startsWith("https")) {
        CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        restTemplate.setRequestFactory(requestFactory);
    }

}

From source file:ph.com.globe.connect.HttpRequest.java

/**
 * Sends get request to the specified url.
 * /*  w w w  .j  a v  a2  s .  c o  m*/
 * @return CloseableHttpResponse
 * @throws HttpRequestException http request exception
 */
public CloseableHttpResponse sendGet() throws HttpRequestException {

    // try building up
    try {
        // initialize ssl context builder
        SSLContextBuilder builder = new SSLContextBuilder();

        // set trust self signed strategy
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

        // initialize ssl socket connection factory
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build());

        // default http client
        CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();

        // create request method
        HttpGet request = new HttpGet(this.url);

        // set default header
        request.setHeader("User-Agent", this.USER_AGENT);

        // try request
        try {
            // execute request and get response
            CloseableHttpResponse response = client.execute(request);

            return response;
        } catch (IOException e) {
            throw new HttpRequestException(e.getMessage());
        }
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw new HttpRequestException(e.getMessage());
    }
}

From source file:com.aliyun.api.gateway.demo.Client.java

/**
 * <br>//from   w  ww  . ja  va2s  . com
 * Client?httpsURL?keystore?storePasswordkeystore??? 
 * <a href="http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html">keytool</a>
 * 
 * @param appKey
 *            APP Key?APIAPP?
 * @param appSecret
 *            APP?APIAPP?
 * @param testEnv
 *            ?truefalse
 */
public Client(String appKey, String appSecret, boolean testEnv) {
    HttpClientBuilder builder = HttpClients.custom();
    try {
        SSLContext sslContext = null;
        if (testEnv) {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    //truetrue
                    return true;
                }
            }).build();
        } else {
            //keytool?keystorekeystore
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, null);
            sslContext = SSLContexts.custom().loadTrustMaterial(ks, new TrustSelfSignedStrategy()).build();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslsf);
    } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException | CertificateException
            | IOException e) {
        log.error(e.getMessage(), e);
    }
    httpClient = builder.setUserAgent(Constants.USER_AGENT).build();
    this.appKey = appKey;
    this.appSecret = appSecret;
    this.testEnv = testEnv;
}

From source file:com.github.tmyroadctfig.icloud4j.ICloudService.java

/**
 * Creates a new iCloud service instance
 *
 * @param clientId the client ID.//www.jav  a  2s .  co  m
 */
@SuppressWarnings("deprecation")
public ICloudService(ICloudSession session) {
    this.session = session;
    try {
        HttpClientBuilder clientBuilder = HttpClientBuilder.create().setDefaultCookieStore(getCookieStore());

        if (!Strings.isNullOrEmpty(PROXY_HOST)) {
            clientBuilder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT));
        }

        if (DISABLE_SSL_CHECKS) {
            clientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSslcontext(
                    new SSLContextBuilder().loadTrustMaterial(null, (x509CertChain, authType) -> true).build());
        }

        httpClient = clientBuilder.build();

    } catch (Exception e) {
        throw Throwables.propagate(e);
    }

    idmsaService = new IdmsaService(this);
}

From source file:com.zextras.zimbradrive.CreateTempAttachmentFileHttpHandler.java

private void doInternalPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    Account account = mBackendUtils.assertAccountFromAuthToken(httpServletRequest);
    ZimbraLog.addAccountNameToContext(account.getName());
    String path;/*from w  ww . j  av a 2  s.  c o m*/
    BufferedReader reader = httpServletRequest.getReader();
    while ((path = reader.readLine()) != null) {
        HttpResponse fileRequestResponse = mCloudHttpRequestUtils.queryCloudServerService(account, path);

        int responseCode = fileRequestResponse.getStatusLine().getStatusCode();
        if (responseCode < HTTP_LOWEST_ERROR_STATUS) {
            HttpPost post = new HttpPost(mBackendUtils.getServerServiceUrl("/service/upload?fmt=extended,raw"));
            post.setHeader(CONTENT_DISPOSITION_HTTP_HEADER, "attachment; filename=\" "
                    + convertToUnicode(path.substring(path.lastIndexOf("/") + 1)) + " \"");
            post.setHeader("Cache-Control", "no-cache");
            post.setHeader("Cookie", httpServletRequest.getHeader("Cookie"));
            post.setHeader("X-Zimbra-Csrf-Token", httpServletRequest.getHeader("X-Zimbra-Csrf-Token"));
            post.setEntity(fileRequestResponse.getEntity());

            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                        throws CertificateException {
                    return true;
                }
            });
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build());
            CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();

            HttpResponse response = client.execute(post);

            response.getEntity().writeTo(httpServletResponse.getOutputStream());
        } else {
            httpServletResponse.setStatus(responseCode);
            PrintWriter respWriter = httpServletResponse.getWriter();
            respWriter.println("Error");
            respWriter.close();
            break;
        }
    }
}

From source file:org.muhia.app.psi.integ.config.ke.shared.SharedWsClientConfiguration.java

@Bean(name = "sharedSecureHttpClient")
public CloseableHttpClient secureHttpClient() {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    try {/*ww w .  j  a  va  2 s.c  o m*/
        /*
        TODO: Modify to accept only specific certificates, test implementation is as below,
        TODO: need to find a way of determining if server url is https or not
        TODO: Whether we have imported the certificate or not
        */
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        Resource resource = loaderService.getResource(properties.getSharedKeystorePath());
        keyStore.load(resource.getInputStream(),
                hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray());
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .loadKeyMaterial(keyStore,
                        hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray())
                .build();
        //            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();

        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(properties.getSharedTransportConnectionTimeout())
                .setConnectionRequestTimeout(properties.getSharedTransportConnectionRequestTimeout())
                .setSocketTimeout(properties.getSharedTransportReadTimeout()).build();
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                sharedDataDTO.getTransportUsername(), sharedDataDTO.getTransportPassword());
        provider.setCredentials(AuthScope.ANY, credentials);

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(properties.getSharedPoolMaxHost());
        connManager.setDefaultMaxPerRoute(properties.getSharedPoolDefaultmaxPerhost());
        connManager.setValidateAfterInactivity(properties.getSharedPoolValidateAfterInactivity());
        httpClient = HttpClientBuilder.create().setSSLContext(sslContext)
                .setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultRequestConfig(config)
                .setDefaultCredentialsProvider(provider).setConnectionManager(connManager)
                .evictExpiredConnections().addInterceptorFirst(new RemoveHttpHeadersInterceptor()).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException
            | IOException | UnrecoverableKeyException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, e.getMessage(), e);
    }
    return httpClient;

}