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.cloudbees.eclipse.core.util.Utils.java

/**
 * @param url/*from   ww  w .j  a v a2 s . co  m*/
 *          url to connec. Required to determine proxy settings if available. If <code>null</code> then proxy is not
 *          configured for the client returned.
 * @return
 * @throws CloudBeesException
 */
public final static DefaultHttpClient getAPIClient(String url) throws CloudBeesException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpClientParams.setCookiePolicy(httpclient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);

        String version = null;
        if (CloudBeesCorePlugin.getDefault() != null) {
            version = CloudBeesCorePlugin.getDefault().getBundle().getVersion().toString();
        } else {
            version = "n/a";
        }
        HttpProtocolParams.setUserAgent(httpclient.getParams(), "CBEclipseToolkit/" + version);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

        CloudBeesCorePlugin plugin = CloudBeesCorePlugin.getDefault();

        URL truststore;

        if (plugin == null) {
            //Outside the OSGI environment, try to open the stream from the current dir.
            truststore = new File("truststore").toURI().toURL();
        } else {
            truststore = plugin.getBundle().getResource("truststore");
        }

        InputStream instream = truststore.openStream();

        try {
            trustStore.load(instream, "123456".toCharArray());
        } finally {
            instream.close();
        }

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

        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustStore,
                null, trustAllStrategy, SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        // Override https handling to use provided truststore
        @SuppressWarnings("deprecation")
        Scheme sch = new Scheme("https", socketFactory, 443);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);

        HttpParams params = httpclient.getParams();

        //TODO Make configurable from the UI?
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        if (CloudBeesCorePlugin.getDefault() != null) { // exclude proxy support when running outside eclipse
            IProxyService ps = CloudBeesCorePlugin.getDefault().getProxyService();
            if (ps.isProxiesEnabled()) {

                IProxyData[] pr = ps.select(new URI(url));

                //NOTE! For now we use just the first proxy settings with type HTTP or HTTPS to try out the connection. If configuration has more than 1 conf then for now this likely won't work!
                if (pr != null) {
                    for (int i = 0; i < pr.length; i++) {

                        IProxyData prd = pr[i];

                        if (IProxyData.HTTP_PROXY_TYPE.equals(prd.getType())
                                || IProxyData.HTTPS_PROXY_TYPE.equals(prd.getType())) {

                            String proxyHost = prd.getHost();
                            int proxyPort = prd.getPort();
                            String proxyUser = prd.getUserId();
                            String proxyPass = prd.getPassword();

                            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                            if (prd.isRequiresAuthentication()) {
                                List authpref = new ArrayList();
                                authpref.add(AuthPolicy.BASIC);
                                AuthScope authScope = new AuthScope(proxyHost, proxyPort);
                                httpclient.getCredentialsProvider().setCredentials(authScope,
                                        new UsernamePasswordCredentials(proxyUser, proxyPass));
                            }

                            break;

                        }

                    }
                }
            }
        }

        /*      httpclient.getHostConfiguration().setProxy(proxyHost,proxyPort);      
              //if there are proxy credentials available, set those too
              Credentials proxyCredentials = null;
              String proxyUser = beesClientConfiguration.getProxyUser();
              String proxyPassword = beesClientConfiguration.getProxyPassword();
              if(proxyUser != null || proxyPassword != null)
        proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
              if(proxyCredentials != null)
        client.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials);
                
        */

        return httpclient;

    } catch (Exception e) {
        throw new CloudBeesException("Error while initiating access to JSON APIs!", e);
    }
}

From source file:com.adobe.acs.commons.http.impl.HttpClientFactoryImpl.java

