Example usage for javax.net.ssl KeyManagerFactory getKeyManagers

List of usage examples for javax.net.ssl KeyManagerFactory getKeyManagers

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory getKeyManagers.

Prototype

public final KeyManager[] getKeyManagers() 

Source Link

Document

Returns one key manager for each type of key material.

Usage

From source file:lucee.runtime.tag.Http.java

private void ssl(HttpClientBuilder builder) throws PageException {
    try {/* ww w .  j ava 2  s . co  m*/
        // SSLContext sslcontext = SSLContexts.createSystemDefault();
        SSLContext sslcontext = SSLContext.getInstance("TLSv1.2");
        if (!StringUtil.isEmpty(this.clientCert)) {
            if (this.clientCertPassword == null)
                this.clientCertPassword = "";
            File ksFile = new File(this.clientCert);
            KeyStore clientStore = KeyStore.getInstance("PKCS12");
            clientStore.load(new FileInputStream(ksFile), this.clientCertPassword.toCharArray());

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(clientStore, this.clientCertPassword.toCharArray());

            sslcontext.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());
        } else {
            sslcontext.init(null, null, new java.security.SecureRandom());
        }
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactoryImpl(sslcontext,
                new DefaultHostnameVerifierImpl());
        builder.setSSLSocketFactory(sslsf);
        Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf)
                .build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
                new DefaultHttpClientConnectionOperatorImpl(reg), null, -1, TimeUnit.MILLISECONDS); // TODO review -1 setting
        builder.setConnectionManager(cm);
    } catch (Exception e) {
        throw Caster.toPageException(e);
    }
}

From source file:org.lockss.protocol.BlockingStreamComm.java

