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:com.lp.alm.lyo.client.oslc.OslcClient.java

private void setupSSLSupport() {
    ClientConnectionManager connManager = httpClient.getConnectionManager();
    SchemeRegistry schemeRegistry = connManager.getSchemeRegistry();
    schemeRegistry.unregister("https");
    /** Create a trust manager that does not validate certificate chains */
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*from w  ww.  jav a 2 s  .  com*/
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            /** Ignore Method Call */
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            /** Ignore Method Call */
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };

    try {
        SSLContext sc = findInstalledSecurityContext();
        if (trustManagers == null) {
            trustManagers = trustAllCerts;
        }
        if (hostnameVerifier == null) {
            hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        }
        sc.init(null, trustManagers, new java.security.SecureRandom());
        SSLSocketFactory sf = new SSLSocketFactory(sc, hostnameVerifier);
        Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
        schemeRegistry.register(https);
    } catch (NoSuchAlgorithmException e) {
        /* Fail Silently */
    } catch (KeyManagementException e) {
        /* Fail Silently */
    }

}

From source file:com.cloud.network.resource.NccHttpCode.java

public static HttpClient getHttpClient() {

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

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

From source file:com.cloud.network.resource.NccHttpCode.java

public static String postHttpRequest(final String jsonCmd, final URI agentUri, String sessionID)
        throws ExecutionException {
    // 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 = getHttpClient();
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override//from   w w w. j  ava2 s  . co  m
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    };

    try {
        SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_PORT, sf));
        ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (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 {
        HttpPost request = new HttpPost(agentUri);

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

        // Unsupported commands will not route.
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            String errMsg = "Failed : HTTP error code : " + response.getStatusLine().getStatusCode();
            throw new ExecutionException(NccHttpCode.NOT_FOUND);
        } else if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                && (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED)) {
            String errMsg = "Command Not Success " + agentUri.toString() + " : HTTP error code : "
                    + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            throw new ExecutionException(NccHttpCode.INTERNAL_ERROR + " " + errMsg);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            //Successfully created the resource in the NCC, Now get the Job ID and send to the response
            // make login request and store new session id
            throw new ExecutionException(NccHttpCode.UNAUTHORIZED);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            //Successfully created the resource in the NCC, Now get the Job ID and send to the response
            result = response.getFirstHeader(NccHttpCode.JOB_ID).getValue();
        } else {
            result = EntityUtils.toString(response.getEntity());
            String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
            s_logger.debug("POST response is " + logResult);
        }

    } catch (ClientProtocolException protocolEx) {
        // Problem with HTTP message exchange
        s_logger.error(protocolEx);
    } catch (IOException connEx) {
        // Problem with underlying communications
        s_logger.error(connEx);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return result;
}

From source file:com.pari.ic.ICManager.java

public DefaultHttpClient getSecuredHttpClient(HttpClient httpClient) throws Exception {
    final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
    try {//w  w w. j av a 2  s  . com
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return _AcceptedIssuers;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, new SecureRandom());
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = httpClient.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
        return new DefaultHttpClient(ccm, httpClient.getParams());
    } catch (Exception e) {
        throw e;
    }
}

From source file:org.dasein.cloud.vcloud.vCloudMethod.java

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

    if (ctx == null) {
        throw new CloudException("No context was defined for this request");
    }//  ww  w .  j av  a2s. com
    String endpoint = ctx.getCloud().getEndpoint();

    if (endpoint == null) {
        throw new CloudException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");
    int targetPort;
    URI uri;

    try {
        uri = new URI(endpoint);
        targetPort = uri.getPort();
        if (targetPort < 1) {
            targetPort = (ssl ? 443 : 80);
        }
    } catch (URISyntaxException e) {
        throw new CloudException(e);
    }
    HttpHost targetHost = new HttpHost(uri.getHost(), targetPort, uri.getScheme());
    HttpParams params = new BasicHttpParams();

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

    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);

    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();
        }
    }
    if (forAuthentication) {
        String accessPublic = null;
        String accessPrivate = null;
        try {
            List<ContextRequirements.Field> fields = provider.getContextRequirements().getConfigurableValues();
            for (ContextRequirements.Field f : fields) {
                if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) {
                    byte[][] keyPair = (byte[][]) provider.getContext().getConfigurationValue(f);
                    accessPublic = new String(keyPair[0], "utf-8");
                    accessPrivate = new String(keyPair[1], "utf-8");
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
        String password = accessPrivate;
        String userName;

        if (matches(getAPIVersion(), "0.8", "0.8")) {
            userName = accessPublic;
        } else {
            userName = accessPublic + "@" + ctx.getAccountNumber();
        }

        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));
    }
    return client;
}

From source file:org.apache.cloudstack.storage.datastore.util.SolidFireUtil.java

private static DefaultHttpClient getHttpClient(int iPort) {
    try {//w  ww.  j a  va2s.  c o m
        SSLContext sslContext = SSLUtils.getSSLContext();
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

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

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, new SecureRandom());

        SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();

        registry.register(new Scheme("https", iPort, socketFactory));

        BasicClientConnectionManager mgr = new BasicClientConnectionManager(registry);
        DefaultHttpClient client = new DefaultHttpClient();

        return new DefaultHttpClient(mgr, client.getParams());
    } catch (NoSuchAlgorithmException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (KeyManagementException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    }
}

From source file:com.infinities.skyport.openstack.nova.os.SkyportNovaMethod.java

@Override
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 2s.  c  om
    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() {

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