@Activate
protected void activate(Map<String, Object> config) throws Exception {
    boolean useSSL = PropertiesUtil.toBoolean(config.get(PROP_USE_SSL), DEFAULT_USE_SSL);

    String scheme = useSSL ? "https" : "http";
    String hostname = PropertiesUtil.toString(config.get(PROP_HOST_DOMAIN), null);
    int port = PropertiesUtil.toInteger(config.get(PROP_GATEWAY_PORT), 0);

    if (hostname == null || port == 0) {
        throw new IllegalArgumentException("Configuration not valid. Both host and port must be provided.");
    }/* w ww .j a v  a 2 s.  c  o m*/

    baseUrl = String.format("%s://%s:%s", scheme, hostname, port);

    int connectTimeout = PropertiesUtil.toInteger(config.get(PROP_CONNECT_TIMEOUT), DEFAULT_CONNECT_TIMEOUT);
    int soTimeout = PropertiesUtil.toInteger(config.get(PROP_SO_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);

    HttpClientBuilder builder = httpClientBuilderFactory.newBuilder();

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
            .setSocketTimeout(soTimeout).build();
    builder.setDefaultRequestConfig(requestConfig);

    boolean disableCertCheck = PropertiesUtil.toBoolean(config.get(PROP_DISABLE_CERT_CHECK),
            DEFAULT_DISABLE_CERT_CHECK);

    if (useSSL && disableCertCheck) {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
        builder.setHostnameVerifier(new AllowAllHostnameVerifier()).setSslcontext(sslContext);
    }
    httpClient = builder.build();
    executor = Executor.newInstance(httpClient);

    String username = PropertiesUtil.toString(config.get(PROP_USERNAME), null);
    String password = PropertiesUtil.toString(config.get(PROP_PASSWORD), null);
    if (username != null && password != null) {
        HttpHost httpHost = new HttpHost(hostname, port, useSSL ? "https" : "http");
        executor.auth(httpHost, username, password).authPreemptive(httpHost);
    }
}

From source file:com.nridge.connector.common.con_com.crawl.CrawlStart.java

private CloseableHttpClient createHttpClient() throws NSException {
    Logger appLogger = mAppMgr.getLogger(this, "createHttpClient");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    // http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java
    // http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3

    CloseableHttpClient httpClient = null;
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    try {/*  w  ww  .  ja v a 2 s.c  o m*/

        // Note: This logic will trust CA and self-signed certificates.

        sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] aChain, String anAuthType) throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                sslContextBuilder.build());
        httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
    } catch (Exception e) {
        String msgStr = String.format("HTTP Client Error: %s", e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return httpClient;
}

From source file:net.dataninja.oracle.client.DataNinjaHttpClient.java

private HttpClient getHttpClient()
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    // Keep only one copy of the HttpClient
    if (httpClient != null) {
        return httpClient;
    }/*w w  w.  j  ava2s .  c o  m*/

    // Create a new instance of HTTPClient
    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] cert, String authType) throws CertificateException {
            return true;
        }
    };
    SSLSocketFactory factory = new SSLSocketFactory(acceptingTrustStrategy,
            SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 443, factory));
    ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

    httpClient = new DefaultHttpClient(ccm);
    return httpClient;
}

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

private static List<String> connectAndReadFromURL(URL url, String fileName, String userId, String passWd) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override// ww w . j ava2s.c  o  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));
        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.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>();
        postParams.add(new BasicNameValuePair("serverManifestLoc", fileName));
        if (userId != null && passWd != null) {
            postParams.add(new BasicNameValuePair("userId", userId));
            httpPostMethod.addHeader("password", passWd);
        }

        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        int responseCode = response.getStatusLine().getStatusCode();
        // System.out.println("!!!!!Response code for requesting datda file:
        // " + responseCode);

        if (responseCode != HttpURLConnection.HTTP_OK) {
            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.dnanexus.DXHTTPRequest.java

/**
 * Construct the DXHTTPRequest using the given DXEnvironment.
 *//*from  www  .  j a v  a2  s .co  m*/
public DXHTTPRequest(DXEnvironment env) {
    this.securityContext = env.getSecurityContextJson();
    this.apiserver = env.getApiserverPath();
    this.disableRetry = env.isRetryDisabled();

    SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }

    SSLConnectionSocketFactory sslSF = null;
    try {
        sslSF = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties();
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    String proxyHostS = System.getProperty("https.proxyHost");
    String proxyPortS = System.getProperty("https.proxyPort");
    if ((proxyHost == null || proxyPort == null) && (proxyHostS == null || proxyPortS == null)) {
        this.httpclient = HttpClientBuilder.create().setUserAgent(USER_AGENT).build();
    } else {
        HttpHost proxy = null;
        if (proxyHostS != null && proxyPortS != null) {
            proxy = new HttpHost(proxyHostS, Integer.parseInt(proxyPortS));
        } else {
            proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));
        }
        httpClientBuilder.setProxy(proxy);
        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        httpClientBuilder.setRoutePlanner(routePlanner).setSSLSocketFactory(sslSF);
        httpclient = httpClientBuilder.setUserAgent(USER_AGENT).build();
    }
}

