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:ch.cyberduck.core.http.HttpConnectionPoolBuilder.java

protected HttpConnectionPoolBuilder(final Host host, final X509TrustManager trust, final X509KeyManager key,
        final ProxyFinder proxy, final SocketFactory socketFactory) {
    this(host, new PlainConnectionSocketFactory() {
        @Override//from  w ww  .j  a  va  2 s .  c  om
        public Socket createSocket(final HttpContext context) throws IOException {
            return socketFactory.createSocket();
        }
    }, new SSLConnectionSocketFactory(new CustomTrustSSLProtocolSocketFactory(trust, key),
            new DisabledX509HostnameVerifier()) {
        @Override
        public Socket createSocket(final HttpContext context) throws IOException {
            return socketFactory.createSocket();
        }

        @Override
        public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
                final InetSocketAddress remoteAddress, final InetSocketAddress localAddress,
                final HttpContext context) throws IOException {
            if (trust instanceof ThreadLocalHostnameDelegatingTrustManager) {
                ((ThreadLocalHostnameDelegatingTrustManager) trust).setTarget(remoteAddress.getHostName());
            }
            return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
        }
    }, proxy);
}

From source file:com.ea.core.bridge.ws.rest.client.AbstractRestClient.java

public AbstractRestClient(URL httpUrl) {
    super(httpUrl);

    HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {
        @Override//from  w w w .  jav a  2 s .co  m
        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();

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
            requestWriterFactory, responseParserFactory);

    SSLContext sslcontext = SSLContexts.createSystemDefault();
    X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();

    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("myhost") || host.equalsIgnoreCase("localhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return super.resolve(host);
            }
        }

    };

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, connFactory, dnsResolver);

    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
    connManager.setDefaultSocketConfig(socketConfig);
    connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);

    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    connManager.setDefaultConnectionConfig(connectionConfig);
    connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(10);
    connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    CookieStore cookieStore = new BasicCookieStore();
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectionRequestTimeout(3000)
            .setConnectTimeout(3000).setSocketTimeout(3000).build();

    client = HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credentialsProvider)
            //            .setProxy(new HttpHost("myproxy", 8080))
            .setDefaultRequestConfig(defaultRequestConfig).build();
}

From source file:ai.susi.server.ClientConnection.java

private static PoolingHttpClientConnectionManager getConnctionManager(boolean useAuthentication) {

    // allow opportunistic encryption if needed

    boolean trustAllCerts = !"none".equals(DAO.getConfig("httpsclient.trustselfsignedcerts", "peers"))
            && (!useAuthentication || "all".equals(DAO.getConfig("httpsclient.trustselfsignedcerts", "peers")));

    Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
    if (trustAllCerts) {
        try {//from   w w w. ja va 2  s. c om
            SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
                    new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    new TrustAllHostNameVerifier());
            socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", trustSelfSignedSocketFactory).build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            Log.getLog().warn(e);
        }
    }

    PoolingHttpClientConnectionManager cm = (trustAllCerts && socketFactoryRegistry != null)
            ? new PoolingHttpClientConnectionManager(socketFactoryRegistry)
            : new PoolingHttpClientConnectionManager();

    // twitter specific options
    cm.setMaxTotal(200);
    cm.setDefaultMaxPerRoute(20);
    HttpHost twitter = new HttpHost("twitter.com", 443);
    cm.setMaxPerRoute(new HttpRoute(twitter), 50);

    return cm;
}

From source file:org.apache.streams.components.http.provider.SimpleHttpProvider.java

@Override
public void prepare(Object configurationObject) {

    mapper = StreamsJacksonMapper.getInstance();

    uriBuilder = new URIBuilder().setScheme(this.configuration.getProtocol())
            .setHost(this.configuration.getHostname()).setPort(this.configuration.getPort().intValue())
            .setPath(this.configuration.getResourcePath());

    SSLContextBuilder builder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {/*from w  ww.ja  v a  2 s . co  m*/
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (NoSuchAlgorithmException e) {
        LOGGER.warn(e.getMessage());
    } catch (KeyManagementException e) {
        LOGGER.warn(e.getMessage());
    } catch (KeyStoreException e) {
        LOGGER.warn(e.getMessage());
    }

    httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    executor = Executors.newSingleThreadExecutor();

}

From source file:com.threatconnect.sdk.conn.ConnectionUtil.java

/**
 * Adds the ability to trust self signed certificates for this HttpClientBuilder
 * /*w  w  w. ja  v a2  s  .c  o m*/
 * @param httpClientBuilder
 * the HttpClientBuilder to apply these settings to
 */
public static void trustSelfSignedCerts(final HttpClientBuilder httpClientBuilder) {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
                new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        // allow all
                        return true;
                    }
                });

        httpClientBuilder.setSSLSocketFactory(sslsf);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        logger.error("Error adding SSLSocketFactory to HttpClientBuilder", ex);
    }
}

From source file:org.musicmount.io.server.dav.DAVResourceProvider.java

