Java Examples for org.apache.http.conn.ssl.SSLContexts

The following java examples will help you to understand the usage of org.apache.http.conn.ssl.SSLContexts. These source code samples are taken from different open source projects.

Example 1
Project: ecf-master  File: SNIAwareHttpClient.java View source code
@Override
protected ClientConnectionManager createClientConnectionManager() {
    SSLSocketFactory factory = new SSLSocketFactory(SSLContexts.createSystemDefault(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER) {

        @Override
        public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException, ConnectTimeoutException {
            // https://bugs.eclipse.org/bugs/show_bug.cgi?id=478655
            if (socket instanceof SSLSocket) {
                try {
                    final Method mSetHost = socket.getClass().getMethod("setHost", String.class);
                    mSetHost.setAccessible(true);
                    mSetHost.invoke(socket, host.getHostName());
                } catch (NoSuchMethodException ex) {
                } catch (IllegalAccessException ex) {
                } catch (InvocationTargetException ex) {
                } catch (RuntimeException ex) {
                }
            }
            return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
        }
    };
    final SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    registry.register(new Scheme("https", 443, factory));
    return new BasicClientConnectionManager(registry);
}
Example 2
Project: MOCBuilder-master  File: OrderDetails.java View source code
public static void main(String[] args) throws Exception {
    Configuration configuration = new Configuration();
    OAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(configuration.getProperty(ConfigurationProperty.CONSUMER_KEY), configuration.getProperty(ConfigurationProperty.CONSUMER_SECRET));
    oAuthConsumer.setTokenWithSecret(configuration.getProperty(ConfigurationProperty.TOKEN_VALUE), configuration.getProperty(ConfigurationProperty.TOKEN_SECRET));
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustAllStrategy()).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpGet request = new HttpGet(BASE_URL + "/orders/1234567");
        oAuthConsumer.sign(request);
        CloseableHttpResponse httpResponse = client.execute(request);
        try {
            System.out.println("Code: " + httpResponse.getStatusLine().getStatusCode() + ',' + httpResponse.getStatusLine().getReasonPhrase());
            InputStream stream = httpResponse.getEntity().getContent();
            ObjectMapper mapper = new ObjectMapper();
            ResponseDT<List<OrderDT>> response = mapper.readValue(stream, new TypeReference<ResponseDT<OrderDT>>() {
            });
            System.out.println(response);
        } finally {
            httpResponse.close();
        }
    } finally {
        client.close();
    }
}
Example 3
Project: chaos-lemur-master  File: StandardDirectorUtils.java View source code
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555), new UsernamePasswordCredentials(username, password));
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(connectionFactory).build();
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    restTemplate.getInterceptors().addAll(interceptors);
    return restTemplate;
}
Example 4
Project: geni-openflow-vertical-handover-master  File: ClientConfiguration.java View source code
public static final void main(String[] args) throws Exception {
    // Use custom message parser / writer to customize the way HTTP
    // messages are parsed from and written out to the data stream.
    HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {

        @Override
        public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer, MessageConstraints constraints) {
            LineParser lineParser = new BasicLineParser() {

                @Override
                public Header parseHeader(final CharArrayBuffer buffer) {
                    try {
                        return super.parseHeader(buffer);
                    } catch (ParseException ex) {
                        return new BasicHeader(buffer.toString(), null);
                    }
                }
            };
            return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints) {

                @Override
                protected boolean reject(final CharArrayBuffer line, int count) {
                    // try to ignore all garbage preceding a status line infinitely
                    return false;
                }
            };
        }
    };
    HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();
    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(requestWriterFactory, responseParserFactory);
    // Client HTTP connection objects when fully initialized can be bound to
    // an arbitrary network socket. The process of network socket initialization,
    // its connection to a remote address and binding to a local one is controlled
    // by a connection socket factory.
    // SSL context for secure connections can be created either based on
    // system or application specific properties.
    SSLContext sslcontext = SSLContexts.createSystemDefault();
    // Use custom hostname verifier to customize SSL hostname verification.
    X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();
    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();
    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {

        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("myhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return super.resolve(host);
            }
        }
    };
    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connFactory, dnsResolver);
    // Create socket configuration
    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    connManager.setDefaultSocketConfig(socketConfig);
    connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);
    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).setMessageConstraints(messageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    connManager.setDefaultConnectionConfig(connectionConfig);
    connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);
    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(10);
    connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);
    // Use custom cookie store if necessary.
    CookieStore cookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // Create global request configuration
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credentialsProvider).setProxy(new HttpHost("myproxy", 8080)).setDefaultRequestConfig(defaultRequestConfig).build();
    try {
        HttpGet httpget = new HttpGet("http://www.apache.org/");
        // Request configuration can be overridden at the request level.
        // They will take precedence over the one set at the client level.
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).setProxy(new HttpHost("myotherproxy", 8080)).build();
        httpget.setConfig(requestConfig);
        // Execution context can be customized locally.
        HttpClientContext context = HttpClientContext.create();
        // Contextual attributes set the local context level will take
        // precedence over those set at the client level.
        context.setCookieStore(cookieStore);
        context.setCredentialsProvider(credentialsProvider);
        System.out.println("executing request " + httpget.getURI());
        CloseableHttpResponse response = httpclient.execute(httpget, context);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            System.out.println("----------------------------------------");
            // Once the request has been executed the local context can
            // be used to examine updated state and various objects affected
            // by the request execution.
            // Last executed request
            context.getRequest();
            // Execution route
            context.getHttpRoute();
            // Target auth state
            context.getTargetAuthState();
            // Proxy auth state
            context.getTargetAuthState();
            // Cookie origin
            context.getCookieOrigin();
            // Cookie spec used
            context.getCookieSpec();
            // User security token
            context.getUserToken();
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}
Example 5
Project: RipplePower-master  File: TestNames.java View source code
public static void main(String[] args) throws Exception {
    // History h=new History("rKiCet8SdvWxPXnAgYarFUXMh1zCPz432Y");
    // System.out.println(h.getUrl());
    System.out.println(NameFind.getAddress("ripplefox"));
// System.out.println(NameFind.getAddress("baidutest"));
// HttpRequest
// req=HttpRequest.get("https://id.staging.ripple.com/v1/user/testUser");
// System.out.println(req.cookies());
// System.out.println(req.ok());
/*
		 * KeyStore trustStore =
		 * KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream
		 * instream = new FileInputStream(new File("my.keystore")); try {
		 * trustStore.load(instream, "nopassword".toCharArray()); } finally {
		 * instream.close(); } // Trust own CA and all self-signed certs
		 * SSLContext sslcontext = SSLContexts.custom()
		 * .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
		 * .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory
		 * sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] {
		 * "TLSv1" }, null,
		 * SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
		 */
}
Example 6
Project: serengeti-ws-master  File: DistroManager.java View source code
/*
   public List<DistroRead> getPluginSupportDistro(String appManager) {
      SoftwareManager softwareManager =
            softwareManagerCollector.getSoftwareManager(appManager);
      if (softwareManager == null) {
         logger.error("Failed to get softwareManger.");
         throw ClusterConfigException.FAILED_TO_GET_SOFTWARE_MANAGER(appManager);
      }
      List<HadoopStack> hadoopStacks = softwareManager.getSupportedStacks();
      if (hadoopStacks != null && hadoopStacks.size() > 0) {
         List<DistroRead> distros = new ArrayList<DistroRead>();
         for (HadoopStack hadoopStack : hadoopStacks) {
            DistroRead distro = new DistroRead();
            distro.setName(hadoopStack.getDistro());
            distro.setVendor(hadoopStack.getVendor());
            distro.setVersion(hadoopStack.getFullVersion());
            distros.add(distro);
         }
         return distros;
      }
      return null;
   }*/
/*
    * Return the content of distro manifest file.
    * Return null if the content is not changed since last visit.
    */
