com.seajas.search.contender.http.ExclusiveConnectionManager.java Source code

Java tutorial

Introduction

Here is the source code for com.seajas.search.contender.http.ExclusiveConnectionManager.java

Source

/**
 * Copyright (C) 2013 Seajas, the Netherlands.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.seajas.search.contender.http;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import org.apache.http.HttpHost;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.impl.conn.SchemeRegistryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

/**
 * Exclusive connection manager.
 *
 * @author Jasper van Veghel <jasper@seajas.com>
 */
public class ExclusiveConnectionManager extends PoolingClientConnectionManager {
    /**
     * The logger.
     */
    private static final Logger logger = LoggerFactory.getLogger(ExclusiveConnectionManager.class);

    /**
     * Default constructor.
     */
    public ExclusiveConnectionManager() {
    }

    /**
     * Default constructor.
     *
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws UnrecoverableKeyException
     * @throws KeyManagementException
     */
    public ExclusiveConnectionManager(final Boolean trustAllCertificates)
            throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
        super(createSchemeRegistry(trustAllCertificates));
    }

    /**
     * Set the exclusions.
     *
     * @param exclusions
     */
    public void setRouteExclusions(final String exclusions) {
        for (String exclusion : StringUtils.tokenizeToStringArray(exclusions, ",", true, true)) {
            setMaxPerRoute(new HttpRoute(new HttpHost(exclusion), null, false), getMaxTotal());
            setMaxPerRoute(new HttpRoute(new HttpHost(exclusion), null, true), getMaxTotal());
        }
    }

    /**
     * Create a scheme registry which either trusts all certificates, or uses the HttpClient default.
     *
     * @param trustAllCertificates
     * @return SchemeRegistry
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws KeyStoreException
     * @throws UnrecoverableKeyException
     */
    private static SchemeRegistry createSchemeRegistry(final Boolean trustAllCertificates)
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        if (trustAllCertificates) {
            SchemeRegistry registry = new SchemeRegistry();

            if (logger.isInfoEnabled())
                logger.info("Trusting all certificates");

            X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
                @Override
                public void verify(String host, SSLSocket ssl) throws IOException {
                    // Do nothing
                }

                @Override
                public void verify(String host, X509Certificate cert) throws SSLException {
                    //Do nothing
                }

                @Override
                public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                    //Do nothing
                }

                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            };

            registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
            registry.register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {
                @Override
                public boolean isTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    return true;
                }
            }, hostnameVerifier)/* {
                                @Override
                                public Socket connectSocket(final Socket socket,
                                final InetSocketAddress remoteAddress,
                                final InetSocketAddress localAddress,
                                final HttpParams param) throws IOException, UnknownHostException, ConnectTimeoutException {
                                if (socket instanceof SSLSocket) {
                                try {
                                if (logger.isDebugEnabled()) {
                                String currentHost = null;
                                    
                                logger.debug("This JVM seems to potentially not support SNI - trying to fix");
                                    
                                try {
                                currentHost = (String) FieldUtils.getFieldValue(socket, "host");
                                } catch (IllegalAccessException e) {
                                logger.debug("Unable to access field 'host' from the underlaying SSLSocket");
                                }
                                    
                                logger.debug("Overriding default socket hostname of " + (currentHost != null ? currentHost : "(null)") + " with " + remoteAddress.getHostName());
                                }
                                    
                                PropertyUtils.setProperty(socket, "host", remoteAddress.getHostName());
                                } catch (NoSuchMethodException e) {
                                if (logger.isDebugEnabled())
                                logger.debug(e);
                                } catch (IllegalAccessException e) {
                                if (logger.isDebugEnabled())
                                logger.debug(e);
                                } catch (InvocationTargetException e) {
                                if (logger.isDebugEnabled())
                                logger.debug(e);
                                }
                                } else {
                                if (logger.isDebugEnabled())
                                logger.debug("This is not the JVM we're looking for - should support SNI");
                                }
                                    
                                return super.connectSocket(socket, remoteAddress, localAddress, param);
                                }
                                } */));

            return registry;
        } else
            return SchemeRegistryFactory.createDefault();
    }
}