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

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

Introduction

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

Prototype

public static SSLSocketFactory getSocketFactory() throws SSLInitializationException 

Source Link

Document

Obtains default SSL socket factory with an SSL context based on the standard JSSE trust material (cacerts file in the security properties directory).

Usage

From source file:org.wso2.carbon.analytics.api.internal.client.AnalyticsAPIHttpClient.java

private AnalyticsAPIHttpClient(String protocol, String hostname, int port, int maxPerRoute, int maxConnection,
        int socketTimeout, int connectionTimeout, String trustStoreLocation, String trustStorePassword) {
    this.hostname = hostname;
    this.port = port;
    this.protocol = protocol;
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    if (this.protocol.equalsIgnoreCase(AnalyticsDataConstants.HTTP_PROTOCOL)) {
        schemeRegistry.register(new Scheme(this.protocol, port, PlainSocketFactory.getSocketFactory()));
    } else {/* www. ja v a2s. c  o m*/
        System.setProperty(AnalyticsDataConstants.SSL_TRUST_STORE_SYS_PROP, trustStoreLocation);
        System.setProperty(AnalyticsDataConstants.SSL_TRUST_STORE_PASSWORD_SYS_PROP, trustStorePassword);
        schemeRegistry.register(new Scheme(this.protocol, port, SSLSocketFactory.getSocketFactory()));
    }
    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setDefaultMaxPerRoute(maxPerRoute);
    connectionManager.setMaxTotal(maxConnection);
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter(AllClientPNames.SO_TIMEOUT, socketTimeout);
    params.setParameter(AllClientPNames.CONNECTION_TIMEOUT, connectionTimeout);
    this.httpClient = new DefaultHttpClient(connectionManager, params);
    gson = new GsonBuilder().create();
}

From source file:jp.ambrosoli.quickrestclient.apache.service.ApacheHttpService.java

/**
 * ?????????//from   w w  w .  ja va2 s  .c  o m
 * 
 * @param uri
 *            URI
 * @return 
 */
protected SocketFactory getSocketFactory(final URI uri) {
    if (uri == null) {
        throw new NullPointerException("URL is null.");
    }

    SocketFactory factory;
    if (URIUtil.isPlain(uri)) {
        factory = PlainSocketFactory.getSocketFactory();
    } else if (URIUtil.isSSL(uri)) {
        factory = SSLSocketFactory.getSocketFactory();
    } else {
        throw new IllegalArgumentException("invalid scheme.");
    }

    return factory;
}

From source file:org.quickconnectfamily.sync.SynchronizedDB.java

/**
 * Creates a SynchronizedDB object used to interact with a local database and a remote HTTP service.  It 
 * sends a login request to the // w ww.  j a v a2s. c  o  m
 * @param theActivityRef - the activity that the database is associated with.  This is usually your initial Acivity class.
 * @param aDbName - the name of the SQLite file to be kept in sync.
 * @param aRemoteURL - the URL of the service that will respond to synchronization requests including the port number if not port 80.  
 * For security reasons it is suggested that your URL be an HTTPS URL but this is not required.
 * @param port - the port number of the remote HTTP service.
 * @param aRemoteUname - a security credential used in the remote service
 * @param aRemotePword - a security credential used in the remote service
 * @param syncTimeout - the amount of time in seconds to attempt all sync requests before timing out.
 * @throws DataAccessException
 * @throws URISyntaxException
 * @throws InterruptedException
 */
public SynchronizedDB(WeakReference<Context> theActivityRef, String aDbName, URL aRemoteURL, int port,
        String aRemoteUname, String aRemotePword, long syncTimeout)
        throws DataAccessException, URISyntaxException, InterruptedException {
    dbName = aDbName;
    remoteURL = aRemoteURL.toURI();
    remoteUname = aRemoteUname;
    remotePword = aRemotePword;
    this.theActivityRef = theActivityRef;

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    if (aRemoteURL.toExternalForm().indexOf("http") == 0) {
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), port));
    } else if (aRemoteURL.toExternalForm().indexOf("https") == 0) {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), port));
    }
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    httpClient = new DefaultHttpClient(cm, params);

    startTransaction();
    String errorMessage = null;
    //insert the required tables if they don't exist
    try {
        DataAccessResult aResult = DataAccessObject.transact(theActivityRef, aDbName,
                "CREATE TABLE IF NOT EXISTS sync_info(int id PRIMARY KEY  NOT NULL, last_sync TIMESTAMP);",
                null);
        if (aResult.getErrorDescription().equals("not an error")) {
            aResult = DataAccessObject.transact(theActivityRef, aDbName,
                    "CREATE TABLE IF NOT EXISTS sync_values(timeStamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, sql_key TEXT, sql_params TEXT)",
                    null);
            if (!aResult.getErrorDescription().equals("not an error")) {
                allTransactionStatementsExecuted = false;
                errorMessage = aResult.getErrorDescription();
            }
        } else {
            allTransactionStatementsExecuted = false;
            errorMessage = aResult.getErrorDescription();
        }
    } catch (DataAccessException e) {
        e.printStackTrace();
        errorMessage = e.getLocalizedMessage();
        allTransactionStatementsExecuted = false;
        errorMessage = e.getLocalizedMessage();
    }
    endTransaction();
    if (allTransactionStatementsExecuted == false) {
        throw new DataAccessException("Error: Transaction failure. " + errorMessage);
    }

    /*
     * Do login and store context
     */
    // Create a local instance of cookie store
    CookieStore cookieStore = new BasicCookieStore();

    // Create local HTTP context
    localContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

}

From source file:org.gege.caldavsyncadapter.caldav.CaldavFacade.java