@SuppressWarnings("deprecation")
private String readDistroManifest() throws Exception {
    File manifestFile = new File(DISTRO_MANIFEST_FILE_PATH);
    if (manifestFile.exists()) {
        // No need to reload the file if it's not modified.
        if (lastModified != manifestFile.lastModified()) {
            lastModified = manifestFile.lastModified();
            logger.info("last modified date of manifest file changed. Reloading manifest.");
        } else {
            return null;
        }
    }
    BufferedReader in = null;
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        SSLContext sslContext = SSLContexts.custom().useTLS().build();
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return;
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } }, null);
        TlsClientConfiguration tlsConfiguration = new TlsClientConfiguration();
        SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, tlsConfiguration.getSslProtocols(), tlsConfiguration.getCipherSuites(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        HttpGet httpget = new HttpGet(new URI(distrosManifestUrl));
        if (eTag != null) {
            httpget.addHeader("If-None-Match", eTag);
        }
        logger.info("executing request: " + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        if (!manifestFile.exists()) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
                return null;
            } else {
                logger.debug("ETag of manifest file changed. Reloading manifest.");
                eTag = response.getFirstHeader("ETag").getValue();
                ;
            }
        }
        HttpEntity entity = response.getEntity();
        in = new BufferedReader(new InputStreamReader(entity.getContent()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        EntityUtils.consume(entity);
        return sb.toString();
    } finally {
        httpclient.getConnectionManager().shutdown();
        if (in != null) {
            in.close();
        }
    }
}
Example 7
Project: categolj2-backend-master  File: EntryRestControllerIntegrationTest.java View source code
@Before
public void setUp() throws Exception {
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
    sockectFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    // clean data
    entryRepository.deleteAll();
    userRepository.deleteAll();
    roleRepository.deleteAll();
    tagRepository.deleteAll();
    entryRepository.flush();
    // initialize user
    Role adminRole = new Role(100, "ADMIN", null);
    Role editorRole = new Role(200, "EDITOR", null);
    roleRepository.save(Arrays.asList(adminRole, editorRole));
    roleRepository.flush();
    admin = new User("admin", passwordEncoder.encode("demo"), "admin@a.b", true, false, "Tarou", "Yamada", Sets.newHashSet(roleRepository.findOneByRoleName("ADMIN")));
    editor = new User("editor", passwordEncoder.encode("demo"), "editor@a.b", true, false, "Ichiro", "Suzuki", Sets.newHashSet(roleRepository.findOneByRoleName("EDITOR")));
    userRepository.save(Arrays.asList(admin, editor));
    userRepository.flush();
    // initialize entry
    entry1 = new Entry(null, "This is entry1!", "**Hello World1!**", "md", Arrays.asList(), true, Arrays.asList(), Collections.<Tag>emptySet());
    entry1.setCreatedBy("admin");
    entry1.setCreatedDate(now);
    entry1.setLastModifiedBy("admin");
    entry1.setLastModifiedDate(now);
    entry1 = entryRepository.saveAndFlush(entry1);
    entry1.setCategory(Categories.fromCategory("aa::bb::cc").getCategories());
    entry1.getCategory().stream().forEach( c -> c.getCategoryPK().setEntryId(entry1.getEntryId()));
    entry1.setTags(Sets.newHashSet(new Tag("Java"), new Tag("Spring")));
    entry2 = new Entry(null, "This is entry2!", "**Hello World2!**", "md", Arrays.asList(), false, Arrays.asList(), Collections.<Tag>emptySet());
    entry2.setCreatedBy("admin");
    entry2.setCreatedDate(now.plus(2));
    entry2.setLastModifiedBy("admin");
    entry2.setLastModifiedDate(now.plus(2));
    entry2 = entryRepository.saveAndFlush(entry2);
    entry2.setCategory(Categories.fromCategory("aa::bb::cc").getCategories());
    entry2.getCategory().stream().forEach( c -> c.getCategoryPK().setEntryId(entry2.getEntryId()));
    entry2.setTags(Sets.newHashSet(new Tag("Java"), new Tag("Java EE")));
    entry3 = new Entry(null, "This is entry3!", "**Hello World3!**", "md", Arrays.asList(), true, Arrays.asList(), Collections.<Tag>emptySet());
    entry3.setCreatedBy("editor");
    entry3.setCreatedDate(now.plus(3));
    entry3.setLastModifiedBy("editor");
    entry3.setLastModifiedDate(now.plus(3));
    entry3 = entryRepository.saveAndFlush(entry3);
    entry3.setCategory(Categories.fromCategory("aa::bb::cc").getCategories());
    entry3.getCategory().stream().forEach( c -> c.getCategoryPK().setEntryId(entry3.getEntryId()));
    entry3.setTags(Sets.newHashSet(new Tag("Java"), new Tag("Java SE")));
    entry4 = new Entry(null, "This is entry4!", "<h1>Hello World4!</h1>", "html", Arrays.asList(), true, Arrays.asList(), Collections.<Tag>emptySet());
    entry4.setCreatedBy("editor");
    entry4.setCreatedDate(now.plus(4));
    entry4.setLastModifiedBy("editor");
    entry4.setLastModifiedDate(now.plus(4));
    entry4 = entryRepository.saveAndFlush(entry4);
    entry4.setCategory(Categories.fromCategory("aa::bb::cc").getCategories());
    entry4.getCategory().stream().forEach( c -> c.getCategoryPK().setEntryId(entry4.getEntryId()));
    entry5 = new Entry(null, "This is entry5!", "**Foo World5!**", "md", Arrays.asList(), true, Arrays.asList(), Collections.<Tag>emptySet());
    entry5.setCreatedBy("editor");
    entry5.setCreatedDate(now.plus(5));
    entry5.setLastModifiedBy("editor");
    entry5.setLastModifiedDate(now.plus(5));
    entry5 = entryRepository.saveAndFlush(entry5);
    entry5.setCategory(Categories.fromCategory("aa::bb::dd::ee").getCategories());
    entry5.getCategory().stream().forEach( c -> c.getCategoryPK().setEntryId(entry5.getEntryId()));
    entryRepository.save(Arrays.asList(entry1, entry2, entry3, entry4, entry5));
    RestAssured.port = port;
    RestAssured.baseURI = "https://localhost";
    RestAssured.config = RestAssuredConfig.newConfig().sslConfig(new SSLConfig().sslSocketFactory(sockectFactory));
}
Example 8
Project: ddf-master  File: HttpSolrClientFactory.java View source code
private static SSLContext getSslContext() {
    if (//
    System.getProperty("javax.net.ssl.keyStore") == null || //
    System.getProperty("javax.net.ssl.keyStorePassword") == null || //
    System.getProperty("javax.net.ssl.trustStore") == null || System.getProperty("javax.net.ssl.trustStorePassword") == null) {
        throw new IllegalArgumentException("KeyStore and TrustStore system properties must be set.");
    }
    KeyStore trustStore = getKeyStore(System.getProperty("javax.net.ssl.trustStore"), System.getProperty("javax.net.ssl.trustStorePassword"));
    KeyStore keyStore = getKeyStore(System.getProperty("javax.net.ssl.keyStore"), System.getProperty("javax.net.ssl.keyStorePassword"));
    SSLContext sslContext = null;
    try {
        sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, System.getProperty("javax.net.ssl.keyStorePassword").toCharArray()).loadTrustMaterial(trustStore).useTLS().build();
    } catch (UnrecoverableKeyExceptionNoSuchAlgorithmException | KeyStoreException | KeyManagementException |  e) {
        throw new IllegalArgumentException("Unable to use javax.net.ssl.keyStorePassword to load key material to create SSL context for Solr client.");
    }
    sslContext.getDefaultSSLParameters().setNeedClientAuth(true);
    sslContext.getDefaultSSLParameters().setWantClientAuth(true);
    return sslContext;
}
Example 9
Project: openmicroscopy-master  File: HtmlMessenger.java View source code
/**
     * Creates a connection.
     *
     * @return See above
     * @throws HtmlMessengerException Thrown if an error occurred while creating the
     *                            SSL context.
     */
