Java Code Examples for org.apache.http.conn.ssl.SSLContextBuilder#build()

The following examples show how to use org.apache.http.conn.ssl.SSLContextBuilder#build() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PostHTTP.java    From localization_nifi with Apache License 2.0 7 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    builder = builder.useProtocol(service.getSslAlgorithm());

    final SSLContext sslContext = builder.build();
    return sslContext;
}
 
Example 2
Source File: BuildWorker.java    From anchore-container-scanner-plugin with Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient makeHttpClient(boolean verify) {
  CloseableHttpClient httpclient = null;
  if (verify) {
    httpclient = HttpClients.createDefault();
  } else {
    //SSLContextBuilder builder;

    //SSLConnectionSocketFactory sslsf=null;

    try {
      SSLContextBuilder builder = new SSLContextBuilder();
      builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
          SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  return (httpclient);
}
 
Example 3
Source File: JWTClientUtil.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * Return a http client instance
 *
 * @param protocol- service endpoint protocol http/https
 * @return
 */
public static HttpClient getHttpClient(String protocol)
		throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
	HttpClient httpclient;
	if (HTTPS_PROTOCOL.equals(protocol)) {
		SSLContextBuilder builder = new SSLContextBuilder();
		builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
		httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).useSystemProperties().build();
	} else {
		httpclient = HttpClients.createDefault();
	}
	return httpclient;
}
 
Example 4
Source File: BaseLivyInterpreter.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private SSLContext getSslContext() {
  try {
    // Build truststore
    String trustStoreFile = getProperty("zeppelin.livy.ssl.trustStore");
    String trustStorePassword = getProperty("zeppelin.livy.ssl.trustStorePassword");
    String trustStoreType = getProperty("zeppelin.livy.ssl.trustStoreType",
            KeyStore.getDefaultType());
    if (StringUtils.isBlank(trustStoreFile)) {
      throw new RuntimeException("No zeppelin.livy.ssl.trustStore specified for livy ssl");
    }
    if (StringUtils.isBlank(trustStorePassword)) {
      throw new RuntimeException("No zeppelin.livy.ssl.trustStorePassword specified " +
              "for livy ssl");
    }
    KeyStore trustStore = getStore(trustStoreFile, trustStoreType, trustStorePassword);
    SSLContextBuilder builder = SSLContexts.custom();
    builder.loadTrustMaterial(trustStore);

    // Build keystore
    String keyStoreFile = getProperty("zeppelin.livy.ssl.keyStore");
    String keyStorePassword = getProperty("zeppelin.livy.ssl.keyStorePassword");
    String keyPassword = getProperty("zeppelin.livy.ssl.keyPassword", keyStorePassword);
    String keyStoreType = getProperty("zeppelin.livy.ssl.keyStoreType",
            KeyStore.getDefaultType());
    if (StringUtils.isNotBlank(keyStoreFile)) {
      KeyStore keyStore = getStore(keyStoreFile, keyStoreType, keyStorePassword);
      builder.loadKeyMaterial(keyStore, keyPassword.toCharArray()).useTLS();
    }
    return builder.build();
  } catch (Exception e) {
    throw new RuntimeException("Failed to create SSL Context", e);
  }
}
 
