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

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

Introduction

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

Prototype

X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Click Source Link

Usage

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

private DefaultHttpClient getHttpClient(int connectionTimeOut, int sockeTimeOut) {
    try {//from   w  w w. j  av  a 2  s .  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");
    }/*www. jav  a  2  s  .co  m*/
    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.jboss.as.test.integration.management.api.web.ConnectorTestCase.java

public static HttpClient wrapClient(HttpClient base) {
    try {/*from   ww w  .j ava2s . c  o  m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

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

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

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.jboss.as.test.manualmode.web.ssl.SSLTruststoreUtil.java

public static DefaultHttpClient getHttpClientWithSSL(File keyStoreFile, String keyStorePassword,
        File trustStoreFile, String trustStorePassword) {

    try {/* w w w  .  j  a v  a  2s. c om*/
        final KeyStore truststore = loadKeyStore(trustStoreFile, trustStorePassword.toCharArray());
        final KeyStore keystore = keyStoreFile != null
                ? loadKeyStore(keyStoreFile, keyStorePassword.toCharArray())
                : null;
        final SSLSocketFactory ssf = new SSLSocketFactory(SSLSocketFactory.TLS, keystore, keyStorePassword,
                truststore, null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", CustomCLIExecutor.MANAGEMENT_HTTP_PORT,
                PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme("https", CustomCLIExecutor.MANAGEMENT_HTTPS_PORT, ssf));
        for (int port : HTTPSWebConnectorTestCase.HTTPS_PORTS) {
            registry.register(new Scheme("https", port, ssf));
        }
        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        LOGGER.error(
                "Creating HttpClient with customized SSL failed. We are returning the default one instead.", e);
        return new DefaultHttpClient();
    }
}

From source file:org.oscarehr.common.hl7.v2.oscar_to_oscar.SendingUtils.java

private static HttpClient getTrustAllHttpClient() {
    try {/*from ww  w  . j a v  a2s .c  o  m*/
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManager[] temp = new TrustManager[1];
        temp[0] = new CxfClientUtilsOld.TrustAllManager();
        sslContext.init(null, temp, null);

        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext);
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpClient httpClient = new DefaultHttpClient();
        ClientConnectionManager connectionManager = httpClient.getConnectionManager();
        SchemeRegistry schemeRegistry = connectionManager.getSchemeRegistry();
        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
        return (new DefaultHttpClient(connectionManager, httpClient.getParams()));
    } catch (Exception e) {
        logger.error("Unexpected error", e);
        return (null);
    }
}

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 ww  w .j  a  va 2  s .c  o m
 * 
 * @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;
}

From source file:org.whitesource.agent.client.WssServiceClientImpl.java

/**
 * Constructor//from  ww w  . j ava  2 s  .  co  m
 *
 * @param serviceUrl WhiteSource service URL to use.
 * @param setProxy WhiteSource set proxy, whether the proxy settings is defined or not.
 * @param connectionTimeoutMinutes WhiteSource connection timeout, whether the connection timeout is defined or not (default to 60 minutes).
 */
