com.seajas.search.codex.social.connection.TrustingClientHttpRequestFactory.java Source code

Java tutorial

Introduction

Here is the source code for com.seajas.search.codex.social.connection.TrustingClientHttpRequestFactory.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.codex.social.connection;

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.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

import static java.lang.String.format;

/**
 * Trusting HttpClient request factory.
 *
 * @author Jasper van Veghel <jasper@seajas.com>
 */
public class TrustingClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {
    private static final Logger logger = LoggerFactory.getLogger(TrustingClientHttpRequestFactory.class);

    public TrustingClientHttpRequestFactory()
            throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        super();

        this.getHttpClient().getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {
                    @Override
                    public boolean isTrusted(final X509Certificate[] chain, final String authType)
                            throws CertificateException {
                        if (logger.isTraceEnabled())
                            logger.trace(format("Trusting certificate chain with %d certificates and auth type %s",
                                    chain != null ? chain.length : 0, authType));

                        return true;
                    }
                }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
    }
}