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

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

Introduction

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

Prototype

public static SSLSocketFactory getSystemSocketFactory() throws SSLInitializationException 

Source Link

Document

Obtains default SSL socket factory with an SSL context based on system properties as described in <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html"> "JavaTM Secure Socket Extension (JSSE) Reference Guide for the JavaTM 2 Platform Standard Edition 5</a>

Usage

From source file:com.liferay.portal.search.solr.http.SSLSocketFactoryBuilderImpl.java

@Override
public SSLSocketFactory build() throws Exception {
    KeyStore keyStore = _keyStoreLoader.load(_keyStoreType, _keyStorePath, _keyStorePassword);

    if (keyStore == null) {
        if (_log.isDebugEnabled()) {
            _log.debug("Use system defaults because there is no custom key store");
        }/*from   w  w  w  .  j av a  2 s .c o m*/

        return SSLSocketFactory.getSystemSocketFactory();
    }

    KeyStore trustKeyStore = null;

    TrustStrategy trustStrategy = null;

    if (_verifyServerCertificate) {
        trustKeyStore = _keyStoreLoader.load(_trustStoreType, _trustStorePath, _trustStorePassword);

        if (trustKeyStore == null) {
            if (_log.isDebugEnabled()) {
                _log.debug("Use system defaults because there is no custom " + "trust store");
            }

            return SSLSocketFactory.getSystemSocketFactory();
        }
    } else {
        trustStrategy = new TrustSelfSignedStrategy();
    }

    X509HostnameVerifier x509HostnameVerifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;

    if (!_verifyServerHostname) {
        x509HostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    }

    try {
        return new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, String.valueOf(_keyStorePassword),
                trustKeyStore, null, trustStrategy, x509HostnameVerifier);
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(
                    "Use system defaults because the custom SSL socket " + "factory was not able to initialize",
                    e);
        }

        return SSLSocketFactory.getSystemSocketFactory();
    }
}

From source file:org.greencheek.spring.rest.SSLCachingHttpComponentsClientHttpRequestFactory.java

/**
 * Create a new instance of the HttpComponentsClientHttpRequestFactory with a default
 * {@link HttpClient} that uses a default {@link org.apache.http.impl.conn.PoolingClientConnectionManager}.
 *//*w w  w  .  j a v a  2 s  .co  m*/
public SSLCachingHttpComponentsClientHttpRequestFactory(boolean useSSLCaching) {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSystemSocketFactory()));

    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);

    this.httpClient = new DefaultHttpClient(connectionManager);
    ((DefaultHttpClient) this.httpClient).removeRequestInterceptorByClass(RequestDefaultHeaders.class);

    setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
    setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLISECONDS);
    this.useSSLCaching = useSSLCaching;
    setTcpNoDelay(DEFAULT_TCP_NO_DELAY);
}

From source file:org.apache.commons.httpclient.contrib.ssl.StrictSSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>//w w w .j  a  v  a2s .  com
 * This method employs several techniques to circumvent the limitations of older JREs that 
 * do not support connect timeout. When running in JRE 1.4 or above reflection is used to 
 * call Socket#connect(SocketAddress endpoint, int timeout) method. When executing in older 
 * JREs a controller thread is executed. The controller thread attempts to create a new socket
 * within the given limit of time. If socket constructor does not return until the timeout 
 * expires, the controller terminates and throws an {@link ConnectTimeoutException}
 * </p>
 *  
 * @param host the host name/IP
 * @param port the port on the host
 * @param clientHost the local host name/IP to bind the socket to
 * @param clientPort the port on the local machine
 * @param params {@link HttpConnectionParams Http connection parameters}
 * 
 * @return Socket a new socket
 * 
 * @throws IOException if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be
 * determined
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = HttpConnectionParams.getConnectionTimeout(params);
    SSLSocket socket = null;

    SSLSocketFactory socketfactory = SSLSocketFactory.getSystemSocketFactory();
    if (timeout == 0) {
        socket = (SSLSocket) socketfactory.createSocket(params);
    } else {
        socket = (SSLSocket) socketfactory.createSocket(params);
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
    }
    verifyHostname(socket);
    return socket;
}

From source file:org.apache.commons.httpclient.contrib.ssl.StrictSSLProtocolSocketFactory.java

/**
 * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
 *//*  w w  w  . j  a  va 2  s. c  om*/
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    SSLSocketFactory sf = SSLSocketFactory.getSystemSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sf.createSocket(new Socket(), host, port, true);
    verifyHostname(sslSocket);

    return sslSocket;
}