protected Sardine createSardine(final ServerFileSystem fileSystem) {
    /*/*from  w  ww .  j av a 2s .  com*/
     * extract user/password
     */
    String user = null;
    String password = null;
    if (fileSystem.getUserInfo() != null) {
        String[] userAndPassword = fileSystem.getUserInfo().split(":");
        user = userAndPassword[0];
        password = userAndPassword.length > 1 ? userAndPassword[1] : null;
    }

    /*
     * create customized sardine
     */
    return new SardineImpl(user, password, null) {
        @Override
        protected Registry<ConnectionSocketFactory> createDefaultSchemeRegistry() {
            ConnectionSocketFactory socketFactory;
            if ("https".equalsIgnoreCase(fileSystem.getScheme())) {
                socketFactory = createDefaultSecureSocketFactory();
            } else {
                socketFactory = createDefaultSocketFactory();
            }
            return RegistryBuilder.<ConnectionSocketFactory>create()
                    .register(fileSystem.getScheme(), socketFactory).build();
        }

        @Override
        protected ConnectionSocketFactory createDefaultSecureSocketFactory() {
            try { // trust anybody...
                SSLContext context = SSLContext.getInstance("TLS");
                X509TrustManager trustManager = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] xcs, String string)
                            throws CertificateException {
                    }

                    public void checkServerTrusted(X509Certificate[] xcs, String string)
                            throws CertificateException {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                };
                context.init(null, new TrustManager[] { trustManager }, null);
                return new SSLConnectionSocketFactory(context,
                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                // should not happen...
            }
            return super.createDefaultSecureSocketFactory();
        }

        @Override
        protected <T> T execute(HttpRequestBase request, ResponseHandler<T> responseHandler)
                throws IOException {
            /*
             * Sardine re-executes a PUT request after a org.apache.http.NoHttpResponseException without resetting it...
             */
            if (request.isAborted()) {
                request.reset();
            }
            return super.execute(request, responseHandler);
        }

        @Override
        public ContentLengthInputStream get(String url, Map<String, String> headers) throws IOException {
            /*
             * abort rather than consume entity for better performance
             */
            final HttpGet get = new HttpGet(url);
            for (String header : headers.keySet()) {
                get.addHeader(header, headers.get(header));
            }
            // Must use #execute without handler, otherwise the entity is consumed already after the handler exits.
            final HttpResponse response = this.execute(get);
            VoidResponseHandler handler = new VoidResponseHandler();
            try {
                handler.handleResponse(response);
                // Will consume or abort the entity when the stream is closed.
                PositionInputStream positionInputStream = new PositionInputStream(
                        response.getEntity().getContent()) {
                    public void close() throws IOException {
                        if (getPosition() == response.getEntity().getContentLength()) {
                            EntityUtils.consume(response.getEntity());
                        } else { // partial read or unknown content length
                            get.abort();
                        }
                    }
                };
                return new ContentLengthInputStream(positionInputStream,
                        response.getEntity().getContentLength());
            } catch (IOException ex) {
                get.abort();
                throw ex;
            }
        }
    };
}

From source file:com.ericsson.gerrit.plugins.syncindex.HttpClientProvider.java

private SSLConnectionSocketFactory buildSslSocketFactory() {
    return new SSLConnectionSocketFactory(buildSslContext(), NoopHostnameVerifier.INSTANCE);
}

From source file:org.thingsboard.server.msa.AbstractContainerTest.java

private static HttpComponentsClientHttpRequestFactory getRequestFactoryForSelfSignedCert() throws Exception {
    SSLContextBuilder builder = SSLContexts.custom();
    builder.loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true);
    SSLContext sslContext = builder.build();
    SSLConnectionSocketFactory sslSelfSigned = new SSLConnectionSocketFactory(sslContext,
            new X509HostnameVerifier() {
                @Override/*www  .  j a  v a  2s  .com*/
                public void verify(String host, SSLSocket ssl) {
                }

                @Override
                public void verify(String host, X509Certificate cert) {
                }

                @Override
                public void verify(String host, String[] cns, String[] subjectAlts) {
                }

                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslSelfSigned).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
    return new HttpComponentsClientHttpRequestFactory(httpClient);
}

From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {/*w  w  w. j  a v  a  2 s. co  m*/
    String deployApiUrl = modelerAppProperties.getDeploymentApiUrl();
    Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set");
    String basicAuthUser = properties.getIdmAdmin().getUser();
    String basicAuthPassword = properties.getIdmAdmin().getPassword();

    String tenantId = tenantProvider.getTenantId();
    if (!deployApiUrl.endsWith("/")) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    if (tenantId != null) {
        StringBuilder sb = new StringBuilder(deployApiUrl);
        sb.append("&tenantId=").append(encode(tenantId));
        deployApiUrl = sb.toString();
    }

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder()
            .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8")))));

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName);

    HttpEntity entity = entityBuilder.build();
    httpPost.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        clientBuilder
                .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }));

    } catch (Exception e) {
        LOGGER.error("Could not configure SSL for http client", e);
        throw new InternalServerErrorException("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return;
        } else {
            LOGGER.error("Invalid deploy result code: {} for url",
                    response.getStatusLine() + httpPost.getURI().toString());
            throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine());
        }

    } catch (IOException ioe) {
        LOGGER.error("Error calling deploy endpoint", ioe);
        throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                LOGGER.warn("Exception while closing http client", e);
            }
        }
    }
}

From source file:org.eclipse.jgit.transport.http.apache.HttpClientConnection.java

private HttpClient getClient() {
    if (client == null) {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
            isUsingProxy = true;//from w  w w  .  j a va2s  .  c  o  m
            InetSocketAddress adr = (InetSocketAddress) proxy.address();
            clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort()));
        }
        if (timeout != null) {
            configBuilder.setConnectTimeout(timeout.intValue());
        }
        if (readTimeout != null) {
            configBuilder.setSocketTimeout(readTimeout.intValue());
        }
        if (followRedirects != null) {
            configBuilder.setRedirectsEnabled(followRedirects.booleanValue());
        }
        if (hostnameverifier != null) {
            SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(getSSLContext(),
                    hostnameverifier);
            clientBuilder.setSSLSocketFactory(sslConnectionFactory);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnectionFactory)
                    .register("http", PlainConnectionSocketFactory.INSTANCE).build();
            clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        }
        clientBuilder.setDefaultRequestConfig(configBuilder.build());
        client = clientBuilder.build();
    }

    return client;
}