/** One-time startup configuration  */
private void configure(Configuration config, Configuration prevConfig, Configuration.Differences changedKeys) {
    enabled = config.getBoolean(PARAM_ENABLED, DEFAULT_ENABLED);
    if (!enabled) {
        return;//www. j a  v  a  2s.  c  o  m
    }
    paramMinPoolSize = config.getInt(PARAM_CHANNEL_THREAD_POOL_MIN, DEFAULT_CHANNEL_THREAD_POOL_MIN);
    paramMaxPoolSize = config.getInt(PARAM_CHANNEL_THREAD_POOL_MAX, DEFAULT_CHANNEL_THREAD_POOL_MAX);
    paramPoolKeepaliveTime = config.getTimeInterval(PARAM_CHANNEL_THREAD_POOL_KEEPALIVE,
            DEFAULT_CHANNEL_THREAD_POOL_KEEPALIVE);

    if (config.getBoolean(PARAM_BIND_TO_LOCAL_IP_ONLY, DEFAULT_BIND_TO_LOCAL_IP_ONLY)) {
        bindAddr = config.get(IdentityManager.PARAM_LOCAL_IP);
    }
    sendFromBindAddr = config.getBoolean(PARAM_SEND_FROM_BIND_ADDR, DEFAULT_SEND_FROM_BIND_ADDR);

    if (changedKeys.contains(PARAM_USE_V3_OVER_SSL)) {
        paramUseV3OverSsl = config.getBoolean(PARAM_USE_V3_OVER_SSL, DEFAULT_USE_V3_OVER_SSL);
        sockFact = null;
        // XXX shut down old listen socket, do exponential backoff
        // XXX on bind() to bring up new listen socket
        // XXX then move this to the "change on the fly" above
    }
    if (!paramUseV3OverSsl)
        return;
    log.info("Using SSL");
    // We're trying to use SSL
    if (changedKeys.contains(PARAM_USE_SSL_CLIENT_AUTH)) {
        paramSslClientAuth = config.getBoolean(PARAM_USE_SSL_CLIENT_AUTH, DEFAULT_USE_SSL_CLIENT_AUTH);
        sockFact = null;
    }
    if (sslServerSocketFactory != null && sslSocketFactory != null) {
        // already initialized
        return;
    }

    if (changedKeys.contains(PARAM_SSL_KEYSTORE_NAME) || changedKeys.contains(PARAM_SSL_PRIVATE_KEYSTORE_NAME)
            || changedKeys.contains(PARAM_SSL_PUBLIC_KEYSTORE_NAME)) {
        String name = getOrNull(config, PARAM_SSL_KEYSTORE_NAME);
        String priv = getOrNull(config, PARAM_SSL_PRIVATE_KEYSTORE_NAME);
        String pub = getOrNull(config, PARAM_SSL_PUBLIC_KEYSTORE_NAME);
        if (!StringUtil.isNullString(name)) {
            paramSslPrivateKeyStoreName = name;
            paramSslPublicKeyStoreName = name;
        }
        if (priv != null) {
            if (name != null && !priv.equals(name)) {
                log.warning("Overriding " + PARAM_SSL_KEYSTORE_NAME + ": " + name + " with "
                        + PARAM_SSL_PRIVATE_KEYSTORE_NAME + ": " + priv);
            }
            paramSslPrivateKeyStoreName = priv;
        }
        if (pub != null) {
            if (name != null && !pub.equals(name)) {
                log.warning("Overriding " + PARAM_SSL_KEYSTORE_NAME + ": " + name + " with "
                        + PARAM_SSL_PUBLIC_KEYSTORE_NAME + ": " + pub);
            }
            paramSslPublicKeyStoreName = pub;
        }
        if (StringUtil.equalStrings(paramSslPublicKeyStoreName, paramSslPrivateKeyStoreName)) {
            // so can use == later
            paramSslPrivateKeyStoreName = paramSslPublicKeyStoreName;
            log.debug("Using keystore " + paramSslPrivateKeyStoreName);
        } else {
            log.debug("Using private keystore " + paramSslPrivateKeyStoreName + ", public keystore "
                    + paramSslPublicKeyStoreName);
        }
        sockFact = null;
    }
    if (changedKeys.contains(PARAM_SSL_PROTOCOL)) {
        paramSslProtocol = config.get(PARAM_SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL);
        sockFact = null;
    }
    KeyManagerFactory kmf = keystoreMgr.getKeyManagerFactory(paramSslPrivateKeyStoreName, "LCAP");
    if (kmf == null) {
        throw new IllegalArgumentException("Keystore not found: " + paramSslPrivateKeyStoreName);
    }
    KeyManager[] kma = kmf.getKeyManagers();

    TrustManagerFactory tmf = keystoreMgr.getTrustManagerFactory(paramSslPublicKeyStoreName, "LCAP");
    if (tmf == null) {
        throw new IllegalArgumentException("Keystore not found: " + paramSslPublicKeyStoreName);
    }
    TrustManager[] tma = tmf.getTrustManagers();

    // Now create an SSLContext from the KeyManager
    SSLContext sslContext = null;
    try {
        RandomManager rmgr = getDaemon().getRandomManager();
        SecureRandom rng = rmgr.getSecureRandom();

        sslContext = SSLContext.getInstance(paramSslProtocol);
        sslContext.init(kma, tma, rng);
        // Now create the SSL socket factories from the context
        sslServerSocketFactory = sslContext.getServerSocketFactory();
        sslSocketFactory = sslContext.getSocketFactory();
        log.info("SSL init successful");
    } catch (NoSuchAlgorithmException ex) {
        log.error("Creating SSL context threw " + ex);
        sslContext = null;
    } catch (NoSuchProviderException ex) {
        log.error("Creating SSL context threw " + ex);
        sslContext = null;
    } catch (KeyManagementException ex) {
        log.error("Creating SSL context threw " + ex);
        sslContext = null;
    }
}

From source file:com.wwpass.connection.WWPassConnection.java

public WWPassConnection(X509Certificate cert, PKCS8EncodedKeySpec key, int timeoutSec, String spfeAddr)
        throws IOException, GeneralSecurityException {
    timeoutMs = timeoutSec * 1000;//from ww  w.  j av a  2 s .c  o  m
    SpfeURL = "https://" + spfeAddr + "/";
    // Setting up client certificate and key

    X509Certificate[] chain = { cert };

    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privKey = kf.generatePrivate(key);

    KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(privKey, chain);

    //This adds no security but Java requires to password-protect the key
    byte[] password_bytes = new byte[16];
    (new java.security.SecureRandom()).nextBytes(password_bytes);
    // String password = (new BASE64Encoder()).encode(password_bytes);
    String password = (new Base64()).encodeToString(password_bytes);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null);

    keyStore.setEntry("WWPass client key", pke, new KeyStore.PasswordProtection(password.toCharArray()));
    keyManagerFactory.init(keyStore, password.toCharArray());

    SPFEContext = SSLContext.getInstance("TLS");

    // Making rootCA certificate
    InputStream is = null;
    CertificateFactory cf;
    X509Certificate rootCA = null;
    try {
        is = new ByteArrayInputStream(WWPassCA_DER);
        cf = CertificateFactory.getInstance("X.509");
        rootCA = (X509Certificate) cf.generateCertificate(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }

    //Creating TrustManager for this CA
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);
    ks.setCertificateEntry("WWPass Root CA", rootCA);

    trustManagerFactory.init(ks);

    SPFEContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new java.security.SecureRandom());
}

