Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

Introduction

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

Prototype

public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:org.apache.manifoldcf.crawler.connectors.confluence.ConfluenceSession.java

public ConfluenceSession(String clientId, String clientSecret, String protocol, String host, int port,
        String path, String proxyHost, int proxyPort, String proxyDomain, String proxyUsername,
        String proxyPassword) throws ManifoldCFException {
    this.host = new HttpHost(host, port, protocol);
    this.path = path;
    this.clientId = clientId;
    this.clientSecret = clientSecret;

    int socketTimeout = 900000;
    int connectionTimeout = 60000;

    javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory.getTrustingSecureSocketFactory();
    SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
            new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    connectionManager = new PoolingHttpClientConnectionManager();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // If authentication needed, set that
    if (clientId != null) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(clientId, clientSecret));
    }// ww  w .j a  v  a  2s.c o m

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    // If there's a proxy, set that too.
    if (proxyHost != null && proxyHost.length() > 0) {

        // Configure proxy authentication
        if (proxyUsername != null && proxyUsername.length() > 0) {
            if (proxyPassword == null)
                proxyPassword = "";
            if (proxyDomain == null)
                proxyDomain = "";

            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
        }

        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        requestBuilder.setProxy(proxy);
    }

    httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();
}

From source file:io.kamax.mxisd.invitation.InvitationManager.java

@PostConstruct
private void postConstruct() {
    gson = new Gson();

    log.info("Loading saved invites");
    Collection<ThreePidInviteIO> ioList = storage.getInvites();
    ioList.forEach(io -> {/* w ww  . j  ava2  s  .c o m*/
        log.info("Processing invite {}", gson.toJson(io));
        ThreePidInvite invite = new ThreePidInvite(new MatrixID(io.getSender()), io.getMedium(),
                io.getAddress(), io.getRoomId(), io.getProperties());

        ThreePidInviteReply reply = new ThreePidInviteReply(getId(invite), invite, io.getToken(), "");
        invitations.put(reply.getId(), reply);
    });

    // FIXME export such madness into matrix-java-sdk with a nice wrapper to talk to a homeserver
    try {
        SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                hostnameVerifier);
        client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
    } catch (Exception e) {
        // FIXME do better...
        throw new RuntimeException(e);
    }

    log.info("Setting up invitation mapping refresh timer");
    refreshTimer = new Timer();
    refreshTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            try {
                lookupMappingsForInvites();
            } catch (Throwable t) {
                log.error("Error when running background mapping refresh", t);
            }
        }
    }, 5000L, TimeUnit.MILLISECONDS.convert(cfg.getResolution().getTimer(), TimeUnit.MINUTES));
}

From source file:org.mycontroller.restclient.core.RestHttpClient.java

private CloseableHttpClient getHttpClientTrustAll() {
    SSLContextBuilder builder = new SSLContextBuilder();
    try {//from w  w w  .j  a v  a 2 s .  c  o  m
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        builder.loadTrustMaterial(keyStore, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] trustedCert, String nameConstraints)
                    throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
                new AnyHostnameVerifier());
        return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(customRequestConfig)
                .build();
    } catch (Exception ex) {
        _logger.error("Exception, ", ex);
        throw new RuntimeException("Unable to create trust ANY http client. Error: " + ex.getMessage());
    }
}

From source file:leap.lang.http.client.apache.ApacheHttpClient.java

protected Registry<ConnectionSocketFactory> getDefaultRegistry() {
    RegistryBuilder<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create();

    reg.register("http", PlainConnectionSocketFactory.getSocketFactory());

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(SSL_CONTEXT,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    reg.register("https", sslSocketFactory);

    return reg.build();
}

From source file:org.ops4j.pax.web.itest.base.client.HttpComponentsWrapper.java

private CloseableHttpClient createHttpClient() throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, KeyManagementException {
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    SSLConnectionSocketFactory sslsf = null;
    try {/* w w w  . jav  a  2 s  .  c  om*/
        FileInputStream instream = new FileInputStream(new File(keyStore));
        try {
            trustStore.load(instream, "password".toCharArray());
        } finally {
            // CHECKSTYLE:OFF
            try {
                instream.close();
            } catch (Exception ignore) {
            }
            // CHECKSTYLE:ON
        }

        SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore).build();
        sslsf = new SSLConnectionSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    } catch (FileNotFoundException e) {
        LOG.error("Error preparing SSL for testing. Https will not be available.", e);
    }

    PlainConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();

    RegistryBuilder<ConnectionSocketFactory> rb = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainsf);
    if (sslsf != null) {
        rb.register("https", sslsf);
    }

    Registry<ConnectionSocketFactory> registry = rb.build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);

    return HttpClients.custom().setConnectionManager(cm).build();

}

