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

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

Introduction

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

Prototype

TrustStrategy

Source Link

Usage

From source file:com.aliyun.oss.common.comm.DefaultServiceClient.java

protected HttpClientConnectionManager createHttpClientConnectionManager() {
    SSLContext sslContext = null;
    try {//from  www.j a va 2 s. com
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }

        }).build();

    } catch (Exception e) {
        throw new ClientException(e.getMessage());
    }

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(Protocol.HTTP.toString(), PlainConnectionSocketFactory.getSocketFactory())
            .register(Protocol.HTTPS.toString(), sslSocketFactory).build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnections());
    connectionManager.setMaxTotal(config.getMaxConnections());
    connectionManager.setValidateAfterInactivity(config.getValidateAfterInactivity());
    connectionManager.setDefaultSocketConfig(
            SocketConfig.custom().setSoTimeout(config.getSocketTimeout()).setTcpNoDelay(true).build());
    if (config.isUseReaper()) {
        IdleConnectionReaper.setIdleConnectionTime(config.getIdleConnectionTime());
        IdleConnectionReaper.registerConnectionManager(connectionManager);
    }
    return connectionManager;
}

From source file:org.xmlsh.internal.commands.http.java

private void disableTrust(DefaultHttpClient client, String disableTrustProto)
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {

    SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustStrategy() {

        @Override/*from   ww w. j  ava 2 s .  c om*/
        public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub
            return false;
        }

    }, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    int port = client.getConnectionManager().getSchemeRegistry().getScheme(disableTrustProto).getDefaultPort();

    client.getConnectionManager().getSchemeRegistry()
            .register(new Scheme(disableTrustProto, port, socketFactory));
}

From source file:com.magnet.tools.tests.RestStepDefs.java

/**
 * @return get a test http client that trusts all certs
 *///  w w w. ja  v a 2s  .c o  m
private static CloseableHttpClient getTestHttpClient(URI uri) {
    String scheme = uri.getScheme();
    int port = uri.getPort();
    if (scheme.toLowerCase().equals("https")) {
        try {
            SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }, new AllowAllHostnameVerifier());

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("https", port, sf));
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry);
            return new DefaultHttpClient(ccm);
        } catch (Exception e) {
            e.printStackTrace();
            return new DefaultHttpClient();
        }
    } else {
        return new DefaultHttpClient();
    }
}

From source file:gov.nih.nci.nbia.StandaloneDMV3.java

private List<String> connectAndReadFromURL(URL url, List<String> seriesList, String userId, String passWd) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override/*from ww  w .  j av a  2  s .  co m*/
        public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        // SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        // sslContext.init(null, new TrustManager[] { new
        // EasyX509TrustManager(null)}, null);

        SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);

        HttpParams httpParams = new BasicHttpParams();
        // HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
        // HttpConnectionParams.setSoTimeout(httpParams, new
        // Integer(12000));
        HttpConnectionParams.setConnectionTimeout(httpParams, 500000);
        HttpConnectionParams.setSoTimeout(httpParams, new Integer(120000));
        httpClient = new DefaultHttpClient(ccm, httpParams);
        httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault()));
        // // Additions by lrt for tcia -
        // // attempt to reduce errors going through a Coyote Point
        // Equalizer load balance switch
        // httpClient.getParams().setParameter("http.socket.timeout", new
        // Integer(12000));
        httpClient.getParams().setParameter("http.socket.timeout", new Integer(120000));
        httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
        httpClient.getParams().setParameter("http.tcp.nodelay", true);
        httpClient.getParams().setParameter("http.connection.stalecheck", false);
        // // end lrt additions

        HttpPost httpPostMethod = new HttpPost(url.toString());

        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();

        if (userId != null && passWd != null) {
            postParams.add(new BasicNameValuePair("userId", userId));
            httpPostMethod.addHeader("password", passWd);
        }
        postParams.add(new BasicNameValuePair("numberOfSeries", Integer.toString(seriesList.size())));
        int i = 0;
        for (String s : seriesList) {
            postParams.add(new BasicNameValuePair("series" + Integer.toString(++i), s));
        }

        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        int responseCode = response.getStatusLine().getStatusCode();

        if (responseCode != HttpURLConnection.HTTP_OK) {
            returnStatus = responseCode;
            return null;
        } else {
            InputStream inputStream = response.getEntity().getContent();
            data = IOUtils.readLines(inputStream);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }

    return data;
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithJsonWithHTTPS() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();

    properties.put("https.enabled", "true");
    properties.put("https.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("https.hostname", "localhost");
    properties.put("https.selfSigned", "true");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {/* ww w.j  a va 2 s  . c om*/
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        SSLContextBuilder builder = SSLContexts.custom();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLContext sslContext = builder.build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new X509HostnameVerifier() {
                    @Override
                    public void verify(String host, SSLSocket ssl) throws IOException {
                    }

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

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

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

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

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build());

        RestTemplate httpClient = new RestTemplate(requestFactory);
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}

From source file:com.liferay.sync.engine.session.Session.java

private static SSLConnectionSocketFactory _getTrustingSSLSocketFactory() throws Exception {

    if (_trustingSSLSocketFactory == null) {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        sslContextBuilder.loadTrustMaterial(new TrustStrategy() {

            @Override//  ww  w  .  j av  a  2s . c  o  m
            public boolean isTrusted(X509Certificate[] x509Certificates, String authType) {

                return true;
            }

        });

        _trustingSSLSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
                new NoopHostnameVerifier());
    }

    return _trustingSSLSocketFactory;
}