From source file:org.apache.ambari.view.hive.client.Connection.java

SSLSocketFactory getTwoWaySSLSocketFactory() throws SQLException {
    SSLSocketFactory socketFactory = null;

    try {// ww w.  j  av a  2 s  . co m
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                Utils.HiveAuthenticationParams.SUNX509_ALGORITHM_STRING,
                Utils.HiveAuthenticationParams.SUNJSSE_ALGORITHM_STRING);
        String keyStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_KEY_STORE);
        String keyStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_KEY_STORE_PASSWORD);
        KeyStore sslKeyStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_KEY_STORE_TYPE);

        if (keyStorePath == null || keyStorePath.isEmpty()) {
            throw new IllegalArgumentException(Utils.HiveAuthenticationParams.SSL_KEY_STORE
                    + " Not configured for 2 way SSL connection, keyStorePath param is empty");
        }
        try (FileInputStream fis = new FileInputStream(keyStorePath)) {
            sslKeyStore.load(fis, keyStorePassword.toCharArray());
        }
        keyManagerFactory.init(sslKeyStore, keyStorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(Utils.HiveAuthenticationParams.SUNX509_ALGORITHM_STRING);
        String trustStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE);
        String trustStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_TYPE);

        if (trustStorePath == null || trustStorePath.isEmpty()) {
            throw new IllegalArgumentException(Utils.HiveAuthenticationParams.SSL_TRUST_STORE
                    + " Not configured for 2 way SSL connection");
        }
        try (FileInputStream fis = new FileInputStream(trustStorePath)) {
            sslTrustStore.load(fis, trustStorePassword.toCharArray());
        }
        trustManagerFactory.init(sslTrustStore);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
        socketFactory = new SSLSocketFactory(context);
    } catch (Exception e) {
        throw new SQLException("Error while initializing 2 way ssl socket factory ", e);
    }
    return socketFactory;
}

From source file:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java

private SSLSocketFactory initSSLSocketFactory(@NotNull String managementCertificate)
        throws NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException,
        UnrecoverableKeyException, KeyManagementException {
    byte[] decodeBuffer = new BASE64Decoder().decodeBuffer(managementCertificate);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");

    InputStream is = new ByteArrayInputStream(decodeBuffer);

    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(is, OpenSSLHelper.PASSWORD.toCharArray());
    keyManagerFactory.init(ks, OpenSSLHelper.PASSWORD.toCharArray());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

    return sslContext.getSocketFactory();
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

/** Getting SSL socket factory using the Admin cert created for client certificate authentication **/
private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException {
    // Put the key and certs in the user keystore (if available)
    java.security.KeyStore ks = java.security.KeyStore.getInstance("jks");
    ks.load(new FileInputStream(TEST_ADMIN_FILE), PASSWORD.toCharArray());
    final KeyManagerFactory kmf;
    kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, PASSWORD.toCharArray());
    final KeyManager km[] = kmf.getKeyManagers();

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);/*w  w w.  j a  va 2 s.c o m*/
    final TrustManager tm[] = tmf.getTrustManagers();
    if (km == null && tm == null) {
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    }
    final SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(km, tm, null);
    return ctx.getSocketFactory();
}

From source file:com.twinsoft.convertigo.engine.MySSLSocketFactory.java