From source file:org.apache.commons.httpclient.contrib.ssl.StrictSSLProtocolSocketFactory.java

/**
 * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
 *//*from   w  ww  .  j a  v  a  2  s  .c  om*/
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
        throws IOException, UnknownHostException {
    SSLSocketFactory sf = SSLSocketFactory.getSystemSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, port, autoClose);
    verifyHostname(sslSocket);

    return sslSocket;
}

From source file:ddf.test.itests.platform.TestSingleSignOn.java

@Test
public void testPkiAuth() throws Exception {

    // Note that PKI is passive (as opposed to username/password which is not)
    ResponseHelper searchHelper = getSearchResponse(true);

    // @formatter:off
    given().auth()/*from  w  w  w  . j a v a2  s . c o m*/
            .certificate(KEY_STORE_PATH, PASSWORD,
                    certAuthSettings().sslSocketFactory(SSLSocketFactory.getSystemSocketFactory()))
            .param("AuthMethod", "pki").params(searchHelper.params).expect().statusCode(200).when()
            .get(searchHelper.redirectUrl);
    // @formatter:on
}

From source file:com.kenai.redminenb.repository.RedmineRepository.java

static PoolingClientConnectionManager createConnectionManager() throws SSLInitializationException {
    SSLSocketFactory socketFactory = SSLSocketFactory.getSystemSocketFactory();
    socketFactory.setHostnameVerifier(new X509HostnameVerifier() {
        @Override/*from   w w w .java  2  s .c  o  m*/
        public void verify(String string, SSLSocket ssls) throws IOException {
            if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(string, ssls.getSession())) {
                throw new SSLException("Hostname did not verify");
            }
        }

        @Override
        public void verify(String string, X509Certificate xc) throws SSLException {
            throw new SSLException("Check not implemented yet");
        }

        @Override
        public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            throw new SSLException("Check not implemented yet");
        }

        @Override
        public boolean verify(String string, SSLSession ssls) {
            return HttpsURLConnection.getDefaultHostnameVerifier().verify(string, ssls);
        }
    });
    PoolingClientConnectionManager connectionManager = RedmineManagerFactory
            .createConnectionManager(Integer.MAX_VALUE, socketFactory);
    return connectionManager;
}

From source file:ddf.test.itests.platform.TestSecurity.java

@Test
public void testUsernameTokenSTS() throws Exception {
    String onBehalfOf = "<wst:OnBehalfOf>"
            + "                    <wsse:UsernameToken xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\n"
            + "                        <wsse:Username>admin</wsse:Username>\n"
            + "                        <wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">admin</wsse:Password>\n"
            + "                   </wsse:UsernameToken>\n" + "                </wst:OnBehalfOf>\n";
    String body = getSoapEnvelope(onBehalfOf);

    given().auth()/*ww  w  . j  av a2 s .  c  om*/
            .certificate(KEY_STORE_PATH, PASSWORD,
                    certAuthSettings().sslSocketFactory(SSLSocketFactory.getSystemSocketFactory()))
            .log().all().body(body).header("Content-Type", "text/xml; charset=utf-8")
            .header("SOAPAction", "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue").expect()
            .statusCode(equalTo(200)).when().post(SERVICE_ROOT.getUrl() + "/SecurityTokenService").then().log()
            .all().assertThat().body(HasXPath.hasXPath("//*[local-name()='Assertion']"));
}

From source file:ddf.test.itests.platform.TestSecurity.java

@Test
public void testBadUsernameTokenSTS() throws Exception {
    String onBehalfOf = "<wst:OnBehalfOf>"
            + "                    <wsse:UsernameToken xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\n"
            + "                        <wsse:Username>admin</wsse:Username>\n"
            + "                        <wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">blah</wsse:Password>\n"
            + "                   </wsse:UsernameToken>\n" + "                </wst:OnBehalfOf>\n";
    String body = getSoapEnvelope(onBehalfOf);

    given().auth()//www  . j  a v a 2s .  c  o m
            .certificate(KEY_STORE_PATH, PASSWORD,
                    certAuthSettings().sslSocketFactory(SSLSocketFactory.getSystemSocketFactory()))
            .log().all().body(body).header("Content-Type", "text/xml; charset=utf-8")
            .header("SOAPAction", "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue").expect()
            .statusCode(equalTo(500)).when().post(SERVICE_ROOT.getUrl() + "/SecurityTokenService").then().log()
            .all();
}