private SSLConnectionSocketFactory createSSLConnection() throws HtmlMessengerException {
    SSLContext sslcontext = SSLContexts.createSystemDefault();
    final TrustManager trustEverything = new X509TrustManager() {

        private final X509Certificate[] acceptedIssuers = new X509Certificate[0];

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return this.acceptedIssuers;
        }
    };
    TrustManager[] managers = { trustEverything };
    try {
        sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, managers, null);
    } catch (Exception e) {
        new HtmlMessengerException("Cannot create security context", e);
    }
    return new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
}
Example 10
Project: pay-master  File: WechatPayClient.java View source code
//判断是�需�带上 支付�书
private <T extends WechatPayResponse> CloseableHttpClient getClient(WechatPayRequest<? extends WechatPayModel, T> request) throws WechatPayException {
    CloseableHttpClient client;
    if (request.requireCert()) {
        try {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            ByteArrayInputStream inputStream = new ByteArrayInputStream(certFile);
            try {
                keyStore.load(inputStream, this.mchId.toCharArray());
            } finally {
                inputStream.close();
            }
            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, this.mchId.toCharArray()).build();
            SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            client = HttpClients.custom().setSSLSocketFactory(factory).build();
        } catch (Exception e) {
            throw new WechatPayException(e);
        }
    } else {
        client = HttpClients.createDefault();
    }
    return client;
}
Example 11
Project: weixin-pay-master  File: HttpsRequest.java View source code
private void init() throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    //加载本地的�书进行https加密传输
    FileInputStream instream = new FileInputStream(new File(Configure.getCertLocalPath()));
    try {
        //设置�书密�
        keyStore.load(instream, Configure.getCertPassword().toCharArray());
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } finally {
        instream.close();
    }
    @SuppressWarnings("deprecation") SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, Configure.getCertPassword().toCharArray()).build();
    @SuppressWarnings("deprecation") SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
    hasInit = true;
}
Example 12
Project: weixin-popular-master  File: HttpClientFactory.java View source code
/**
	 * 
	 * @param maxTotal maxTotal
	 * @param maxPerRoute maxPerRoute
	 * @param timeout timeout
	 * @param retryExecutionCount retryExecutionCount
	 * @return CloseableHttpClient
	 */
public static CloseableHttpClient createHttpClient(int maxTotal, int maxPerRoute, int timeout, int retryExecutionCount) {
    try {
        SSLContext sslContext = SSLContexts.custom().useSSL().build();
        SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
        poolingHttpClientConnectionManager.setMaxTotal(maxTotal);
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPerRoute);
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
        poolingHttpClientConnectionManager.setDefaultSocketConfig(socketConfig);
        return HttpClientBuilder.create().setConnectionManager(poolingHttpClientConnectionManager).setSSLSocketFactory(sf).setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount)).build();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}
Example 13
Project: antiope-master  File: DefaultHttpClientFactory.java View source code
@Override
public HttpClient createHttpClient(APIConfiguration pConfiguration) {
    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> oConnFactory = new ManagedHttpClientConnectionFactory(new DefaultHttpRequestWriterFactory(), new DefaultHttpResponseParserFactory());
    SSLContext oSslContext = null;
    X509HostnameVerifier oHostnameVerifier = null;
    if (pConfiguration.isCheckSSLCertificates()) {
        oSslContext = SSLContexts.createSystemDefault();
        oHostnameVerifier = new BrowserCompatHostnameVerifier();
    } else {
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        // Install the all-trusting trust manager
        try {
            final SSLContext sslContext = SSLContext.getInstance(SSL);
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            //final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            oSslContext = sslContext;
        } catch (NoSuchAlgorithmException e) {
            throw new APIClientException(e);
        } catch (KeyManagementException e) {
            throw new APIClientException(e);
        }
        oHostnameVerifier = new AllowAllHostnameVerifier();
    }
    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> oSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(HTTP, PlainConnectionSocketFactory.INSTANCE).register(HTTPS, new SSLConnectionSocketFactory(oSslContext, oHostnameVerifier)).build();
    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver oDnsResolver = new SystemDefaultDnsResolver();
    /* {
			@Override
			public InetAddress[] resolve(final String host) throws UnknownHostException {
				if (host.equalsIgnoreCase("myhost")) {
					return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
				} else {
					return super.resolve(host);
				}
			}
		};*/
    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager oConnManager = new PoolingHttpClientConnectionManager(oSocketFactoryRegistry, oConnFactory, oDnsResolver);
    // Create socket configuration
    SocketConfig oSocketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(pConfiguration.getSocketTimeout()).build();
    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    oConnManager.setDefaultSocketConfig(oSocketConfig);
    // connManager.setSocketConfig(new HttpHost("somehost", 80), oSocketConfig);
    // Create message constraints
    MessageConstraints oMessageConstraints = MessageConstraints.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig oConnectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).setMessageConstraints(oMessageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    oConnManager.setDefaultConnectionConfig(oConnectionConfig);
    // connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);
    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    oConnManager.setMaxTotal(100);
    oConnManager.setDefaultMaxPerRoute(10);
    //oConnManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);
    // Use custom cookie store if necessary.
    CookieStore oCookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    //
    // Create global request configuration
    RequestConfig oDefaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).setStaleConnectionCheckEnabled(//.setExpectContinueEnabled(true)			// WARNING: setting it to true slows things down by 4s!!!!
    true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectTimeout(pConfiguration.getConnectionTimeout()).build();
    CredentialsProvider oCredentialsProvider = new BasicCredentialsProvider();
    HttpHost oProxy = null;
    if (pConfiguration.getProxyHost() != null && pConfiguration.getProxyPort() > 0) {
        String proxyHost = pConfiguration.getProxyHost();
        int proxyPort = pConfiguration.getProxyPort();
        String proxyUsername = pConfiguration.getProxyUsername();
        String proxyPassword = pConfiguration.getProxyPassword();
        String proxyDomain = pConfiguration.getProxyDomain();
        String proxyWorkstation = pConfiguration.getProxyWorkstation();
        oProxy = new HttpHost(proxyHost, proxyPort);
        if (proxyUsername != null && proxyPassword != null) {
            oCredentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }
    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient oHttpClient = HttpClients.custom().setConnectionManager(oConnManager).setDefaultCookieStore(oCookieStore).setDefaultCredentialsProvider(oCredentialsProvider).setProxy(oProxy).setDefaultRequestConfig(oDefaultRequestConfig).build();
    return oHttpClient;
/*
		RequestConfig oRequestConfig = RequestConfig.custom()
				.setConnectTimeout(pConfiguration.getConnectionTimeout())
				.setSocketTimeout(pConfiguration.getSocketTimeout())
				.setStaleConnectionCheckEnabled(true)
				.build();
		*/
}
Example 14
Project: comsat-master  File: FiberHttpClientBuilder.java View source code
private static Registry<SchemeIOSessionStrategy> convertRegistry(final SchemeRegistry oldRegistry) throws SSLInitializationException {
    SchemeRegistry baseRegistry = oldRegistry;
    //TODO: use values from old registry;
    Registry<SchemeIOSessionStrategy> defaultRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE).register("https", new SSLIOSessionStrategy(SSLContexts.createDefault(), null, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER)).build();
    return defaultRegistry;
}
Example 15
Project: jOCCI-api-master  File: HTTPAuthentication.java View source code
/**
     * Creates a ssl context with custom CAs if set.
     *
     * @return ssl context
     * @throws AuthenticationException
     */