private SSLContext createEasySSLContext()
        throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, IOException {
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Creating SSL context");

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Using KeyManager algorithm " + algorithm);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);

    String keyStoreType = keyStore.endsWith(".pkcs11") ? "pkcs11" : "pkcs12";
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Key store type: " + keyStoreType);

    String alias = null;/*  w  w  w. jav  a 2 s  .c o  m*/
    KeyStore ks, ts;
    char[] passPhrase;

    if (keyStore.equals("") || (keyStore.endsWith(".udv"))) {
        ks = KeyStore.getInstance(keyStoreType);
        ks.load(null, keyStorePassword.toCharArray());
        kmf.init(ks, null);
    } else {
        File file = new File(keyStore);

        Properties properties = new Properties();
        properties.load(
                new FileInputStream(Engine.CERTIFICATES_PATH + CertificateManager.STORES_PROPERTIES_FILE_NAME));
        String p = properties.getProperty(file.getName(), "");
        int i = p.indexOf('/');
        if (i != -1) {
            alias = p.substring(i + 1);
        }

        if (keyStoreType.equals("pkcs11")) {
            String providerName = file.getName();
            providerName = "SunPKCS11-" + providerName.substring(0, providerName.lastIndexOf('.'));
            Engine.logCertificateManager.debug("(MySSLSocketFactory) Provider name: '" + providerName + "'");

            String pinCode;
            if (i == -1) {
                pinCode = Crypto2.decodeFromHexString(p);
            } else {
                pinCode = Crypto2.decodeFromHexString(p.substring(0, i));
            }

            Engine.logCertificateManager.debug("(MySSLSocketFactory) PIN code: " + pinCode);

            ks = KeyStore.getInstance("pkcs11", providerName);
            ks.load((InputStream) null, pinCode.toCharArray());
            kmf.init(ks, null);
        } else {
            ks = KeyStore.getInstance(keyStoreType);
            passPhrase = keyStorePassword.toCharArray();
            ks.load(new FileInputStream(keyStore), passPhrase);
            kmf.init(ks, passPhrase);
        }
    }
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Client alias: "
            + (alias == null ? "<to be chosen by the security implementor>" : alias));

    ts = KeyStore.getInstance("jks");
    passPhrase = trustStorePassword.toCharArray();
    if (trustStore.equals(""))
        ts.load(null, passPhrase);
    else
        ts.load(new FileInputStream(trustStore), passPhrase);

    algorithm = TrustManagerFactory.getDefaultAlgorithm();
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Using TrustManager algorithm " + algorithm);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init(ts);

    TrustManager[] tm = { TRUST_MANAGER };

    MyX509KeyManager xkm = new MyX509KeyManager((X509KeyManager) kmf.getKeyManagers()[0], ks, ts, alias);

    Engine.logCertificateManager
            .debug("(MySSLSocketFactory) trusting all certificates : " + trustAllServerCertificates);

    //SSLContext context = SSLContext.getInstance("SSLv3");
    SSLContext context = SSLContext.getInstance("TLS");
    if (trustAllServerCertificates)
        context.init(new KeyManager[] { xkm }, tm, null);
    else
        context.init(new KeyManager[] { xkm }, tmf.getTrustManagers(), null);

    Engine.logCertificateManager.debug("(MySSLSocketFactory) SSL context created: " + context.getProtocol());
    return context;
}

From source file:org.apache.servicemix.http.processors.CommonsHttpSSLSocketFactory.java

protected final void createUnmanagedFactory(SslParameters ssl) throws Exception {
    SSLContext context;/*from ww  w. j  ava 2 s  .c o  m*/
    if (ssl.getProvider() == null) {
        context = SSLContext.getInstance(ssl.getProtocol());
    } else {
        context = SSLContext.getInstance(ssl.getProtocol(), ssl.getProvider());
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(ssl.getKeyManagerFactoryAlgorithm());
    String keyStore = ssl.getKeyStore();
    if (keyStore == null) {
        keyStore = System.getProperty("javax.net.ssl.keyStore");
        if (keyStore == null) {
            throw new IllegalArgumentException(
                    "keyStore or system property javax.net.ssl.keyStore must be set");
        }
    }
    if (keyStore.startsWith("classpath:")) {
        try {
            String res = keyStore.substring(10);
            URL url = new ClassPathResource(res).getURL();
            keyStore = url.toString();
        } catch (IOException e) {
            throw new JBIException("Unable to find keyStore " + keyStore, e);
        }
    }
    String keyStorePassword = ssl.getKeyStorePassword();
    if (keyStorePassword == null) {
        keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
        if (keyStorePassword == null) {
            throw new IllegalArgumentException(
                    "keyStorePassword or system property javax.net.ssl.keyStorePassword must be set");
        }
    }
    String trustStore = ssl.getTrustStore();
    String trustStorePassword = null;
    if (trustStore == null) {
        trustStore = System.getProperty("javax.net.ssl.trustStore");
    }
    if (trustStore != null) {
        if (trustStore.startsWith("classpath:")) {
            try {
                String res = trustStore.substring(10);
                URL url = new ClassPathResource(res).getURL();
                trustStore = url.toString();
            } catch (IOException e) {
                throw new JBIException("Unable to find trustStore " + trustStore, e);
            }
        }
        trustStorePassword = ssl.getTrustStorePassword();
        if (trustStorePassword == null) {
            trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
            if (trustStorePassword == null) {
                throw new IllegalArgumentException(
                        "trustStorePassword or system property javax.net.ssl.trustStorePassword must be set");
            }
        }
    }
    KeyStore ks = KeyStore.getInstance(ssl.getKeyStoreType());
    ks.load(Resource.newResource(keyStore).getInputStream(), keyStorePassword.toCharArray());
    keyManagerFactory.init(ks,
            ssl.getKeyPassword() != null ? ssl.getKeyPassword().toCharArray() : keyStorePassword.toCharArray());
    if (trustStore != null) {
        KeyStore ts = KeyStore.getInstance(ssl.getTrustStoreType());
        ts.load(Resource.newResource(trustStore).getInputStream(), trustStorePassword.toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(ssl.getTrustManagerFactoryAlgorithm());
        trustManagerFactory.init(ts);
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new java.security.SecureRandom());
    } else {
        context.init(keyManagerFactory.getKeyManagers(), null, new java.security.SecureRandom());
    }
    factory = context.getSocketFactory();
}

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * Configures all the needed components, but does not actually start the server.
 * @param config   Contains all information needed to fully wire up the http, https, and httpclient components of this reverse proxy.
 * @throws Exception   Yeah, a lot can go wrong here, but at least it will be caught immediately :-)
 *///www . j  a v  a 2s.  co  m
