HttpsSchemeFactory

From Null-pointer

Jump to: navigation, search
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
 
@Component
public class HttpsSchemeFactory {
    private static final String CLIENT_STORE_LOCATION = "classpath:etc/ssl/client-keystore-gamesys-local.jks";
    private static final String CLIENT_STORE_PASSWORD = "password";
    private static final String TRUST_STORE_LOCATION = "classpath:etc/ssl/trust-store-gamesys-local.jks";
    private static final String TRUST_STORE_PASSWORD = "password";
    private static final String HTTPS = "https";
    private static final String JKS = "jks";
 
    public Scheme create(Integer securePort) {
        Scheme scheme = null;
        try {
            KeyStore clientKeystore = createKeyStore(ResourceUtils.getURL(CLIENT_STORE_LOCATION),
                    CLIENT_STORE_PASSWORD);
            KeyStore trustKeystore = createKeyStore(ResourceUtils.getURL(TRUST_STORE_LOCATION),
                    System.getProperty(TRUST_STORE_PASSWORD));
            SSLSocketFactory socketFactory = new SSLSocketFactory(clientKeystore, CLIENT_STORE_PASSWORD, trustKeystore);
            scheme = new Scheme(HTTPS, socketFactory, securePort);
        } catch (Exception ignore) {
        }
        return scheme;
    }
 
    private KeyStore createKeyStore(final URL url, final String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
        if (url == null) {
            throw new IllegalArgumentException("Keystore url may not be null");
        }
        KeyStore keystore = KeyStore.getInstance(JKS);
        InputStream inputStream = null;
        try {
            inputStream = url.openStream();
            keystore.load(inputStream, password != null ? password.toCharArray() : null);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return keystore;
    }
 
}
Personal tools