protected SSLContext createSSLContext() throws AuthenticationException {
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = loadCAs();
    try {
        SSLContext sslContext;
        if (keyStore == null) {
            sslContext = SSLContexts.createSystemDefault();
        } else {
            sslContext = SSLContexts.custom().loadTrustMaterial(keyStore).build();
        }
        return sslContext;
    } catch (NoSuchAlgorithmExceptionKeyStoreException | KeyManagementException |  ex) {
        throw new AuthenticationException(ex);
    }
}
Example 16
Project: jqm-master  File: JdbcClient.java View source code
private InputStream getFile(String url) {
    DbConn cnx = getDbSession();
    File file = null;
    FileOutputStream fos = null;
    CloseableHttpClient cl = null;
    CloseableHttpResponse rs = null;
    String nameHint = null;
    File destDir = new File(System.getProperty("java.io.tmpdir"));
    if (!destDir.isDirectory() && !destDir.mkdir()) {
        throw new JqmClientException("could not create temp directory " + destDir.getAbsolutePath());
    }
    jqmlogger.trace("File will be copied into " + destDir);
    try {
        file = new File(destDir + "/" + UUID.randomUUID().toString());
        CredentialsProvider credsProvider = null;
        if (SimpleApiSecurity.getId(cnx).usr != null) {
            credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(SimpleApiSecurity.getId(cnx).usr, SimpleApiSecurity.getId(cnx).pass));
        }
        SSLContext ctx = null;
        if (getFileProtocol(cnx).equals("https://")) {
            try {
                if (p.containsKey("com.enioka.jqm.ws.truststoreFile")) {
                    KeyStore trust = null;
                    InputStream trustIs = null;
                    try {
                        trust = KeyStore.getInstance(this.p.getProperty("com.enioka.jqm.ws.truststoreType", "JKS"));
                    } catch (KeyStoreException e) {
                        throw new JqmInvalidRequestException("Specified trust store type [" + this.p.getProperty("com.enioka.jqm.ws.truststoreType", "JKS") + "] is invalid", e);
                    }
                    try {
                        trustIs = new FileInputStream(this.p.getProperty("com.enioka.jqm.ws.truststoreFile"));
                    } catch (FileNotFoundException e) {
                        throw new JqmInvalidRequestException("Trust store file [" + this.p.getProperty("com.enioka.jqm.ws.truststoreFile") + "] cannot be found", e);
                    }
                    String trustp = this.p.getProperty("com.enioka.jqm.ws.truststorePass", null);
                    try {
                        trust.load(trustIs, (trustp == null ? null : trustp.toCharArray()));
                    } catch (Exception e) {
                        throw new JqmInvalidRequestException("Could not load the trust store file", e);
                    } finally {
                        try {
                            trustIs.close();
                        } catch (IOException e) {
                        }
                    }
                    ctx = SSLContexts.custom().loadTrustMaterial(trust).build();
                } else {
                    ctx = SSLContexts.createSystemDefault();
                }
            } catch (Exception e) {
                jqmlogger.error("An supposedly impossible error has happened. Downloading files through the API may not work.", e);
            }
        }
        cl = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).setSslcontext(ctx).build();
        // Run HTTP request
        HttpUriRequest rq = new HttpGet(url.toString());
        rs = cl.execute(rq);
        if (rs.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new JqmClientException("Could not retrieve file from JQM node. The file may have been purged, or the node may be unreachable. HTTP code was: " + rs.getStatusLine().getStatusCode());
        }
        // There may be a filename hint inside the response
        Header[] hs = rs.getHeaders("Content-Disposition");
        if (hs.length == 1) {
            Header h = hs[0];
            if (h.getValue().contains("filename=")) {
                nameHint = h.getValue().split("=")[1];
            }
        }
        // Save the file to a temp local file
        fos = new FileOutputStream(file);
        rs.getEntity().writeTo(fos);
        jqmlogger.trace("File was downloaded to " + file.getAbsolutePath());
    } catch (IOException e) {
        throw new JqmClientException("Could not create a webserver-local copy of the file. The remote node may be down. " + url, e);
    } finally {
        closeQuietly(cnx);
        closeQuietly(fos);
        closeQuietly(rs);
        closeQuietly(cl);
    }
    SelfDestructFileStream res = null;
    try {
        res = new SelfDestructFileStream(file);
    } catch (IOException e) {
        throw new JqmClientException("File seems not to be present where it should have been downloaded", e);
    }
    res.nameHint = nameHint;
    return res;
}
Example 17
Project: Rap-ID-Android-master  File: HttpUtil.java View source code
private static CloseableHttpClient getHttpClient() {
    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
    ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
    registryBuilder.register("http", plainSF);
    //指定信任密钥存储对象和连接套接字工厂
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        //信任任何链接
        TrustStrategy anyTrustStrategy = new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        };
        SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
        LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registryBuilder.register("https", sslSF);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    Registry<ConnectionSocketFactory> registry = registryBuilder.build();
    //设置连接管�器
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
    //构建客户端
    return HttpClientBuilder.create().setConnectionManager(connManager).build();
}
Example 18
Project: zeppelin-master  File: BaseLivyInterpreter.java View source code
private RestTemplate createRestTemplate() {
    HttpClient httpClient = null;
    if (livyURL.startsWith("https:")) {
        String keystoreFile = property.getProperty("zeppelin.livy.ssl.trustStore");
        String password = property.getProperty("zeppelin.livy.ssl.trustStorePassword");
        if (StringUtils.isBlank(keystoreFile)) {
            throw new RuntimeException("No zeppelin.livy.ssl.trustStore specified for livy ssl");
        }
        if (StringUtils.isBlank(password)) {
            throw new RuntimeException("No zeppelin.livy.ssl.trustStorePassword specified " + "for livy ssl");
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(keystoreFile);
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(keystoreFile), password.toCharArray());
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
            httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create SSL HttpClient", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.error("Failed to close keystore file", e);
                }
            }
        }
    }
    String keytabLocation = property.getProperty("zeppelin.livy.keytab");
    String principal = property.getProperty("zeppelin.livy.principal");
    if (StringUtils.isNotEmpty(keytabLocation) && StringUtils.isNotEmpty(principal)) {
        if (httpClient == null) {
            return new KerberosRestTemplate(keytabLocation, principal);
        } else {
            return new KerberosRestTemplate(keytabLocation, principal, httpClient);
        }
    }
    if (httpClient == null) {
        return new RestTemplate();
    } else {
        return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    }
}
Example 19
Project: coprhd-controller-master  File: WinRMTarget.java View source code
private HttpClientConnectionManager createClientConnectionManager() throws Exception {
    SSLContextBuilder contextBuilder = SSLContexts.custom();
    try {
        contextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
        return (new PoolingHttpClientConnectionManager(registry));
    } catch (Exception e) {
        throw new HttpException(e.getMessage());
    }
}
Example 20
Project: funiture-master  File: HttpUtil.java View source code
/**
     * 缺�connectionManager
     *
     * @return
     */
