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

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

Introduction

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

Prototype

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

Source Link

Usage

From source file:org.opendedup.sdfs.filestore.cloud.BatchAwsS3ChunkStore.java

@Override
public boolean checkAccess(String username, String password, Properties props) throws Exception {
    BasicAWSCredentials _cred = new BasicAWSCredentials(username, password);
    if (props.containsKey("default-bucket-location")) {
        bucketLocation = RegionUtils.getRegion(props.getProperty("default-bucket-location"));
    }/*  w ww. j a v  a 2  s  .  com*/

    ClientConfiguration clientConfig = new ClientConfiguration();
    clientConfig.setMaxConnections(Main.dseIOThreads * 2);
    clientConfig.setConnectionTimeout(10000);
    clientConfig.setSocketTimeout(10000);
    String s3Target = null;

    if (props.containsKey("s3-target")) {
        s3Target = props.getProperty("s3-target");
    }
    if (props.containsKey("proxy-host")) {
        clientConfig.setProxyHost(props.getProperty("proxy-host"));
    }
    if (props.containsKey("proxy-domain")) {
        clientConfig.setProxyDomain(props.getProperty("proxy-domain"));
    }
    if (props.containsKey("proxy-password")) {
        clientConfig.setProxyPassword(props.getProperty("proxy-password"));
    }
    if (props.containsKey("proxy-port")) {
        clientConfig.setProxyPort(Integer.parseInt(props.getProperty("proxy-port")));
    }
    if (props.containsKey("proxy-username")) {
        clientConfig.setProxyUsername(props.getProperty("proxy-username"));
    }
    s3Service = new AmazonS3Client(_cred, clientConfig);
    if (s3Target != null) {
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] certificate, String authType) {
                return true;
            }
        };
        SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        clientConfig.getApacheHttpClientConfig().withSslSocketFactory(sf);
        s3Service.setEndpoint(s3Target);
    }
    s3Service.listBuckets();
    return true;
}

From source file:com.cloud.hypervisor.hyperv.resource.HypervDirectConnectResource.java

public static String postHttpRequest(final String jsonCmd, final URI agentUri) {
    // Using Apache's HttpClient for HTTP POST
    // Java-only approach discussed at on StackOverflow concludes with
    // comment to use Apache HttpClient
    // http://stackoverflow.com/a/2793153/939250, but final comment is to
    // use Apache.
    String logMessage = StringEscapeUtils.unescapeJava(jsonCmd);
    logMessage = cleanPassword(logMessage);
    s_logger.debug("POST request to " + agentUri.toString() + " with contents " + logMessage);

    // Create request
    HttpClient httpClient = null;/*from   w  w  w .  j  a  va  2  s . c  om*/
    final TrustStrategy easyStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
            return true;
        }
    };

    try {
        final SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_AGENT_PORT, sf));
        final ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (final KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final KeyStoreException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    }

    String result = null;

    // TODO: are there timeout settings and worker thread settings to tweak?
    try {
        final HttpPost request = new HttpPost(agentUri);

        // JSON encode command
        // Assumes command sits comfortably in a string, i.e. not used for
        // large data transfers
        final StringEntity cmdJson = new StringEntity(jsonCmd);
        request.addHeader("content-type", "application/json");
        request.setEntity(cmdJson);
        s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage);
        final HttpResponse response = httpClient.execute(request);

        // Unsupported commands will not route.
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            final String errMsg = "Failed to send : HTTP error code : "
                    + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            final String unsupportMsg = "Unsupported command " + agentUri.getPath()
                    + ".  Are you sure you got the right type of" + " server?";
            final Answer ans = new UnsupportedAnswer(null, unsupportMsg);
            s_logger.error(ans);
            result = s_gson.toJson(new Answer[] { ans });
        } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            final String errMsg = "Failed send to " + agentUri.toString() + " : HTTP error code : "
                    + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            return null;
        } else {
            result = EntityUtils.toString(response.getEntity());
            final String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
            s_logger.debug("POST response is " + logResult);
        }
    } catch (final ClientProtocolException protocolEx) {
        // Problem with HTTP message exchange
        s_logger.error(protocolEx);
    } catch (final IOException connEx) {
        // Problem with underlying communications
        s_logger.error(connEx);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return result;
}

From source file:org.bigmouth.nvwa.network.http.HttpClientHelper.java