Example 5
Source File: CommonHttpClientBuilder.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
protected SSLContext createSslContext() {
    try {
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(null, ACCEPT_ANY_CERTIFICATE_TRUST_STRATEGY);
        return sslContextBuilder.build();
    } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 6
Source File: UnsafeHttpsClient.java    From mobilecloud-15 with Apache License 2.0 5 votes vote down vote up
public static HttpClient createUnsafeClient() {
	try {
		SSLContextBuilder builder = new SSLContextBuilder();
		builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				builder.build());
		CloseableHttpClient httpclient = HttpClients.custom()
				.setSSLSocketFactory(sslsf).build();

		return httpclient;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 7
Source File: UnsafeHttpsClient.java    From mobilecloud-15 with Apache License 2.0 5 votes vote down vote up
public static HttpClient createUnsafeClient() {
	try {
		SSLContextBuilder builder = new SSLContextBuilder();
		builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				builder.build());
		CloseableHttpClient httpclient = HttpClients.custom()
				.setSSLSocketFactory(sslsf).build();

		return httpclient;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 8
Source File: UnsafeHttpsClient.java    From mobilecloud-15 with Apache License 2.0 5 votes vote down vote up
public static HttpClient createUnsafeClient() {
	try {
		SSLContextBuilder builder = new SSLContextBuilder();
		builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				builder.build());
		CloseableHttpClient httpclient = HttpClients.custom()
				.setSSLSocketFactory(sslsf).build();

		return httpclient;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 9
Source File: HttpUtil.java    From codehelper.generator with Apache License 2.0 4 votes vote down vote up
public static void init() throws RuntimeException {
        try {
            logger.warn(NOTICELINE + " httpUtil init begin " + NOTICELINE);
            SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
//            sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            sslContextBuilder.loadTrustMaterial(null,new TrustAnyTrustManager());
            SSLConnectionSocketFactory sslConnectionSocketFactory =
                    new SSLConnectionSocketFactory(
                            sslContextBuilder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().
                    register("http", new PlainConnectionSocketFactory()).
                    register("https", sslConnectionSocketFactory).
                    build();


            logger.warn(NOTICELINE + " SSL context init done " + NOTICELINE);

            //init connectionManager , ThreadSafe pooled conMgr
            PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
            poolingHttpClientConnectionManager.setMaxTotal(30);
            poolingHttpClientConnectionManager.setDefaultMaxPerRoute(3);
            //init request config. pooltimeout,sotime,contimeout
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(POOL_TIMECOUT).setConnectTimeout(CON_TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
            // begin construct httpclient
            HttpClientBuilder httpClientBuilder = HttpClients.custom();
            httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
            httpClientBuilder.setDefaultRequestConfig(requestConfig);
            httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() {
                @Override
                public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                    if (executionCount >= HTTP_RETRY_COUNT) {
                        return false;
                    }
                    if (exception instanceof InterruptedIOException) {
                        // Timeout
                        logger.warn("httpUtil retry for InterruptIOException");
                        return true;
                    }
                    if (exception instanceof UnknownHostException) {
                        // Unknown host
                        return false;
                    }
                    if (exception instanceof SSLException) {
                        // SSL handshake exception
                        return false;
                    }
                    HttpClientContext clientContext = HttpClientContext.adapt(context);
                    HttpRequest request = clientContext.getRequest();
                    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
                    if (idempotent) {
                        // Retry if the request is considered idempotent
                        logger.warn("httpUtil retry for idempotent");
                        return true;
                    }
                    return false;
                }
            });
            logger.warn(NOTICELINE + " poolManager , requestconfig init done " + NOTICELINE);

            httpclient = httpClientBuilder.build();
            logger.warn(NOTICELINE + " httpUtil init done " + NOTICELINE);
        } catch (Exception e) {
            logger.error(NOTICELINE + "httpclient init fail" + NOTICELINE, e);
            throw new RuntimeException(e);
        }
    }
 
Example 10
Source File: TaxiiHandler.java    From metron with Apache License 2.0 4 votes vote down vote up
private static HttpClient buildClient(URL proxy, String username, String password) throws Exception
{
  HttpClient client = new HttpClient(); // Start with a default TAXII HTTP client.

  // Create an Apache HttpClientBuilder to be customized by the command line arguments.
  HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();

  // Proxy
  if (proxy != null) {
    HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol());
    builder.setProxy(proxyHost);
  }

  // Basic authentication. User & Password
  if (username != null ^ password != null) {
    throw new Exception("'username' and 'password' arguments are required to appear together.");
  }


  // from:  http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3
  SSLContextBuilder ssbldr = new SSLContextBuilder();
  ssbldr.loadTrustMaterial(null, new TrustSelfSignedStrategy());
  SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ssbldr.build(),SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);


  Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
      .register("http", new PlainConnectionSocketFactory())
      .register("https", sslsf)
      .build();


  PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
  cm.setMaxTotal(20);//max connection

  System.setProperty("jsse.enableSNIExtension", "false"); //""
  CloseableHttpClient httpClient = builder
      .setSSLSocketFactory(sslsf)
      .setConnectionManager(cm)
      .build();

  client.setHttpclient(httpClient);
  return client;
}