public static PoolingHttpClientConnectionManager getPoolingClientConnectionManager() {
    try {
        SSLContext sslContext = SSLContexts.custom().useTLS().build();
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } }, null);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslContext)).build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
        connManager.setDefaultSocketConfig(socketConfig);
        ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).build();
        connManager.setDefaultConnectionConfig(connectionConfig);
        return connManager;
    } catch (Exception e) {
        log.error("build client connection manager failed", e);
        throw new RuntimeException(e);
    }
}
Example 21
Project: jvarkit-master  File: VcfAnnotWithBeacon.java View source code
@Override
protected int doVcfToVcf(String inputName, final VcfIterator iter, final VariantContextWriter out) {
    CloseableHttpClient httpClient = null;
    InputStream contentInputStream = null;
    try {
        final org.apache.http.impl.client.HttpClientBuilder hb = HttpClients.custom();
        if (this.ignoreCertErrors) {
            // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error
            System.setProperty("jsse.enableSNIExtension", "false");
            final SSLContext sslContext = org.apache.http.conn.ssl.SSLContexts.custom().loadTrustMaterial(null, new org.apache.http.conn.ssl.TrustStrategy() {

                @Override
                public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
                    return true;
                }
            }).useTLS().build();
            final org.apache.http.conn.ssl.SSLConnectionSocketFactory connectionFactory = new org.apache.http.conn.ssl.SSLConnectionSocketFactory(sslContext, new org.apache.http.conn.ssl.AllowAllHostnameVerifier());
            hb.setSSLSocketFactory(connectionFactory);
        }
        httpClient = hb.build();
        HttpGet httpGetRequest = null;
        final Set<String> available_chromosomes = new HashSet<>();
        try {
            httpGetRequest = new HttpGet(baseurl + "/chromosomes");
            httpGetRequest.setHeader("Accept", ContentType.APPLICATION_JSON.getMimeType());
            contentInputStream = httpClient.execute(httpGetRequest).getEntity().getContent();
            JsonParser jsonparser = new JsonParser();
            final JsonElement root = jsonparser.parse(new InputStreamReader(contentInputStream));
            Iterator<JsonElement> jsr = root.getAsJsonArray().iterator();
            while (jsr.hasNext()) {
                final String ctg = jsr.next().getAsString();
                available_chromosomes.add(ctg);
            }
            LOG.debug(available_chromosomes);
        } catch (final Exception err) {
            LOG.error(err);
            return -1;
        } finally {
            CloserUtil.close(contentInputStream);
        }
        final Set<String> available_alleles = new HashSet<>();
        try {
            httpGetRequest = new HttpGet(baseurl + "/alleles");
            httpGetRequest.setHeader("Accept", ContentType.APPLICATION_JSON.getMimeType());
            contentInputStream = httpClient.execute(httpGetRequest).getEntity().getContent();
            JsonParser jsonparser = new JsonParser();
            final JsonElement root = jsonparser.parse(new InputStreamReader(contentInputStream));
            Iterator<JsonElement> jsr = root.getAsJsonArray().iterator();
            while (jsr.hasNext()) {
                final String allele = jsr.next().getAsString();
                available_alleles.add(allele);
            }
            LOG.debug(available_alleles);
        } catch (final Exception err) {
            LOG.error(err);
            return -1;
        } finally {
            CloserUtil.close(contentInputStream);
        }
        final StoredResponseBinding storedResponseBinding = new StoredResponseBinding();
        final VCFHeader header = new VCFHeader(iter.getHeader());
        final VCFInfoHeaderLine infoHeaderLine = new VCFInfoHeaderLine(this.infoTag, VCFHeaderLineCount.UNBOUNDED, VCFHeaderLineType.String, "Tag inserted with " + getProgramName());
        header.addMetaDataLine(infoHeaderLine);
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry data = new DatabaseEntry();
        out.writeHeader(header);
        while (iter.hasNext()) {
            final VariantContext ctx = iter.next();
            if (!ctx.isVariant() || ctx.getReference().isSymbolic()) {
                out.add(ctx);
                continue;
            }
            if (ctx.hasAttribute(infoHeaderLine.getID()) && this.dontUpdateIfInfoIsPresent) {
                out.add(ctx);
                continue;
            }
            String beaconContig = ctx.getContig();
            if (!available_chromosomes.contains(beaconContig)) {
                if (beaconContig.startsWith("chr")) {
                    beaconContig = beaconContig.substring(3);
                }
                if (!available_chromosomes.contains(beaconContig)) {
                    out.add(ctx);
                    continue;
                }
            }
            final List<Allele> altAlleles = ctx.getAlternateAlleles();
            if (altAlleles.isEmpty()) {
                out.add(ctx);
                continue;
            }
            final Set<String> newInfo = new HashSet<>();
            for (final Allele alt : altAlleles) {
                if (alt.isSymbolic() || alt.isNoCall())
                    continue;
                final StringBuilder buildUrl = new StringBuilder();
                buildUrl.append("chrom=");
                buildUrl.append(URLEncoder.encode(beaconContig, "UTF-8"));
                buildUrl.append("&pos=");
                /*
					 * "Coordinate within a chromosome. Position is a number and is 0-based"
					 * .
					 */
                buildUrl.append(ctx.getStart() - 1);
                buildUrl.append("&allele=");
                final String allele;
                if (ctx.getReference().length() > alt.length()) {
                    // del
                    allele = "D";
                } else if (ctx.getReference().length() > alt.length()) {
                    // ins
                    allele = "I";
                } else {
                    allele = alt.getDisplayString();
                }
                if (!available_alleles.contains(allele))
                    continue;
                buildUrl.append(allele);
                buildUrl.append("&ref=");
                buildUrl.append(URLEncoder.encode(this.genomeBuild, "UTF-8"));
                final String queryUrl = buildUrl.toString();
                boolean foundInBdb = false;
                Set<String> foundIn = null;
                if (this.beaconDatabase != null) {
                    StringBinding.stringToEntry(queryUrl, key);
                    if (this.beaconDatabase.get(this.txn, key, data, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
                        StoredResponse response = storedResponseBinding.entryToObject(data);
                        if (// TODO check how old is
                        response.timeStamp < 0) // that data
                        {
                            response = null;
                            this.beaconDatabase.delete(this.txn, key);
                        }
                        if (response != null) {
                            foundInBdb = true;
                            foundIn = response.foundIn;
                        }
                    }
                }
                if (foundIn == null) {
                    foundIn = new HashSet<>();
                    try {
                        httpGetRequest = new HttpGet(baseurl + "/responses?" + queryUrl);
                        httpGetRequest.setHeader("Accept", ContentType.APPLICATION_JSON.getMimeType());
                        LOG.debug(httpGetRequest.getURI());
                        contentInputStream = httpClient.execute(httpGetRequest).getEntity().getContent();
                        JsonParser jsonparser = new JsonParser();
                        final JsonElement root = jsonparser.parse(new InputStreamReader(contentInputStream));
                        Iterator<JsonElement> jsr = root.getAsJsonArray().iterator();
                        while (jsr.hasNext()) {
                            final JsonObject b = jsr.next().getAsJsonObject();
                            if (!(b.has("beacon") && b.has("response")))
                                continue;
                            final String beacon_id = b.get("beacon").getAsJsonObject().get("id").getAsString();
                            final JsonElement response_prim = b.get("response");
                            if (response_prim.isJsonPrimitive() && response_prim.getAsBoolean()) {
                                foundIn.add(beacon_id);
                            }
                        }
                    } catch (final Exception err) {
                        LOG.error(err);
                        if (stopOnNetworkError) {
                            throw new RuntimeIOException(err);
                        }
                    } finally {
                        CloserUtil.close(contentInputStream);
                    }
                }
                if (this.beaconDatabase != null && !foundInBdb) {
                    StoredResponse response = new StoredResponse();
                    response.timeStamp = System.currentTimeMillis();
                    response.foundIn = foundIn;
                }
                // 17&pos=41244981&=G&ref=GRCh37")
                newInfo.addAll(foundIn.stream().map( S -> alt.getDisplayString() + "|" + S).collect(Collectors.toSet()));
            }
            if (newInfo.isEmpty()) {
                out.add(ctx);
                continue;
            }
            final VariantContextBuilder vcb = new VariantContextBuilder(ctx);
            vcb.attribute(infoHeaderLine.getID(), new ArrayList<String>(newInfo));
            out.add(vcb.make());
        }
        return 0;
    } catch (final Exception err) {
        LOG.error(err);
        return -1;
    } finally {
        CloserUtil.close(httpClient);
    }
}
Example 22
Project: mylyn-redmine-connector-master  File: RedmineManagerFactory.java View source code
public static RedmineManager createWithUserAuthNoSslCheck(String url, String username, String password) {
    SSLContext sslcontext = null;
    try {
        sslcontext = SSLContexts.custom().setSecureRandom(new SecureRandom()).loadTrustMaterial(null, new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }).build();
    } catch (Exception e) {
    }
    final CloseableHttpClient httpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier()).setSslcontext(sslcontext).setMaxConnTotal(Integer.MAX_VALUE).setMaxConnPerRoute(Integer.MAX_VALUE).build();
    Runnable shutdownListener = new Runnable() {

        @Override
        public void run() {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }
    };
    return createWithUserAuth(url, username, password, TransportConfiguration.create(httpClient, shutdownListener));
}
Example 23
Project: splunk-library-javalogging-master  File: HttpEventCollectorSender.java View source code
private void startHttpClient() {
    if (httpClient != null) {
        // http client is already started
        return;
    }
    // limit max  number of async requests in sequential mode, 0 means "use
    // default limit"
    int maxConnTotal = sendMode == SendMode.Sequential ? 1 : 0;
    if (!disableCertificateValidation) {
        // create an http client that validates certificates
        httpClient = HttpAsyncClients.custom().setMaxConnTotal(maxConnTotal).build();
    } else {
        // create strategy that accepts all certificates
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] certificate, String type) {
                return true;
            }
        };
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
            httpClient = HttpAsyncClients.custom().setMaxConnTotal(maxConnTotal).setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslContext).build();
        } catch (Exception e) {
        }
    }
    httpClient.start();
}
Example 24
Project: ymate-module-wechat-master  File: HttpClientHelper.java View source code
private CloseableHttpClient __doBuildHttpClient() throws KeyManagementException, NoSuchAlgorithmException {
    HttpClientBuilder _builder = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(__connectionTimeout).setSocketTimeout(__connectionTimeout).setConnectionRequestTimeout(__connectionTimeout).build());
    if (__socketFactory == null) {
        __socketFactory = new SSLConnectionSocketFactory(SSLContexts.custom().useSSL().build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
    return _builder.setSSLSocketFactory(__socketFactory).build();
}
Example 25
Project: belladati-sdk-java-master  File: BellaDatiClient.java View source code
/**
	 * Builds the HTTP client to connect to the server.
	 * 
	 * @param trustSelfSigned <tt>true</tt> if the client should accept
	 *            self-signed certificates
	 * @return a new client instance
	 */
private CloseableHttpClient buildClient(boolean trustSelfSigned) {
    try {
        // if required, define custom SSL context allowing self-signed certs
        SSLContext sslContext = !trustSelfSigned ? SSLContexts.createSystemDefault() : SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
        // set timeouts for the HTTP client
        int globalTimeout = readFromProperty("bdTimeout", 100000);
        int connectTimeout = readFromProperty("bdConnectTimeout", globalTimeout);
        int connectionRequestTimeout = readFromProperty("bdConnectionRequestTimeout", globalTimeout);
        int socketTimeout = readFromProperty("bdSocketTimeout", globalTimeout);
        RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT).setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
        // configure caching
        CacheConfig cacheConfig = CacheConfig.copy(CacheConfig.DEFAULT).setSharedCache(false).setMaxCacheEntries(1000).setMaxObjectSize(2 * 1024 * 1024).build();
        // configure connection pooling
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(sslContext)).build());
        int connectionLimit = readFromProperty("bdMaxConnections", 40);
        // there's only one server to connect to, so max per route matters
        connManager.setMaxTotal(connectionLimit);
        connManager.setDefaultMaxPerRoute(connectionLimit);
        // create the HTTP client
        return CachingHttpClientBuilder.create().setCacheConfig(cacheConfig).setDefaultRequestConfig(requestConfig).setConnectionManager(connManager).build();
    } catch (GeneralSecurityException e) {
        throw new InternalConfigurationException("Failed to set up SSL context", e);
    }
}
Example 26
Project: ddf-platform-master  File: SolrServerFactory.java View source code
private static SSLContext getSslContext() {
    if (System.getProperty("javax.net.ssl.keyStore") == null || System.getProperty("javax.net.ssl.keyStorePassword") == null || System.getProperty("javax.net.ssl.trustStore") == null || System.getProperty("javax.net.ssl.trustStorePassword") == null) {
        throw new IllegalArgumentException("KeyStore and TrustStore system properties must be" + " set.");
    }
    KeyStore trustStore = getKeyStore(System.getProperty("javax.net.ssl.trustStore"), System.getProperty("javax.net.ssl.trustStorePassword"));
    KeyStore keyStore = getKeyStore(System.getProperty("javax.net.ssl.keyStore"), System.getProperty("javax.net.ssl.keyStorePassword"));
    SSLContext sslContext = null;
    try {
        sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, System.getProperty("javax.net.ssl.keyStorePassword").toCharArray()).loadTrustMaterial(trustStore).useTLS().build();
    } catch (UnrecoverableKeyExceptionNoSuchAlgorithmException | KeyStoreException | KeyManagementException |  e) {
        LOGGER.error("Unable to create secure HttpClient", e);
        return null;
    }
    sslContext.getDefaultSSLParameters().setNeedClientAuth(true);
    sslContext.getDefaultSSLParameters().setWantClientAuth(true);
    return sslContext;
}
Example 27
Project: elassandra-master  File: RestClient.java View source code
protected CloseableHttpClient createHttpClient(Settings settings) throws IOException {
    SSLConnectionSocketFactory sslsf;
    String keystorePath = settings.get(TRUSTSTORE_PATH);
    if (keystorePath != null) {
        final String keystorePass = settings.get(TRUSTSTORE_PASSWORD);
        if (keystorePass == null) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD);
        }
        Path path = PathUtils.get(keystorePath);
        if (!Files.exists(path)) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file");
        }
        try {
            KeyStore keyStore = KeyStore.getInstance("jks");
            try (InputStream is = Files.newInputStream(path)) {
                keyStore.load(is, keystorePass.toCharArray());
            }
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build();
            sslsf = new SSLConnectionSocketFactory(sslcontext);
        } catch (KeyStoreExceptionNoSuchAlgorithmException | KeyManagementException | CertificateException |  e) {
            throw new RuntimeException(e);
        }
    } else {
        sslsf = SSLConnectionSocketFactory.getSocketFactory();
    }
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
    return HttpClients.createMinimal(new PoolingHttpClientConnectionManager(socketFactoryRegistry, null, null, null, 15, TimeUnit.SECONDS));
}
Example 28
Project: elk-master  File: AbstractUnitTest.java View source code
protected final CloseableHttpClient getHTTPClient() throws Exception {
    final HttpClientBuilder hcb = HttpClients.custom();
    if (enableHTTPClientSSL) {
        log.debug("Configure HTTP client with SSL");
        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("truststore.jks")), "changeit".toCharArray());
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath(keystore)), "changeit".toCharArray());
        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();
        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }
        if (sendHTTPClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }
        final SSLContext sslContext = sslContextbBuilder.build();
        String[] protocols = null;
        if (enableHTTPClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        hcb.setSSLSocketFactory(sslsf);
    }
    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());
    return hcb.build();
}
Example 29
Project: knox-master  File: KnoxCLI.java View source code
@Override
public void execute() {
    attempts++;
    SSLContext ctx = null;
    CloseableHttpClient client;
    String http = "http://";
    String https = "https://";
    GatewayConfig conf = getGatewayConfig();
    String gatewayPort;
    String host;
    if (cluster == null) {
        printKnoxShellUsage();
        out.println("A --cluster argument is required.");
        return;
    }
    if (hostname != null) {
        host = hostname;
    } else {
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            out.println(e.toString());
            out.println("Defaulting address to localhost. Use --hostname option to specify a different hostname");
            host = "localhost";
        }
    }
    if (port != null) {
        gatewayPort = port;
    } else if (conf.getGatewayPort() > -1) {
        gatewayPort = Integer.toString(conf.getGatewayPort());
    } else {
        out.println("Could not get port. Please supply it using the --port option");
        return;
    }
    String path = "/" + conf.getGatewayPath();
    String topology = "/" + cluster;
    String httpServiceTestURL = http + host + ":" + gatewayPort + path + topology + "/service-test";
    String httpsServiceTestURL = https + host + ":" + gatewayPort + path + topology + "/service-test";
    String authString = "";
    //    Create Authorization String
    if (user != null && pass != null) {
        authString = "Basic " + Base64.encodeBase64String((user + ":" + pass).getBytes());
    } else {
        out.println("Username and/or password not supplied. Expect HTTP 401 Unauthorized responses.");
    }
    //    Attempt to build SSL context for HTTP client.
    try {
        ctx = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (Exception e) {
        out.println(e.toString());
    }
    //    Initialize the HTTP client
    if (ctx == null) {
        client = HttpClients.createDefault();
    } else {
        client = HttpClients.custom().setSslcontext(ctx).build();
    }
    HttpGet request;
    if (ssl) {
        request = new HttpGet(httpsServiceTestURL);
    } else {
        request = new HttpGet(httpServiceTestURL);
    }
    request.setHeader("Authorization", authString);
    request.setHeader("Accept", MediaType.APPLICATION_JSON.getMediaType());
    try {
        out.println(request.toString());
        CloseableHttpResponse response = client.execute(request);
        switch(response.getStatusLine().getStatusCode()) {
            case 200:
                response.getEntity().writeTo(out);
                break;
            case 404:
                out.println("Could not find service-test resource");
                out.println("Make sure you have configured the SERVICE-TEST service in your topology.");
                break;
            case 500:
                out.println("HTTP 500 Server error");
                break;
            default:
                out.println("Unexpected HTTP response code.");
                out.println(response.getStatusLine().toString());
                response.getEntity().writeTo(out);
                break;
        }
        response.close();
        request.releaseConnection();
    } catch (ClientProtocolException e) {
        out.println(e.toString());
        if (debug) {
            e.printStackTrace(out);
        }
    } catch (SSLException e) {
        out.println(e.toString());
        retryRequest();
    } catch (IOException e) {
        out.println(e.toString());
        retryRequest();
        if (debug) {
            e.printStackTrace(out);
        }
    } finally {
        try {
            client.close();
        } catch (IOException e) {
            out.println(e.toString());
        }
    }
}
Example 30
Project: lucene-solr-master  File: SSLTestConfig.java View source code
/**
   * Builds a new SSLContext for HTTP <b>clients</b> to use when communicating with servers which have 
   * been configured based on the settings of this object.  
   *
   * NOTE: Uses a completely insecure {@link SecureRandom} instance to prevent tests from blocking 
   * due to lack of entropy, also explicitly allows the use of self-signed 
   * certificates (since that's what is almost always used during testing).
   */