From source file:it.anyplace.sync.discovery.protocol.gd.GlobalDiscoveryHandler.java

/**
 * /*from   w ww.j  a v  a2s.  co m*/
 * @param server
 * @param deviceId
 * @return null on error, empty list on 'not found', address list otherwise
 */
private @Nullable List<DeviceAddress> doQuery(String server, final String deviceId) {
    try {
        logger.trace("querying server {} for device id {}", server, deviceId);
        HttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(new SSLConnectionSocketFactory(
                        new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))
                .build();
        HttpGet httpGet = new HttpGet("https://" + server + "/v2/?device=" + deviceId);
        return httpClient.execute(httpGet, new ResponseHandler<List<DeviceAddress>>() {
            @Override
            public List<DeviceAddress> handleResponse(HttpResponse response)
                    throws ClientProtocolException, IOException {
                switch (response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_NOT_FOUND:
                    logger.debug("device not found: {}", deviceId);
                    return Collections.<DeviceAddress>emptyList();
                case HttpStatus.SC_OK:
                    AnnouncementMessageBean announcementMessageBean = gson.fromJson(
                            EntityUtils.toString(response.getEntity()), AnnouncementMessageBean.class);
                    List<DeviceAddress> list = Lists
                            .newArrayList(Iterables.transform(
                                    firstNonNull(announcementMessageBean.getAddresses(),
                                            Collections.<String>emptyList()),
                                    new Function<String, DeviceAddress>() {
                                        @Override
                                        public DeviceAddress apply(String address) {
                                            return new DeviceAddress(deviceId, address);
                                        }
                                    }));
                    logger.debug("found address list = {}", list);
                    return list;
                default:
                    throw new IOException("http error " + response.getStatusLine());
                }
            }
        });
    } catch (Exception ex) {
        logger.warn("error in global discovery for device = " + deviceId, ex);
    }
    return null;
}

From source file:com.spectralogic.ds3client.NetworkClientImpl.java

private static CloseableHttpClient createDefaultClient(final ConnectionDetails connectionDetails) {
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(MAX_CONNECTION_PER_ROUTE);
    connectionManager.setMaxTotal(MAX_CONNECTION_TOTAL);

    if (connectionDetails.isHttps() && !connectionDetails.isCertificateVerification()) {
        try {/*from   www  . j a v  a 2s.com*/

            final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    return true;
                }
            }).useTLS().build();

            final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    new AllowAllHostnameVerifier());
            return HttpClients.custom().setConnectionManager(connectionManager).setSSLSocketFactory(sslsf)
                    .build();

        } catch (final NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            throw new SSLSetupException(e);
        }
    } else {
        return HttpClients.custom().setConnectionManager(connectionManager).build();
    }
}

From source file:crawler.java.edu.uci.ics.crawler4j.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(CookieSpecs.DEFAULT).setRedirectsEnabled(false)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();/*ww w  .j ava  2  s.  c om*/

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    if (config.isIncludeHttpsPages()) {
        try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
            // By always trusting the ssl certificate
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(final X509Certificate[] chain, String authType) {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            connRegistryBuilder.register("https", sslsf);
        } catch (Exception e) {
            logger.warn("Exception thrown while trying to register https");
            logger.debug("Stacktrace", e);
        }
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent(config.getUserAgentString());
    clientBuilder.setDefaultHeaders(config.getDefaultHeaders());

    if (config.getProxyHost() != null) {
        if (config.getProxyUsername() != null) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        clientBuilder.setProxy(proxy);
        logger.debug("Working through Proxy: {}", proxy.getHostName());
    }

    httpClient = clientBuilder.build();
    if ((config.getAuthInfos() != null) && !config.getAuthInfos().isEmpty()) {
        doAuthetication(config.getAuthInfos());
    }

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();
}

From source file:com.pipinan.githubcrawler.GithubCrawler.java

/**
 * Just to avoid the ssl exception when using HttpClient to access https url
 *
 * @return/*from  ww w .  java  2  s . co  m*/
 */
private HttpClient getHttpClient() {
    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        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) {
            }
        } }, new SecureRandom());

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build();

        return httpClient;

    } catch (Exception e) {
        e.printStackTrace();
        return HttpClientBuilder.create().build();
    }
}

From source file:com.qwazr.utils.http.HttpUtils.java

/**
 * Create a new HttpClient which accept untrusted SSL certificates
 *
 * @return a new HttpClient/*from   w  w w .ja  va2 s  . co  m*/
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static CloseableHttpClient createHttpClient_AcceptsUntrustedCerts()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    final HttpClientBuilder unsecureHttpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();

    unsecureHttpClientBuilder.setSSLContext(sslContext);

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    unsecureHttpClientBuilder.setConnectionManager(connMgr);
    return unsecureHttpClientBuilder.build();
}