public void config(HierarchicalConfiguration config) throws Exception {
    List<HierarchicalConfiguration> lconf;
    HttpAsyncRequester executor = null;
    BasicNIOConnPool connPool = null;
    ObjectPool<ByteBuffer> byteBufferPool = null;
    LinkedHashMap<String, TargetDescriptor> mappings = null;
    ConcurrentMap<String, HttpHost> hosts = null;

    handlerRegistry = new UriHttpAsyncRequestHandlerMapper();

    // Initialize the keystore (if one was specified)
    KeyStore keystore = null;
    char[] keypass = null;
    String keystoreUri = config.getString("keystore");
    if ((keystoreUri != null) && (keystoreUri.trim().length() > 0)) {
        Path keystorePath = Utils.MakePath(keystoreUri);
        if (!Files.exists(keystorePath))
            throw new ConfigurationException("Keystore does not exist.");
        if (Files.isDirectory(keystorePath))
            throw new ConfigurationException("Keystore is not a file");
        String storepass = config.getString("storepass");
        if ((storepass != null) && "null".equals(storepass))
            storepass = null;
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream keyStoreStream = Files.newInputStream(keystorePath)) {
            keystore.load(keyStoreStream, storepass == null ? null : storepass.trim().toCharArray());
        } catch (IOException ex) {
            Logger.error("Unable to load https server keystore from " + keystoreUri);
            return;
        }
        keypass = config.getString("keypass").trim().toCharArray();
    }

    // Wire up the listening reactor
    lconf = config.configurationsAt("server");
    if ((lconf == null) || (lconf.size() != 1))
        throw new ConfigurationException("One (and only one) server configuration element is allowed.");
    else {
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("server[@cpu]", 0.667)));
        builder.setSoTimeout(config.getInt("server[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("server[@soLinger]", -1));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        builder.setSelectInterval(100);

        IOReactorConfig rconfig = builder.build();
        Logger.info("Configuring server with options: " + rconfig.toString());
        listeningReactor = new DefaultListeningIOReactor(rconfig);

        lconf = config.configurationsAt("server.listen");
        InetSocketAddress addr;
        boolean hasNonWildcardSecure = false;
        LinkedHashMap<SocketAddress, SSLContext> addrSSLContext = new LinkedHashMap<SocketAddress, SSLContext>();
        if ((lconf == null) || (lconf.size() == 0)) {
            addr = new InetSocketAddress("127.0.0.1", 8080);
            ListenerEndpoint ep = listeningReactor.listen(addr);
            Logger.warn("Configured " + ep.getAddress());
        } else {
            TrustManager[] trustManagers = null;
            KeyManagerFactory kmf = null;
            // Create all the specified listeners.
            for (HierarchicalConfiguration hc : lconf) {
                String addrStr = hc.getString("[@address]");
                if ((addrStr == null) || (addrStr.length() == 0))
                    addrStr = "0.0.0.0";
                String alias = hc.getString("[@alias]");
                int port = hc.getInt("[@port]", alias != null ? 443 : 80);
                addr = new InetSocketAddress(addrStr, port);
                ListenerEndpoint ep = listeningReactor.listen(addr);
                String protocol = hc.containsKey("[@protocol]") ? hc.getString("[@protocol]") : null;
                Boolean secure = hc.containsKey("[@secure]") ? hc.getBoolean("[@secure]") : null;
                if ((alias != null) && (secure == null))
                    secure = true;
                if ((protocol != null) && (secure == null))
                    secure = true;
                if ((secure != null) && secure) {
                    if (protocol == null)
                        protocol = "TLS";
                    if (keystore == null)
                        throw new ConfigurationException(
                                "An https listening socket was requested, but no keystore was specified.");
                    if (kmf == null) {
                        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                        kmf.init(keystore, keypass);
                    }
                    // Are we going to trust all clients or just specific ones?
                    if (hc.getBoolean("[@trustAny]", true))
                        trustManagers = new TrustManager[] { new X509TrustAllManager() };
                    else {
                        TrustManagerFactory instance = TrustManagerFactory
                                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                        instance.init(keystore);
                        trustManagers = instance.getTrustManagers();
                    }
                    KeyManager[] keyManagers = kmf.getKeyManagers();
                    if (alias != null)
                        for (int i = 0; i < keyManagers.length; i++) {
                            if (keyManagers[i] instanceof X509ExtendedKeyManager)
                                keyManagers[i] = new PokerFaceKeyManager(alias,
                                        (X509ExtendedKeyManager) keyManagers[i]);
                        }
                    SSLContext sslCtx = SSLContext.getInstance(protocol);
                    sslCtx.init(keyManagers, trustManagers, new SecureRandom());
                    if (addr.getAddress().isAnyLocalAddress()) {
                        // This little optimization helps us respond faster for every connection as we don't have to extrapolate a local connection address to wild card.
                        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                                .hasMoreElements();) {
                            NetworkInterface intf = en.nextElement();
                            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                    .hasMoreElements();) {
                                addr = new InetSocketAddress(enumIpAddr.nextElement(), port);
                                addrSSLContext.put(addr, sslCtx);
                            }
                        }
                    } else {
                        addrSSLContext.put(addr, sslCtx);
                        hasNonWildcardSecure = true;
                    }
                }
                Logger.warn("Configured " + (alias == null ? "" : (protocol + " on")) + ep.getAddress());
            }
        }
        // We will need an HTTP protocol processor for the incoming connections
        String serverAgent = config.getString("server.serverAgent", "PokerFace/" + Utils.Version);
        HttpProcessor inhttpproc = new ImmutableHttpProcessor(
                new HttpResponseInterceptor[] { new ResponseDateInterceptor(), new ResponseServer(serverAgent),
                        new ResponseContent(), new ResponseConnControl() });
        HttpAsyncService serviceHandler = new HttpAsyncService(inhttpproc, new DefaultConnectionReuseStrategy(),
                null, handlerRegistry, null) {
            public void exception(final NHttpServerConnection conn, final Exception cause) {
                Logger.warn(cause.getMessage());
                super.exception(conn, cause);
            }
        };
        if (addrSSLContext.size() > 0) {
            final SSLContext defaultCtx = addrSSLContext.values().iterator().next();
            final Map<SocketAddress, SSLContext> sslMap;
            if ((!hasNonWildcardSecure) || (addrSSLContext.size() == 1))
                sslMap = null;
            else
                sslMap = addrSSLContext;
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler,
                    new SSLNHttpServerConnectionFactory(defaultCtx, null, ConnectionConfig.DEFAULT) {
                        protected SSLIOSession createSSLIOSession(IOSession iosession, SSLContext sslcontext,
                                SSLSetupHandler sslHandler) {
                            SSLIOSession retVal;
                            SSLContext sktCtx = sslcontext;
                            if (sslMap != null) {
                                SocketAddress la = iosession.getLocalAddress();
                                if (la != null) {
                                    sktCtx = sslMap.get(la);
                                    if (sktCtx == null)
                                        sktCtx = sslcontext;
                                }
                                retVal = new SSLIOSession(iosession, SSLMode.SERVER, sktCtx, sslHandler);
                            } else
                                retVal = super.createSSLIOSession(iosession, sktCtx, sslHandler);
                            if (sktCtx != null)
                                retVal.setAttribute("com.bytelightning.opensource.pokerface.secure", true);
                            return retVal;
                        }
                    });
        } else
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, ConnectionConfig.DEFAULT);
    }

    // Configure the httpclient reactor that will be used to do reverse proxing to the specified targets.
    lconf = config.configurationsAt("targets");
    if ((lconf != null) && (lconf.size() > 0)) {
        HierarchicalConfiguration conf = lconf.get(0);
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("targets[@cpu]", 0.667)));
        builder.setSoTimeout(conf.getInt("targets[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("targets[@soLinger]", -1));
        builder.setConnectTimeout(conf.getInt("targets[@connectTimeout]", 0));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        connectingReactor = new DefaultConnectingIOReactor(builder.build());

        final int bufferSize = conf.getInt("targets[@bufferSize]", 1024) * 1024;
        byteBufferPool = new SoftReferenceObjectPool<ByteBuffer>(new BasePooledObjectFactory<ByteBuffer>() {
            @Override
            public ByteBuffer create() throws Exception {
                return ByteBuffer.allocateDirect(bufferSize);
            }

            @Override
            public PooledObject<ByteBuffer> wrap(ByteBuffer buffer) {
                return new DefaultPooledObject<ByteBuffer>(buffer);
            }
        });

        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        if (keystore != null) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keystore, keypass);
            keyManagers = kmf.getKeyManagers();
        }
        // Will the httpclient's trust any remote target, or only specific ones.
        if (conf.getBoolean("targets[@trustAny]", false))
            trustManagers = new TrustManager[] { new X509TrustAllManager() };
        else if (keystore != null) {
            TrustManagerFactory instance = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            instance.init(keystore);
            trustManagers = instance.getTrustManagers();
        }
        SSLContext clientSSLContext = SSLContext.getInstance(conf.getString("targets[@protocol]", "TLS"));
        clientSSLContext.init(keyManagers, trustManagers, new SecureRandom());

        // Setup an SSL capable connection pool for the httpclients.
        connPool = new BasicNIOConnPool(connectingReactor,
                new BasicNIOConnFactory(clientSSLContext, null, ConnectionConfig.DEFAULT),
                conf.getInt("targets[@connectTimeout]", 0));
        connPool.setMaxTotal(conf.getInt("targets[@connMaxTotal]", 1023));
        connPool.setDefaultMaxPerRoute(conf.getInt("targets[@connMaxPerRoute]", 1023));

        // Set up HTTP protocol processor for outgoing connections
        String userAgent = conf.getString("targets.userAgent", "PokerFace/" + Utils.Version);
        HttpProcessor outhttpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                new RequestContent(), new RequestTargetHost(), new RequestConnControl(),
                new RequestUserAgent(userAgent), new RequestExpectContinue(true) });
        executor = new HttpAsyncRequester(outhttpproc, new DefaultConnectionReuseStrategy());

        // Now set up all the configured targets.
        mappings = new LinkedHashMap<String, TargetDescriptor>();
        hosts = new ConcurrentHashMap<String, HttpHost>();
        String[] scheme = { null };
        String[] host = { null };
        int[] port = { 0 };
        String[] path = { null };
        int[] stripPrefixCount = { 0 };
        for (HierarchicalConfiguration targetConfig : conf.configurationsAt("target")) {
            String match = targetConfig.getString("[@pattern]");
            if ((match == null) || (match.trim().length() < 1)) {
                Logger.error("Unable to configure target;  Invalid url match pattern");
                continue;
            }
            String key = RequestForTargetConsumer.UriToTargetKey(targetConfig.getString("[@url]"), scheme, host,
                    port, path, stripPrefixCount);
            if (key == null) {
                Logger.error("Unable to configure target");
                continue;
            }
            HttpHost targetHost = hosts.get(key);
            if (targetHost == null) {
                targetHost = new HttpHost(host[0], port[0], scheme[0]);
                hosts.put(key, targetHost);
            }
            TargetDescriptor desc = new TargetDescriptor(targetHost, path[0], stripPrefixCount[0]);
            mappings.put(match, desc);
        }
        connectionDispatcher = new DefaultHttpClientIODispatch(new HttpAsyncRequestExecutor(),
                ConnectionConfig.DEFAULT);
    }
    // Allocate the script map which will be populated by it's own executor thread.
    if (config.containsKey("scripts.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("scripts.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Scripts directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'scripts' path is not a directory.");
        scripts = new ConcurrentSkipListMap<String, ScriptObjectMirror>();
        boolean watch = config.getBoolean("scripts.dynamicWatch", false);
        List<Path> jsLibs;
        Object prop = config.getProperty("scripts.library");
        if (prop != null) {
            jsLibs = new ArrayList<Path>();
            if (prop instanceof Collection<?>) {
                @SuppressWarnings("unchecked")
                Collection<Object> oprop = (Collection<Object>) prop;
                for (Object obj : oprop)
                    jsLibs.add(Utils.MakePath(obj));
            } else {
                jsLibs.add(Utils.MakePath(prop));
            }
        } else
            jsLibs = null;

        lconf = config.configurationsAt("scripts.scriptConfig");
        if (lconf != null) {
            if (lconf.size() > 1)
                throw new ConfigurationException("Only one scriptConfig element is allowed.");
            if (lconf.size() == 0)
                lconf = null;
        }

        HierarchicalConfiguration scriptConfig;
        if (lconf == null)
            scriptConfig = new HierarchicalConfiguration();
        else
            scriptConfig = lconf.get(0);
        scriptConfig.setProperty("pokerface.scripts.rootDirectory", tmp.toString());

        configureScripts(jsLibs, scriptConfig, tmp, watch);
        if (watch)
            ScriptDirectoryWatcher = new DirectoryWatchService();
    }

    // Configure the static file directory (if any)
    Path staticFilesPath = null;
    if (config.containsKey("files.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("files.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Files directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'files' path is not a directory.");
        staticFilesPath = tmp;
        List<HierarchicalConfiguration> mimeEntries = config.configurationsAt("files.mime-entry");
        if (mimeEntries != null) {
            for (HierarchicalConfiguration entry : mimeEntries) {
                entry.setDelimiterParsingDisabled(true);
                String type = entry.getString("[@type]", "").trim();
                if (type.length() == 0)
                    throw new ConfigurationException("Invalid mime type entry");
                String extensions = entry.getString("[@extensions]", "").trim();
                if (extensions.length() == 0)
                    throw new ConfigurationException("Invalid mime extensions for: " + type);
                ScriptHelperImpl.AddMimeEntry(type, extensions);
            }
        }
    }

    handlerRegistry.register("/*",
            new RequestHandler(executor, connPool, byteBufferPool, staticFilesPath, mappings,
                    scripts != null ? Collections.unmodifiableNavigableMap(scripts) : null,
                    config.getBoolean("scripts.allowScriptsToSpecifyDynamicHosts", false) ? hosts : null));
}

From source file:org.apache.hive.jdbc.HiveConnection.java

SSLConnectionSocketFactory getTwoWaySSLSocketFactory() throws SQLException {
    SSLConnectionSocketFactory socketFactory = null;

    try {/* w w  w . j  a v  a  2 s  .  com*/
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                JdbcConnectionParams.SUNX509_ALGORITHM_STRING, JdbcConnectionParams.SUNJSSE_ALGORITHM_STRING);
        String keyStorePath = sessConfMap.get(JdbcConnectionParams.SSL_KEY_STORE);
        String keyStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_KEY_STORE_PASSWORD);
        KeyStore sslKeyStore = KeyStore.getInstance(JdbcConnectionParams.SSL_KEY_STORE_TYPE);

        if (keyStorePath == null || keyStorePath.isEmpty()) {
            throw new IllegalArgumentException(JdbcConnectionParams.SSL_KEY_STORE
                    + " Not configured for 2 way SSL connection, keyStorePath param is empty");
        }
        try (FileInputStream fis = new FileInputStream(keyStorePath)) {
            sslKeyStore.load(fis, keyStorePassword.toCharArray());
        }
        keyManagerFactory.init(sslKeyStore, keyStorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(JdbcConnectionParams.SUNX509_ALGORITHM_STRING);
        String trustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE);
        String trustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE);

        if (trustStorePath == null || trustStorePath.isEmpty()) {
            throw new IllegalArgumentException(
                    JdbcConnectionParams.SSL_TRUST_STORE + " Not configured for 2 way SSL connection");
        }
        try (FileInputStream fis = new FileInputStream(trustStorePath)) {
            sslTrustStore.load(fis, trustStorePassword.toCharArray());
        }
        trustManagerFactory.init(sslTrustStore);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
        socketFactory = new SSLConnectionSocketFactory(context);
    } catch (Exception e) {
        throw new SQLException("Error while initializing 2 way ssl socket factory ", e);
    }
    return socketFactory;
}