public SSLContext buildClientSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    assert isSSLMode();
    SSLContextBuilder builder = SSLContexts.custom();
    builder.setSecureRandom(NotSecurePsuedoRandom.INSTANCE);
    // NOTE: KeyStore & TrustStore are swapped because they are from configured from server perspective...
    // we are a client - our keystore contains the keys the server trusts, and vice versa
    builder.loadTrustMaterial(buildKeyStore(keyStore, getKeyStorePassword()), new TrustSelfSignedStrategy()).build();
    if (isClientAuthMode()) {
        builder.loadKeyMaterial(buildKeyStore(trustStore, getTrustStorePassword()), getTrustStorePassword().toCharArray());
    }
    return builder.build();
}
Example 31
Project: search-guard-master  File: AbstractUnitTest.java View source code
protected final CloseableHttpClient getHTTPClient() throws Exception {
    final HttpClientBuilder hcb = HttpClients.custom();
    if (enableHTTPClientSSL) {
        log.debug("Configure HTTP client with SSL");
        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("truststore.jks")), "changeit".toCharArray());
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath(keystore)), "changeit".toCharArray());
        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();
        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }
        if (sendHTTPClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }
        final SSLContext sslContext = sslContextbBuilder.build();
        String[] protocols = null;
        if (enableHTTPClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        hcb.setSSLSocketFactory(sslsf);
    }
    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());
    return hcb.build();
}
Example 32
Project: wisdom-master  File: ServerTest.java View source code
/**
     * This methods checks HTTP, HTTPS and HTTPS with Mutual Authentication.
     */