protected HttpClient getHttpClient() {

    HttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    registry.register(new Scheme("https",
            (trustAll ? EasySSLSocketFactory.getSocketFactory() : SSLSocketFactory.getSocketFactory()), 443));
    DefaultHttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);

    return client;
}

From source file:org.nuxeo.wizard.download.PackageDownloader.java

protected PackageDownloader() {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    registry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(registry);
    cm.setMaxTotal(NB_DOWNLOAD_THREADS);
    cm.setDefaultMaxPerRoute(NB_DOWNLOAD_THREADS);
    httpClient = new DefaultHttpClient(cm, httpParams);
}

From source file:org.vietspider.net.client.impl.AnonymousHttpClient.java

@Override
protected ClientConnectionManager createClientConnectionManager() {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager connManager = null;
    HttpParams params = getParams();// ww w  .java  2s  .  co  m

    ClientConnectionManagerFactory factory = null;

    // Try first getting the factory directly as an object.
    factory = (ClientConnectionManagerFactory) params.getParameter(ClientPNames.CONNECTION_MANAGER_FACTORY);
    if (factory == null) { // then try getting its class name.
        String className = (String) params.getParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME);
        if (className != null) {
            try {
                Class<?> clazz = Class.forName(className);
                factory = (ClientConnectionManagerFactory) clazz.newInstance();
            } catch (ClassNotFoundException ex) {
                throw new IllegalStateException("Invalid class name: " + className);
            } catch (IllegalAccessException ex) {
                throw new IllegalAccessError(ex.getMessage());
            } catch (InstantiationException ex) {
                throw new InstantiationError(ex.getMessage());
            }
        }
    }

    if (factory != null) {
        connManager = factory.newInstance(params, registry);
    } else {
        connManager = new SingleClientConnManager(getParams(), registry);
    }

    return connManager;
}

From source file:com.duokan.reader.domain.account.oauth.evernote.TEvernoteHttpClient.java

private DefaultHttpClient getHTTPClient() {

    try {//from  w w w. j  a  va2s  .c o  m
        if (mConnectionManager != null) {
            mConnectionManager.closeExpiredConnections();
            mConnectionManager.closeIdleConnections(1, TimeUnit.SECONDS);
        } else {
            BasicHttpParams params = new BasicHttpParams();

            HttpConnectionParams.setConnectionTimeout(params, 10000);
            HttpConnectionParams.setSoTimeout(params, 20000);

            ConnManagerParams.setMaxTotalConnections(params, ConnManagerParams.DEFAULT_MAX_TOTAL_CONNECTIONS);
            ConnManagerParams.setTimeout(params, 10000);

            ConnPerRouteBean connPerRoute = new ConnPerRouteBean(18); // Giving 18 connections to Evernote
            ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

            schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

            mConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
            DefaultHttpClient httpClient = new DefaultHttpClient(mConnectionManager, params);
            httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
                @Override
                public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                    return 2 * 60 * 1000; // 2 minutes in millis
                }
            });

            httpClient.setReuseStrategy(new ConnectionReuseStrategy() {
                @Override
                public boolean keepAlive(HttpResponse response, HttpContext context) {
                    return true;
                }
            });
            mHttpClient = httpClient;
        }
    } catch (Exception ex) {
        return null;
    }

    return mHttpClient;
}

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

/**
 * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
 *//*from  ww  w.  j  a  v a2  s . co  m*/
public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
        throws IOException, UnknownHostException {
    SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sf.createSocket(new Socket(host, port), clientHost.toString(), clientPort,
            true);
    verifyHostname(sslSocket);

    return sslSocket;
}

From source file:ch.iterate.openstack.swift.Client.java

/**
 * @param connectionTimeOut The connection timeout, in ms.
 *///from  w  w  w  .j  a v  a2s  . com
public Client(final int connectionTimeOut) {
    this(new DefaultHttpClient() {
        @Override
        protected HttpParams createHttpParams() {
            BasicHttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSoTimeout(params, connectionTimeOut);
            return params;
        }

        @Override
        protected ClientConnectionManager createClientConnectionManager() {
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
            schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
            return new PoolingClientConnectionManager(schemeRegistry);
        }
    });
}

From source file:com.evernote.client.conn.mobile.TEvernoteHttpClient.java

@Deprecated
private DefaultHttpClient getHTTPClient() {

    try {/*from w  w  w  . j  a  va 2  s .c  o m*/
        if (mConnectionManager != null) {
            mConnectionManager.closeExpiredConnections();
            mConnectionManager.closeIdleConnections(1, TimeUnit.SECONDS);
        } else {
            BasicHttpParams params = new BasicHttpParams();

            HttpConnectionParams.setConnectionTimeout(params, 10000);
            HttpConnectionParams.setSoTimeout(params, 20000);

            ConnManagerParams.setMaxTotalConnections(params, ConnManagerParams.DEFAULT_MAX_TOTAL_CONNECTIONS);
            ConnManagerParams.setTimeout(params, 10000);

            ConnPerRouteBean connPerRoute = new ConnPerRouteBean(18); // Giving 18 connections to Evernote
            ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

            schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

            mConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
            DefaultHttpClient httpClient = new DefaultHttpClient(mConnectionManager, params);
            httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
                @Override
                public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                    return 2 * 60 * 1000; // 2 minutes in millis
                }
            });

            httpClient.setReuseStrategy(new ConnectionReuseStrategy() {
                @Override
                public boolean keepAlive(HttpResponse response, HttpContext context) {
                    return true;
                }
            });
            mHttpClient = httpClient;
        }
    } catch (Exception ex) {
        return null;
    }

    return mHttpClient;
}