public WssServiceClientImpl(String serviceUrl, boolean setProxy, int connectionTimeoutMinutes,
        boolean ignoreCertificateCheck) {
    gson = new Gson();

    if (serviceUrl == null || serviceUrl.length() == 0) {
        this.serviceUrl = ClientConstants.DEFAULT_SERVICE_URL;
    } else {
        this.serviceUrl = serviceUrl;
    }

    if (connectionTimeoutMinutes <= 0) {
        this.connectionTimeout = ClientConstants.DEFAULT_CONNECTION_TIMEOUT_MINUTES * TO_MILLISECONDS;
    } else {
        this.connectionTimeout = connectionTimeoutMinutes * TO_MILLISECONDS;
    }

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, this.connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, this.connectionTimeout);
    HttpClientParams.setRedirecting(params, true);

    httpClient = new DefaultHttpClient();

    if (ignoreCertificateCheck) {
        try {
            logger.warn("Security Warning - Trusting all certificates");

            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            char[] password = SOME_PASSWORD.toCharArray();
            keystore.load(null, password);

            WssSSLSocketFactory sf = new WssSSLSocketFactory(keystore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

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

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

            httpClient = new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    if (setProxy) {
        findDefaultProxy();
    }
}

From source file:org.wso2.carbon.appmgt.keymgt.service.APIKeyMgtSubscriberService.java

/**
 * Renew the ApplicationAccesstoken, Call Token endpoint and get parameters.
 * Revoke old token.//from  www.  j  av  a2s  . c o  m
 * 
 * @param tokenType
 * @param oldAccessToken
 * @param allowedDomains
 * @param clientId
 * @param clientSecret
 * @param validityTime
 * @return
 * @throws Exception
 */

public String renewAccessToken(String tokenType, String oldAccessToken, String[] allowedDomains,
        String clientId, String clientSecret, String validityTime) throws Exception {
    String newAccessToken = null;
    long validityPeriod = 0;
    // create a post request to getNewAccessToken for client_credentials
    // grant type.

    //String tokenEndpoint = OAuthServerConfiguration.getInstance().getTokenEndPoint();
    String tokenEndpointName = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration().getFirstProperty(AppMConstants.API_KEY_MANAGER_TOKEN_ENDPOINT_NAME);
    String keyMgtServerURL = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration().getFirstProperty(AppMConstants.API_KEY_MANAGER_URL);
    URL keymgtURL = new URL(keyMgtServerURL);
    int keyMgtPort = keymgtURL.getPort();
    String tokenEndpoint = null;

    if (keyMgtServerURL != null) {
        String[] tmp = keyMgtServerURL.split("services");
        tokenEndpoint = tmp[0] + tokenEndpointName;
    }

    String revokeEndpoint = tokenEndpoint.replace("token", "revoke");

    // Below code is to overcome host name verification failure we get in certificate
    // validation due to self-signed certificate.
    X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    DefaultHttpClient client = new DefaultHttpClient();
    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier(hostnameVerifier);
    if (keyMgtPort >= 0) {
        registry.register(new Scheme("https", keyMgtPort, socketFactory));
    } else {
        registry.register(new Scheme("https", 443, socketFactory));
    }
    SingleClientConnManager mgr1 = new SingleClientConnManager(registry);
    SingleClientConnManager mgr2 = new SingleClientConnManager(registry);

    HttpClient tokenEPClient = new DefaultHttpClient(mgr1, client.getParams());
    HttpClient revokeEPClient = new DefaultHttpClient(mgr2, client.getParams());
    HttpPost httpTokpost = new HttpPost(tokenEndpoint);
    HttpPost httpRevokepost = new HttpPost(revokeEndpoint);

    // Request parameters.
    List<NameValuePair> tokParams = new ArrayList<NameValuePair>(3);
    List<NameValuePair> revokeParams = new ArrayList<NameValuePair>(3);

    tokParams.add(new BasicNameValuePair(OAuth.OAUTH_GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS));
    tokParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_ID, clientId));
    tokParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_SECRET, clientSecret));

    revokeParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_ID, clientId));
    revokeParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_SECRET, clientSecret));
    revokeParams.add(new BasicNameValuePair("token", oldAccessToken));

    try {
        //Revoke the Old Access Token
        httpRevokepost.setEntity(new UrlEncodedFormEntity(revokeParams, "UTF-8"));
        HttpResponse revokeResponse = tokenEPClient.execute(httpRevokepost);

        if (revokeResponse.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + revokeResponse.getStatusLine().getStatusCode());
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Successfully revoked old application access token");
            }
        }

        //Generate New Access Token
        httpTokpost.setEntity(new UrlEncodedFormEntity(tokParams, "UTF-8"));
        HttpResponse tokResponse = revokeEPClient.execute(httpTokpost);
        HttpEntity tokEntity = tokResponse.getEntity();

        if (tokResponse.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + tokResponse.getStatusLine().getStatusCode());
        } else {
            String responseStr = EntityUtils.toString(tokEntity);
            JSONObject obj = new JSONObject(responseStr);
            newAccessToken = obj.get(OAUTH_RESPONSE_ACCESSTOKEN).toString();
            validityPeriod = Long.parseLong(obj.get(OAUTH_RESPONSE_EXPIRY_TIME).toString());

            if (validityTime != null && !"".equals(validityTime)) {
                validityPeriod = Long.parseLong(validityTime);
            }
        }
    } catch (Exception e2) {
        String errMsg = "Error in getting new accessToken";
        log.error(errMsg);
        throw new APIKeyMgtException(errMsg, e2);

    }
    AppMDAO appMDAO = new AppMDAO();
    appMDAO.updateRefreshedApplicationAccessToken(tokenType, newAccessToken, validityPeriod);
    return newAccessToken;

}

From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java

/**
 * Initializes the httpClient./*from   ww  w .j a  v  a  2  s  . c  o  m*/
 */
public static void initialize() throws XPathExpressionException {

    DefaultHttpClient client = new DefaultHttpClient();

    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    Scheme sch = new Scheme("https", 443, socketFactory);
    ClientConnectionManager mgr = client.getConnectionManager();
    mgr.getSchemeRegistry().register(sch);
    httpClient = new DefaultHttpClient(mgr, client.getParams());

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
}

From source file:org.wso2.mdm.agent.proxy.utils.ServerUtilities.java

public static HttpClient getCertifiedHttpClient() throws IDPTokenManagerException {
    HttpClient client = null;/*from   w w w . ja va2s.co  m*/
    InputStream inStream = null;
    try {
        if (Constants.SERVER_PROTOCOL.equalsIgnoreCase("https://")) {
            KeyStore localTrustStore = KeyStore.getInstance("BKS");
            inStream = IdentityProxy.getInstance().getContext().getResources()
                    .openRawResource(R.raw.emm_truststore);
            localTrustStore.load(inStream, Constants.TRUSTSTORE_PASSWORD.toCharArray());

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
            HttpParams params = new BasicHttpParams();
            ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);

            client = new DefaultHttpClient(connectionManager, params);

        } else {
            client = new DefaultHttpClient();
        }

    } catch (KeyStoreException e) {
        throw new IDPTokenManagerException("Invalid keystore.", e);
    } catch (CertificateException e) {
        throw new IDPTokenManagerException("Invalid certificate.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IDPTokenManagerException("Keystore algorithm does not match.", e);
    } catch (UnrecoverableKeyException e) {
        throw new IDPTokenManagerException("Invalid keystore.", e);
    } catch (KeyManagementException e) {
        throw new IDPTokenManagerException("Invalid keystore.", e);
    } catch (IOException e) {
        throw new IDPTokenManagerException("Trust store failed to load.", e);
    } finally {
        StreamHandlerUtil.closeInputStream(inStream, TAG);
    }

    return client;
}