@Test
public void testCreationOfThreeServersFromConfiguration() throws InterruptedException, IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException {
    FakeConfiguration s1 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0).put("ssl", false).put("authentication", false).build());
    FakeConfiguration s2 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0).put("ssl", true).put("authentication", false).build());
    FakeConfiguration s3 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0).put("ssl", true).put("authentication", true).build());
    // Server HTTPS
    File root = new File("");
    final File serverKeyStore = new File(root.getAbsolutePath() + "/src/test/resources/keystore/server/server.jks");
    assertThat(serverKeyStore).isFile();
    when(application.get("https.keyStore")).thenReturn(serverKeyStore.getAbsolutePath());
    when(application.get("https.trustStore")).thenReturn(new File(root.getAbsolutePath() + "/src/test/resources/keystore/server/server.jks").getAbsolutePath());
    when(application.getWithDefault("https.keyStoreType", "JKS")).thenReturn("JKS");
    when(application.getWithDefault("https.trustStoreType", "JKS")).thenReturn("JKS");
    when(application.getWithDefault("https.keyStorePassword", "")).thenReturn("wisdom");
    when(application.getWithDefault("https.trustStorePassword", "")).thenReturn("wisdom");
    when(application.getWithDefault("https.keyStoreAlgorithm", KeyManagerFactory.getDefaultAlgorithm())).thenReturn(KeyManagerFactory.getDefaultAlgorithm());
    when(application.getWithDefault("https.trustStoreAlgorithm", KeyManagerFactory.getDefaultAlgorithm())).thenReturn(KeyManagerFactory.getDefaultAlgorithm());
    when(application.getConfiguration("vertx.servers")).thenReturn(new FakeConfiguration(ImmutableMap.<String, Object>of("s1", s1, "s2", s2, "s3", s3)));
    Controller controller = new DefaultController() {

        @SuppressWarnings("unused")
        public Result index() {
            return ok("Alright");
        }
    };
    Route route = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index");
    when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route);
    wisdom.start();
    waitForStart(wisdom);
    waitForHttpsStart(wisdom);
    assertThat(wisdom.servers).hasSize(3);
    // Check rendering
    for (Server server : wisdom.servers) {
        String r;
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream("src/test/resources/keystore/client/client1.jks");
        trustStore.load(instream, "wisdom".toCharArray());
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).loadKeyMaterial(trustStore, "wisdom".toCharArray()).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1", "SSLv3" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        if (server.ssl()) {
            HttpGet httpget = new HttpGet("https://localhost:" + server.port());
            final CloseableHttpResponse response = httpclient.execute(httpget);
            r = EntityUtils.toString(response.getEntity());
        } else {
            r = org.apache.http.client.fluent.Request.Get("http://localhost:" + server.port()).execute().returnContent().asString();
        }
        assertThat(r).isEqualToIgnoringCase("Alright");
    }
}
Example 33
Project: jersey-master  File: ApacheConnector.java View source code
private HttpClientConnectionManager createConnectionManager(final Client client, final Configuration config, final SSLContext sslContext, final boolean useSystemProperties) {
    final String[] supportedProtocols = useSystemProperties ? split(System.getProperty("https.protocols")) : null;
    final String[] supportedCipherSuites = useSystemProperties ? split(System.getProperty("https.cipherSuites")) : null;
    HostnameVerifier hostnameVerifier = client.getHostnameVerifier();
    final LayeredConnectionSocketFactory sslSocketFactory;
    if (sslContext != null) {
        sslSocketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols, supportedCipherSuites, hostnameVerifier);
    } else {
        if (useSystemProperties) {
            sslSocketFactory = new SSLConnectionSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault(), supportedProtocols, supportedCipherSuites, hostnameVerifier);
        } else {
            sslSocketFactory = new SSLConnectionSocketFactory(SSLContexts.createDefault(), hostnameVerifier);
        }
    }
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
    final Integer chunkSize = ClientProperties.getValue(config.getProperties(), ClientProperties.CHUNKED_ENCODING_SIZE, ClientProperties.DEFAULT_CHUNK_SIZE, Integer.class);
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry, new ConnectionFactory(chunkSize));
    if (useSystemProperties) {
        String s = System.getProperty("http.keepAlive", "true");
        if ("true".equalsIgnoreCase(s)) {
            s = System.getProperty("http.maxConnections", "5");
            final int max = Integer.parseInt(s);
            connectionManager.setDefaultMaxPerRoute(max);
            connectionManager.setMaxTotal(2 * max);
        }
    }
    return connectionManager;
}
Example 34
Project: liferay-portal-master  File: JSONWebServiceClientImpl.java View source code
protected SSLConnectionSocketFactory getSSLConnectionSocketFactory() {
    SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    SSLContext sslContext = null;
    try {
        sslContextBuilder.loadTrustMaterial(_keyStore);
        sslContext = sslContextBuilder.build();
        sslContext.init(null, new TrustManager[] { new X509TrustManagerImpl() }, null);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
}
Example 35
Project: vitam-master  File: ApacheConnector.java View source code
private HttpClientConnectionManager createConnectionManager(final Client client, final Configuration config, final SSLContext sslContext, final boolean useSystemProperties) {
    final String[] supportedProtocols = useSystemProperties ? split(System.getProperty("https.protocols")) : null;
    final String[] supportedCipherSuites = useSystemProperties ? split(System.getProperty("https.cipherSuites")) : null;
    final HostnameVerifier hostnameVerifier = client.getHostnameVerifier();
    final LayeredConnectionSocketFactory sslSocketFactory;
    if (sslContext != null) {
        sslSocketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols, supportedCipherSuites, hostnameVerifier);
    } else {
        if (useSystemProperties) {
            sslSocketFactory = new SSLConnectionSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault(), supportedProtocols, supportedCipherSuites, hostnameVerifier);
        } else {
            sslSocketFactory = new SSLConnectionSocketFactory(SSLContexts.createDefault(), hostnameVerifier);
        }
    }
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
    final Integer chunkSize = ClientProperties.getValue(config.getProperties(), ClientProperties.CHUNKED_ENCODING_SIZE, ClientProperties.DEFAULT_CHUNK_SIZE, Integer.class);
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry, new ConnectionFactory(chunkSize));
    if (useSystemProperties) {
        String s = System.getProperty("http.keepAlive", "true");
        if ("true".equalsIgnoreCase(s)) {
            s = System.getProperty("http.maxConnections", "5");
            final int max = Integer.parseInt(s);
            connectionManager.setDefaultMaxPerRoute(max);
            connectionManager.setMaxTotal(2 * max);
        }
    }
    return connectionManager;
}
Example 36
Project: stash-master  File: StashNotifier.java View source code
/**
     * Helper in place to allow us to define out HttpClient SSL context
     *
     * @param ignoreUnverifiedSSL
     * @param credentials
     * @return
     * @throws UnrecoverableKeyException
     * @throws NoSuchAlgorithmException
     * @throws KeyStoreException
     * @throws KeyManagementException
     */