From source file:com.ibm.ws.lars.rest.RepositoryContext.java

@Override
protected void before() throws InvalidJsonAssetException, IOException, KeyManagementException,
        NoSuchAlgorithmException, KeyStoreException {

    targetHost = new HttpHost(hostname, portNumber, protocol);

    /* Create the HTTPClient that we use to make all HTTP calls */
    HttpClientBuilder b = HttpClientBuilder.create();

    // Trust all certificates
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        @Override//from www .  j a v a  2  s  .c  o m
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSslcontext(sslContext);

    // By default, it will verify the hostname in the certificate, which should be localhost
    // and therefore should match. If we start running these tests against a LARS server on
    // a different host then we may need disable hostname verification.

    context = HttpClientContext.create();

    httpClient = b.build();

    /*
     * Create the HTTPClientContext with the appropriate credentials. We'll use this whenever we
     * make an HTTP call.
     */
    if (user != null && password != null) {
        credentials = new UsernamePasswordCredentials(user, password);

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                credentials);

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
    }

    /* Clean the repository but only if the client asked us to. */
    if (cleanRepository) {
        cleanRepo();
    }
}

From source file:ru.anr.base.facade.web.api.RestClient.java

/**
 * Configuring an apache client to support untrusted ssl connections. This
 * can be useful for test purposes only.
 * /*from   w  ww. j  a  va 2s . c  o m*/
 * @return Apache {@link HttpClient}
 */
private HttpClient buildSSLClient() {

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {

            return true;
        }
    };

    try {

        SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy);
        SSLContext sslContext = sslBuilder.useTLS().build();

        SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext,
                new AllowAllHostnameVerifier());
        return HttpClients.custom().setSSLSocketFactory(sf).build();

    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) {
        throw new ApplicationException(ex);
    }
}

From source file:com.revo.deployr.client.core.impl.RClientImpl.java

public RClientImpl(String serverurl, int concurrentCallLimit, boolean allowSelfSignedSSLCert)
        throws RClientException, RSecurityException {

    log.debug("Creating client connection: serverurl=" + serverurl + ", concurrentCallLimit="
            + concurrentCallLimit + ", allowSelfSignedSSLCert=" + allowSelfSignedSSLCert);

    this.serverurl = serverurl;

    // Create and initialize HTTP parameters
    HttpParams httpParams = new BasicHttpParams();
    // Set Infinite Connection and Socket Timeouts.
    HttpConnectionParams.setConnectionTimeout(httpParams, 0);
    HttpConnectionParams.setSoTimeout(httpParams, 0);
    ConnManagerParams.setMaxTotalConnections(httpParams, concurrentCallLimit);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(concurrentCallLimit));
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    if (allowSelfSignedSSLCert) {
        /*//  ww w  . j a  v a2s. c  o  m
         * Register scheme for "https" that bypasses
         * SSL cert trusted-origin verification check
         * which makes it possible to connect to a
         * DeployR server using a self-signed certificate.
         *
         * Recommended for prototyping and testing only,
         * not recommended for production environments.
         */
        TrustStrategy blindTrust = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] certificate, String authType) {
                return true;
            }
        };
        try {
            sslSocketFactory = new SSLSocketFactory(blindTrust, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            schemeRegistry.register(new Scheme("https", 8443, sslSocketFactory));
        } catch (GeneralSecurityException gsex) {
            String exMsg = "Self-signed SSL cert config failed, " + gsex.getMessage();
            log.debug(exMsg);
            throw new RSecurityException(exMsg, 0);
        }
    }

    // Create a HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    ClientConnectionManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpClient = new DefaultHttpClient(cm, httpParams);

    // Enable cookie handling by setting cookie policy on HttpClient.
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    log.debug("Created client connection: httpClient=" + httpClient);

    eService = Executors.newCachedThreadPool();

}