private static HttpClient getHttpClient(SSLContext ctx, ClientConnectionManager ccm, int port, int timeout) {
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(//  ww w. j a va 2s .  c  o  m
            new Scheme("https", port, new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
    HttpClient httpClient = new DefaultHttpClient(ccm);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_KEEPALIVE, true);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
    return httpClient;
}

From source file:org.craftercms.profile.impl.ProfileRestClientService.java

private DefaultHttpClient getHttpClient(int connectionTimeOut, int sockeTimeOut) {
    try {//from  w w w .  ja  va2s .  c om

        HttpParams httpParams = new BasicHttpParams();

        setParams(httpParams, connectionTimeOut, sockeTimeOut);

        SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", port, PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme("https", sslPort, sf));

        PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
        HttpHost localhost = new HttpHost(host, port);
        ccm.setMaxPerRoute(new HttpRoute(localhost), maxPerRoute);
        ccm.setMaxTotal(maxTotal);
        ccm.setDefaultMaxPerRoute(defaultMaxPerRoute);
        return new DefaultHttpClient(ccm, httpParams);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return new DefaultHttpClient();
    }
}

From source file:org.dasein.cloud.openstack.nova.os.AbstractMethod.java

protected @Nonnull HttpClient getClient() throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new InternalException("No context was defined for this request");
    }/*from   ww w .  j av  a  2 s.  com*/
    String endpoint = ctx.getCloud().getEndpoint();

    if (endpoint == null) {
        throw new InternalException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");

    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (provider.isInsecure()) {
        try {
            client.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {

                        public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                                throws CertificateException {
                            return true;
                        }
                    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    return client;
}

From source file:org.hyperic.util.security.DatabaseSSLProviderImpl.java

public DatabaseSSLProviderImpl(KeystoreConfig keystoreConfig, boolean acceptUnverifiedCertificates) {
    if (log.isDebugEnabled()) {
        log.debug("Keystore info: alias=" + keystoreConfig.getAlias() + ", path:" + keystoreConfig.getFilePath()
                + ", acceptUnverifiedCertificates=" + acceptUnverifiedCertificates);
    }//  w  ww . ja  v  a 2 s  .  c  o m
    boolean hasLock = false;
    final boolean debug = log.isDebugEnabled();
    final StopWatch watch = new StopWatch();
    try {
        KeystoreManager keystoreMgr = KeystoreManager.getKeystoreManager();
        KEYSTORE_READER_LOCK.lockInterruptibly();
        hasLock = true;
        KeyStore trustStore = keystoreMgr.getKeyStore(keystoreConfig);
        KeyManagerFactory keyManagerFactory = getKeyManagerFactory(trustStore,
                keystoreConfig.getFilePassword());
        TrustManagerFactory trustManagerFactory = getTrustManagerFactory(trustStore);
        X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
        X509TrustManager customTrustManager = getCustomTrustManager(defaultTrustManager, keystoreConfig,
                acceptUnverifiedCertificates, trustStore);
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { customTrustManager },
                new SecureRandom());
        // XXX Should we use ALLOW_ALL_HOSTNAME_VERIFIER (least restrictive) or 
        //     BROWSER_COMPATIBLE_HOSTNAME_VERIFIER (moderate restrictive) or
        //     STRICT_HOSTNAME_VERIFIER (most restrictive)???
        sslSocketFactory = new SSLSocketFactory(sslContext, getHostnameVerifier());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    } finally {
        if (hasLock)
            KEYSTORE_READER_LOCK.unlock();
        if (debug)
            log.debug("readCert: " + watch);
    }
}

From source file:org.hyperic.util.security.DefaultSSLProviderImpl.java

public DefaultSSLProviderImpl(KeystoreConfig keystoreConfig, boolean acceptUnverifiedCertificates) {
    if (log.isDebugEnabled()) {
        log.debug("Keystore info: alias=" + keystoreConfig.getAlias() + ", acceptUnverifiedCertificates="
                + acceptUnverifiedCertificates);
    }/*from  w  w  w  . ja  va  2s. c om*/
    final boolean debug = log.isDebugEnabled();
    final StopWatch watch = new StopWatch();
    try {
        KeystoreManager keystoreMgr = KeystoreManager.getKeystoreManager();
        KeyStore trustStore = keystoreMgr.getKeyStore(keystoreConfig);
        KeyManagerFactory keyManagerFactory = getKeyManagerFactory(trustStore,
                keystoreConfig.getFilePassword());
        TrustManagerFactory trustManagerFactory = getTrustManagerFactory(trustStore);
        X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
        X509TrustManager customTrustManager = keystoreMgr.getCustomTrustManager(defaultTrustManager,
                keystoreConfig, acceptUnverifiedCertificates, trustStore);
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { customTrustManager },
                new SecureRandom());
        // XXX Should we use ALLOW_ALL_HOSTNAME_VERIFIER (least restrictive) or 
        //     BROWSER_COMPATIBLE_HOSTNAME_VERIFIER (moderate restrictive) or
        //     STRICT_HOSTNAME_VERIFIER (most restrictive)???
        sslSocketFactory = new SSLSocketFactory(sslContext, getHostnameVerifier());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    } finally {
        if (debug)
            log.debug("readCert: " + watch);
    }
}

From source file:org.sonatype.nexus.plugins.webhook.WebHookNotifier.java

/**
 * Instantiate a new {@link HttpClient} instance, configured to accept all SSL certificates, and use proxy settings
 * from Nexus.//from  www.j  a v a 2s .  com
 * 
 * @return an {@link HttpClient} instance - won't be null
 */
private HttpClient instantiateHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // configure user-agent
    HttpProtocolParams.setUserAgent(httpClient.getParams(), "Nexus WebHook Plugin");

    // configure SSL
    SSLSocketFactory socketFactory = null;
    try {
        socketFactory = new SSLSocketFactory(new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    } catch (UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }
    httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));

    // configure proxy
    if (proxySettings != null && proxySettings.isEnabled()) {
        HttpHost proxy = new HttpHost(proxySettings.getHostname(), proxySettings.getPort());
        if (UsernamePasswordRemoteAuthenticationSettings.class
                .isInstance(proxySettings.getProxyAuthentication())) {
            UsernamePasswordRemoteAuthenticationSettings proxyAuthentication = (UsernamePasswordRemoteAuthenticationSettings) proxySettings
                    .getProxyAuthentication();
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(proxySettings.getHostname(), proxySettings.getPort()),
                    new UsernamePasswordCredentials(proxyAuthentication.getUsername(),
                            proxyAuthentication.getPassword()));
        }
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    return httpClient;
}