private SSLContext buildSslContext(boolean ignoreUnverifiedSSL, Credentials credentials) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    SSLContextBuilder customContext = SSLContexts.custom();
    if (credentials instanceof CertificateCredentials) {
        customContext = customContext.loadKeyMaterial(((CertificateCredentials) credentials).getKeyStore(), ((CertificateCredentials) credentials).getPassword().getPlainText().toCharArray());
    }
    if (ignoreUnverifiedSSL) {
        TrustStrategy easyStrategy = new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        };
        customContext = customContext.loadTrustMaterial(null, easyStrategy);
    }
    return customContext.useTLS().build();
}
Example 37
Project: stashnotifier-plugin-master  File: StashNotifier.java View source code
/**
     * Helper in place to allow us to define out HttpClient SSL context
     *
     * @param ignoreUnverifiedSSL
     * @param credentials
     * @return
     * @throws UnrecoverableKeyException
     * @throws NoSuchAlgorithmException
     * @throws KeyStoreException
     * @throws KeyManagementException
     */
private SSLContext buildSslContext(boolean ignoreUnverifiedSSL, Credentials credentials) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    SSLContextBuilder customContext = SSLContexts.custom();
    if (credentials instanceof CertificateCredentials) {
        customContext = customContext.loadKeyMaterial(((CertificateCredentials) credentials).getKeyStore(), ((CertificateCredentials) credentials).getPassword().getPlainText().toCharArray());
    }
    if (ignoreUnverifiedSSL) {
        TrustStrategy easyStrategy = new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        };
        customContext = customContext.loadTrustMaterial(null, easyStrategy);
    }
    return customContext.useTLS().build();
}
Example 38
Project: nifi-master  File: PostHTTP.java View source code
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 39
Project: galaxy-fds-sdk-java-master  File: GalaxyFDSClient.java View source code
private HttpClient createHttpClient(FDSClientConfiguration config) {
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(config.getConnectionTimeoutMs()).setSocketTimeout(config.getSocketTimeoutMs()).build();
    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
    registryBuilder.register("http", new PlainConnectionSocketFactory());
    if (config.isHttpsEnabled()) {
        SSLContext sslContext = SSLContexts.createSystemDefault();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registryBuilder.register("https", sslsf);
    }
    connectionManager = new PoolingHttpClientConnectionManager(registryBuilder.build());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnection());
    connectionManager.setMaxTotal(config.getMaxConnection());
    HttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)).build();
    return httpClient;
}
Example 40
Project: java-json-client-master  File: HttpSSLClientBuilder.java View source code
private SSLContext createSSLContext() {
    try {
        return SSLContexts.custom().loadTrustMaterial(createKeyStore(), new TrustSelfSignedStrategy()).build();
    } catch (Exception e) {
        throw new RuntimeException("Could not create SSL context", e);
    }
}
Example 41
Project: saki-monkey-master  File: MandrillAsyncClient.java View source code
/**
     * This SSLIOSessionStategy can be overridden by createConnectionManager 
     * @return
     */
protected SSLIOSessionStrategy createSSLIOSessionStrategy() {
    return new SSLIOSessionStrategy(SSLContexts.createDefault(), createHostnameVerifier());
}
Example 42
Project: heliosearch-master  File: SSLTestConfig.java View source code
/**
   * Builds a new SSLContext with the given configuration and allows the uses of
   * self-signed certificates during testing.
   */
protected SSLContext buildSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    return SSLContexts.custom().loadKeyMaterial(buildKeyStore(getKeyStore(), getKeyStorePassword()), getKeyStorePassword().toCharArray()).loadTrustMaterial(buildKeyStore(getTrustStore(), getTrustStorePassword()), new TrustSelfSignedStrategy()).build();
}
Example 43
Project: keycloak-master  File: HttpClientBuilder.java View source code
private SSLContext createSslContext(final String algorithm, final KeyStore keystore, final String keyPassword, final KeyStore truststore, final SecureRandom random) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    return SSLContexts.custom().useProtocol(algorithm).setSecureRandom(random).loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null).loadTrustMaterial(truststore).build();
}
Example 44
Project: stability-utils-master  File: PooledHttpClientStrategy.java View source code
private SSLConnectionSocketFactory getLenientSslSocketFactory() {
    SSLContext sslContext = SSLContexts.createSystemDefault();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return sslsf;
}