Example usage for javax.net.ssl SSLContext getDefault

List of usage examples for javax.net.ssl SSLContext getDefault

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getDefault.

Prototype

public static SSLContext getDefault() throws NoSuchAlgorithmException 

Source Link

Document

Returns the default SSL context.

Usage

From source file:cn.ctyun.amazonaws.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config//from ww  w . j av  a2 s  .  c om
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    /* Set connection manager */
    ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory
            .createThreadSafeClientConnManager(config, httpClientParams);
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams);
    httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());

        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);

        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to access default SSL context", e);
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty("com.amazonaws.sdk.disableCertChecking") != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        AmazonHttpClient.log
                .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    return httpClient;
}

From source file:com.sonatype.nexus.ssl.plugin.internal.repository.RepositoryClientConnectionOperatorSelectorTest.java

/**
 * Verify that an no {@link ClientConnectionOperator} is returned when trust store is enabled but no repository
 * present in context under {@link HttpClientFactory#HTTP_CTX_KEY_REPOSITORY} key.
 *//*ww  w . ja v a  2 s. c om*/
@Test
public void noOperatorReturnedWhenTrustStoreIsEnabledButNoRepositoryInHttpContext() throws Exception {
    final Repository repository = mock(Repository.class);
    when(repository.getId()).thenReturn("foo");

    final TrustStore trustStore = mock(TrustStore.class);
    when(trustStore.getSSLContextFor(repositoryTrustStoreKey("foo"))).thenReturn(SSLContext.getDefault());

    final HttpContext httpContext = mock(HttpContext.class);

    final RepositoryClientConnectionOperatorSelector underTest = new RepositoryClientConnectionOperatorSelector(
            trustStore);
    final SSLContext context = underTest.select(httpContext);

    assertThat(context, is(nullValue()));
}

From source file:com.sinacloud.scs.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config//ww  w  .  j ava2 s  .com
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
@SuppressWarnings("deprecation")
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    PoolingClientConnectionManager connectionManager = ConnectionManagerFactory
            .createPoolingClientConnManager(config, httpClientParams);
    SdkHttpClient httpClient = new SdkHttpClient(connectionManager, httpClientParams);
    if (config.getMaxErrorRetry() > 0)
        httpClient.setHttpRequestRetryHandler(SdkHttpRequestRetryHandler.Singleton);
    //        httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

        Scheme https = new Scheme("https", sf, 443);
        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new SCSClientException("Unable to access default SSL context", e);
    }

    //        /* 
    //         * If SSL cert checking for endpoints has been explicitly disabled,
    //         * register a new scheme for HTTPS that won't cause self-signed certs to
    //         * error out.
    //         */
    //        if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
    Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
    httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    //        }

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        //            AmazonHttpClient.log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    return httpClient;
}

From source file:at.diamonddogs.net.ssl.CustomSSLSocketFactory.java

/**
 * @see org.apache.http.conn.scheme.LayeredSocketFactory#createSocket(java.net.Socket,
 *      java.lang.String, int, boolean)/*w  ww  .j a v  a2 s. co m*/
 */
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
        throws IOException, UnknownHostException {
    if (sslcontext != null) {
        return sslcontext.getSocketFactory().createSocket(socket, host, port, autoClose);
    } else {
        try {
            return SSLContext.getDefault().getSocketFactory().createSocket(socket, host, port, autoClose);
        } catch (Exception e) {
            return null;
        }
    }
}

From source file:pt.lunacloud.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config/* w  ww. java2  s . c om*/
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Form User-Agent information */
    String userAgent = config.getUserAgent();
    if (!(userAgent.equals(ClientConfiguration.DEFAULT_USER_AGENT))) {
        userAgent += ", " + ClientConfiguration.DEFAULT_USER_AGENT;
    }

    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(httpClientParams, userAgent);
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, false);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    /* Set connection manager */
    ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory
            .createThreadSafeClientConnManager(config, httpClientParams);
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams);
    httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());

        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);

        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new LunacloudClientException("Unable to access default SSL context");
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty("com.amazonaws.sdk.disableCertChecking") != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        AmazonHttpClient.log
                .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    return httpClient;
}

From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java

/**
 * This method is the entry point to the invocation of a remote REST
 * service. It accepts a number of parameters from the related REST activity
 * and uses those to assemble, execute and fetch results of a relevant HTTP
 * request./* www  .ja v a  2s  . c o m*/
 *
 * @param requestURL
 *            The URL for the request to be made. This cannot be taken from
 *            the <code>configBean</code>, because this should be the
 *            complete URL which may be directly used to make the request (
 *            <code>configBean</code> would only contain the URL signature
 *            associated with the REST activity).
 * @param configBean
 *            Configuration of the associated REST activity is passed to
 *            this class as a configuration bean. Settings such as HTTP
 *            method, MIME types for "Content-Type" and "Accept" headers,
 *            etc are taken from the bean.
 * @param inputMessageBody
 *            Body of the message to be sent to the server - only needed for
 *            POST and PUT requests; for GET and DELETE it will be
 *            discarded.
 * @return
 */