From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java

protected SSLContext createSSLContext() {
    if (!trustAllSSLCertificates) {
        return null;
    }/*from  w  ww. j a  v  a 2  s .  c  o m*/
    SSLContext sslcontext;
    try {
        sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
                return true;
            }
        }).build();
    } catch (Exception e) {
        throw new CollectorException("Cannot create SSL context trusting all certificates.", e);
    }
    return sslcontext;
}

From source file:com.ibm.dataworks.DataLoadResource.java

/** 
 * Create an HTTP client object that is authenticated with the user and password
 * of the IBM DataWorks Service./*from  www  .  j a  v a 2  s. c  om*/
 */
private HttpClient getAuthenticatedHttpClient() throws GeneralSecurityException {
    // NOTE: If you re-purpose this code for your own application you might want to have 
    // additional security mechanisms in place regarding certificate authentication.

    // build credentials object
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(vcapInfo.getUser(),
            vcapInfo.getPassword());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
    // For demo purposes only: always accept the certificate 
    TrustStrategy accepAllTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };
    SSLContextBuilder contextBuilder = new SSLContextBuilder();
    SSLContext context = contextBuilder.loadTrustMaterial(null, accepAllTrustStrategy).build();
    SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(context, new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create() //
            .setSSLSocketFactory(scsf) //
            .setDefaultCredentialsProvider(credsProvider) //
            .build();

    return httpClient;
}

From source file:org.syncany.plugins.webdav.WebdavTransferManager.java

private ConnectionSocketFactory initSsl() throws Exception {
    TrustStrategy trustStrategy = new TrustStrategy() {
        @Override//  w  w  w.j a  v a  2 s.  c om
        public boolean isTrusted(X509Certificate[] certificateChain, String authType)
                throws CertificateException {
            logger.log(Level.INFO, "WebDAV: isTrusted(" + certificateChain.toString() + ", " + authType + ")");

            try {
                // First check if already in trust store, if so; okay!
                X509Certificate serverCertificate = certificateChain[0];

                for (int i = 0; i < certificateChain.length; i++) {
                    X509Certificate certificate = certificateChain[i];

                    logger.log(Level.FINE,
                            "WebDAV: Checking certificate validity: " + certificate.getSubjectDN().toString());
                    logger.log(Level.FINEST, "WebDAV:              Full certificate: " + certificate);

                    // Check validity
                    try {
                        certificate.checkValidity();
                    } catch (CertificateException e) {
                        logger.log(Level.FINE, "WebDAV: Certificate is NOT valid.", e);
                        return false;
                    }

                    logger.log(Level.FINE, "WebDAV: Checking is VALID.");

                    // Certificate found; we trust this, okay!
                    if (inTrustStore(certificate)) {
                        logger.log(Level.FINE, "WebDAV: Certificate found in trust store.");
                        return true;
                    }

                    // Certificate is new; continue ...
                    else {
                        logger.log(Level.FINE, "WebDAV: Certificate NOT found in trust store.");
                    }
                }

                // We we reach this code, none of the CAs are known in the trust store
                // So we ask the user if he/she wants to add the server certificate to the trust store  
                UserInteractionListener userInteractionListener = getSettings().getUserInteractionListener();

                if (userInteractionListener == null) {
                    throw new RuntimeException("pluginListener cannot be null!");
                }

                boolean userTrustsCertificate = userInteractionListener.onUserConfirm(
                        "Unknown SSL/TLS certificate", formatCertificate(serverCertificate),
                        "Do you want to trust this certificate?");

                if (!userTrustsCertificate) {
                    logger.log(Level.INFO, "WebDAV: User does not trust certificate. ABORTING.");
                    throw new RuntimeException("User does not trust certificate. ABORTING.");
                }

                logger.log(Level.INFO, "WebDAV: User trusts certificate. Adding to trust store.");
                addToTrustStore(serverCertificate);

                return true;
            } catch (KeyStoreException e) {
                logger.log(Level.SEVERE, "WebDAV: Key store exception.", e);
                return false;
            }
        }

        private boolean inTrustStore(X509Certificate certificate) throws KeyStoreException {
            String certAlias = getCertificateAlias(certificate);
            return UserConfig.getUserTrustStore().containsAlias(certAlias);
        }

        private void addToTrustStore(X509Certificate certificate) throws KeyStoreException {
            String certAlias = getCertificateAlias(certificate);
            UserConfig.getUserTrustStore().setCertificateEntry(certAlias, certificate);

            hasNewCertificates = true;
        }

        private String getCertificateAlias(X509Certificate certificate) {
            return StringUtil.toHex(certificate.getSignature());
        }
    };

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustStrategy).useTLS().build();

    return new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
}