@SuppressWarnings("deprecation")
public static HTTPRequestResponse initiateHTTPRequest(String requestURL,
        RESTActivityConfigurationBean configBean, Object inputMessageBody, Map<String, String> urlParameters,
        CredentialsProvider credentialsProvider) {
    ClientConnectionManager connectionManager = null;
    if (requestURL.toLowerCase().startsWith("https")) {
        // Register a protocol scheme for https that uses Taverna's
        // SSLSocketFactory
        try {
            URL url = new URL(requestURL); // the URL object which will
            // parse the port out for us
            int port = url.getPort();
            if (port == -1) // no port was defined in the URL
                port = HTTPS_DEFAULT_PORT; // default HTTPS port
            Scheme https = new Scheme("https",
                    new org.apache.http.conn.ssl.SSLSocketFactory(SSLContext.getDefault()), port);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(https);
            connectionManager = new SingleClientConnManager(null, schemeRegistry);
        } catch (MalformedURLException ex) {
            logger.error("Failed to extract port from the REST service URL: the URL " + requestURL
                    + " is malformed.", ex);
            // This will cause the REST activity to fail but this method
            // seems not to throw an exception so we'll just log the error
            // and let it go through
        } catch (NoSuchAlgorithmException ex2) {
            // This will cause the REST activity to fail but this method
            // seems not to throw an exception so we'll just log the error
            // and let it go through
            logger.error("Failed to create SSLContext for invoking the REST service over https.", ex2);
        }
    }

    switch (configBean.getHttpMethod()) {
    case GET:
        return doGET(connectionManager, requestURL, configBean, urlParameters, credentialsProvider);
    case POST:
        return doPOST(connectionManager, requestURL, configBean, inputMessageBody, urlParameters,
                credentialsProvider);
    case PUT:
        return doPUT(connectionManager, requestURL, configBean, inputMessageBody, urlParameters,
                credentialsProvider);
    case DELETE:
        return doDELETE(connectionManager, requestURL, configBean, urlParameters, credentialsProvider);
    default:
        return new HTTPRequestResponse(new Exception(
                "Error: something went wrong; " + "no failure has occurred, but but unexpected HTTP method (\""
                        + configBean.getHttpMethod() + "\") encountered."));
    }
}

From source file:org.dataconservancy.archive.impl.fcrepo.ri.MultiThreadedHttpClient.java

private static SSLSocketFactory createSSLSocketFactory(boolean skipSSLTrustCheck,
        boolean skipSSLHostnameVerification) {
    SSLContext sslContext = null;
    try {/*from   w w w.j  a  va2  s . co m*/
        if (skipSSLTrustCheck) {
            sslContext = SSLContext.getInstance("TLS");
            TrustManager easyTrustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Oh, I am easy!
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Oh, I am easy!
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
        } else {
            sslContext = SSLContext.getDefault();
        }
    } catch (KeyManagementException wontHappen) {
        throw new RuntimeException(wontHappen);
    } catch (NoSuchAlgorithmException wontHappen) {
        throw new RuntimeException(wontHappen);
    }
    SSLSocketFactory factory = new SSLSocketFactory(sslContext);
    if (skipSSLHostnameVerification) {
        factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
    return factory;
}

From source file:de.minehattan.xmppchat.XMPPChat.java

/**
 * Returns the applicable SSLContext. May return {@code null} if no default
 * context is available./*from w  ww.  j  av  a  2  s  .  c om*/
 * 
 * @return the SSLContext
 */
@Nullable
private SSLContext getContext() {
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getDefault();
    } catch (NoSuchAlgorithmException e) {
        // TODO although this is unlikely to happen, returning null is ugly!
        CommandBook.logger().log(Level.SEVERE, "Failed to get default SSL context.", e);
        return null;
    }

    if (config.xmppSSLUseSelfSigned) {

        try {
            sslContext = JavaPinning.forPin(config.xmppSSLCertificatePin);
        } catch (KeyManagementException e) {
            CommandBook.logger().log(Level.SEVERE,
                    "Failed to use configured certificate pin, using the default SSL context instead.", e);
        } catch (NoSuchAlgorithmException e) {
            CommandBook.logger().log(Level.SEVERE,
                    "Failed to use configured certificate pin due to an unsupported algorithm, using the default SSL context instead.",
                    e);
        }
    }

    return sslContext;
}

From source file:com.sonatype.nexus.ssl.plugin.internal.repository.RepositoryClientConnectionOperatorSelectorTest.java

/**
 * Verify that an no {@link ClientConnectionOperator} is returned when trust store is enabled but under
 * {@link HttpClientFactory#HTTP_CTX_KEY_REPOSITORY} key is not a repository.
 *///from w w  w. j  a v  a2  s  . c om
@Test
public void noOperatorReturnedWhenTrustStoreIsEnabledButHttpContextContainsAnotherTypeUnderKey()
        throws Exception {
    final Repository repository = mock(Repository.class);
    when(repository.getId()).thenReturn("foo");

    final TrustStore trustStore = mock(TrustStore.class);
    when(trustStore.getSSLContextFor(repositoryTrustStoreKey("foo"))).thenReturn(SSLContext.getDefault());

    final HttpContext httpContext = mock(HttpContext.class);
    when(httpContext.getAttribute(HttpClientFactory.HTTP_CTX_KEY_REPOSITORY)).thenReturn(new Object());

    final RepositoryClientConnectionOperatorSelector underTest = new RepositoryClientConnectionOperatorSelector(
            trustStore);
    final SSLContext context = underTest.select(httpContext);

    assertThat(context, is(nullValue()));
}