Example usage for javax.net.ssl SSLContext getSocketFactory

List of usage examples for javax.net.ssl SSLContext getSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getSocketFactory.

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:org.jab.docsearch.spider.LinkFinder.java

/**
 * Method init/*w  w w. j a v a 2 s  .c o  m*/
 */
private void init() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            // nothing
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            // nothing
        }
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        logger.error("init() failed", e);
    }
}

From source file:org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduit.java

public void initializeSSLEngine(SSLContext sslcontext, SSLEngine sslengine) {
    TLSClientParameters tlsClientParameters = getTlsClientParameters();
    if (tlsClientParameters == null) {
        tlsClientParameters = new TLSClientParameters();
    }//from  w ww.  ja  va2 s.  c o m

    String[] cipherSuites = SSLUtils.getCiphersuitesToInclude(tlsClientParameters.getCipherSuites(),
            tlsClientParameters.getCipherSuitesFilter(), sslcontext.getSocketFactory().getDefaultCipherSuites(),
            SSLUtils.getSupportedCipherSuites(sslcontext), LOG);
    sslengine.setEnabledCipherSuites(cipherSuites);

    String protocol = tlsClientParameters.getSecureSocketProtocol() != null
            ? tlsClientParameters.getSecureSocketProtocol()
            : "TLS";

    String p[] = findProtocols(protocol, sslengine.getSupportedProtocols());
    if (p != null) {
        sslengine.setEnabledProtocols(p);
    }
}

From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java

@Before
public void setup() throws Exception {
    config.setString(WebOptions.UPLOAD_DIR, temporaryFolder.newFolder().getCanonicalPath());

    defaultSSLContext = SSLContext.getDefault();
    defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    final SSLContext sslClientContext = SSLUtils.createRestClientSSLContext(config);
    if (sslClientContext != null) {
        SSLContext.setDefault(sslClientContext);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslClientContext.getSocketFactory());
    }/*from w w w.j  a v a2 s. com*/

    RestServerEndpointConfiguration serverConfig = RestServerEndpointConfiguration.fromConfiguration(config);
    RestClientConfiguration clientConfig = RestClientConfiguration.fromConfiguration(config);

    final String restAddress = "http://localhost:1234";
    RestfulGateway mockRestfulGateway = mock(RestfulGateway.class);
    when(mockRestfulGateway.requestRestAddress(any(Time.class)))
            .thenReturn(CompletableFuture.completedFuture(restAddress));

    final GatewayRetriever<RestfulGateway> mockGatewayRetriever = () -> CompletableFuture
            .completedFuture(mockRestfulGateway);

    testHandler = new TestHandler(CompletableFuture.completedFuture(restAddress), mockGatewayRetriever,
            RpcUtils.INF_TIMEOUT);

    TestVersionHandler testVersionHandler = new TestVersionHandler(
            CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT);

    TestVersionSelectionHandler1 testVersionSelectionHandler1 = new TestVersionSelectionHandler1(
            CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT);

    TestVersionSelectionHandler2 testVersionSelectionHandler2 = new TestVersionSelectionHandler2(
            CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT);

    testUploadHandler = new TestUploadHandler(CompletableFuture.completedFuture(restAddress),
            mockGatewayRetriever, RpcUtils.INF_TIMEOUT);

    final StaticFileServerHandler<RestfulGateway> staticFileServerHandler = new StaticFileServerHandler<>(
            mockGatewayRetriever, CompletableFuture.completedFuture(restAddress), RpcUtils.INF_TIMEOUT,
            temporaryFolder.getRoot());

    final List<Tuple2<RestHandlerSpecification, ChannelInboundHandler>> handlers = Arrays.asList(
            Tuple2.of(new TestHeaders(), testHandler), Tuple2.of(TestUploadHeaders.INSTANCE, testUploadHandler),
            Tuple2.of(testVersionHandler.getMessageHeaders(), testVersionHandler),
            Tuple2.of(testVersionSelectionHandler1.getMessageHeaders(), testVersionSelectionHandler1),
            Tuple2.of(testVersionSelectionHandler2.getMessageHeaders(), testVersionSelectionHandler2),
            Tuple2.of(WebContentHandlerSpecification.getInstance(), staticFileServerHandler));

    serverEndpoint = new TestRestServerEndpoint(serverConfig, handlers);
    restClient = new TestRestClient(clientConfig);

    serverEndpoint.start();
    serverAddress = serverEndpoint.getServerAddress();
}

From source file:com.siviton.huanapi.data.HuanApi.java

public void AutoLoginUser() {

    new Thread() {

        public void run() {

            JSONObject jsonObject2 = new JSONObject();
            try {
                jsonObject2.putOpt("dnum", getdnum());
                jsonObject2.putOpt("didtoken", getdidtoken());
            } catch (JSONException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();//from w w w  . j  a v a2 s  . c o  m
            }
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.putOpt("action", "AutoLoginUser");
                jsonObject.putOpt("device", jsonObject2);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                byte[] entity = jsonObject.toString().getBytes();
                URL url = new URL(getDeviceUrl());
                HttpsURLConnection connections = (HttpsURLConnection) url.openConnection();
                if (connections instanceof HttpsURLConnection) {
                    // Trust all certificates
                    SSLContext context = SSLContext.getInstance("SSL");
                    context.init(new KeyManager[0], xtmArray, new SecureRandom());
                    SSLSocketFactory socketFactory = context.getSocketFactory();
                    ((HttpsURLConnection) connections).setSSLSocketFactory(socketFactory);
                    ((HttpsURLConnection) connections).setHostnameVerifier(HOSTNAME_VERIFIER);
                }
                connections.setConnectTimeout(5 * 1000);
                connections.setRequestMethod("POST");
                connections.setDoOutput(true);// ??
                connections.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connections.setRequestProperty("Content-Length", String.valueOf(entity.length));
                OutputStream outStream = connections.getOutputStream();
                outStream.write(entity);
                outStream.flush();
                outStream.close();
                if (connections.getResponseCode() == 200) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connections.getInputStream()));
                    String line = "";
                    StringBuilder stringBuffer = new StringBuilder();
                    while ((line = in.readLine()) != null) {
                        stringBuffer.append("" + line + "\n");
                        System.out.println("==pengbdata==AutoLoginUser=====" + line);
                    }
                    in.close();

                    JSONObject object = new JSONObject("" + stringBuffer.toString());

                    JSONObject object2 = null;
                    try {
                        object2 = object.getJSONObject("error");
                        String code = object2.getString("code");
                        String info = object2.getString("info");
                        if (!code.equals("0")) {
                            mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_ERROR_COCDE,
                                    "" + info, null, null, null);
                        } else {
                            object2 = object.getJSONObject("user");
                            String huanid = object2.getString("huanid");
                            String token = object2.getString("token");
                            if (token != null && huanid != null) {
                                huanItemInfo.setToken(token);
                                huanItemInfo.setHuanid(huanid);
                                updateData();
                                mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_LOGIN_SUCC,
                                        "user succ", null, null, null);
                            } else {
                                // ?
                                mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_HUANIDTOKEN_NULL,
                                        "huanid or huanid is null", null, null, null);
                            }
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                        mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_JESON_EXCEPTION,
                                e.toString(), null, null, null);
                    }

                } else {
                    // 
                    mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_NETCODE_ISNO200,
                            "user   network error", null, null, null);
                }

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_NETCODE_EXCEPTION,
                        "user   network error" + e.toString(), null, null, null);
            }

        };

    }.start();

}

From source file:org.parosproxy.paros.network.SSLConnector.java

public SSLSocketFactory getTunnelSSLSocketFactory(String hostname) {

    //   SSLServerSocketFactory ssf = null;
    // set up key manager to do server authentication

    //   KeyStore ks;
    try {/*from w ww.ja  v a  2  s  .  com*/
        SSLContext ctx = SSLContext.getInstance(SSL);
        // Normally "SunX509", "IbmX509"...
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        SslCertificateService scs = CachedSslCertifificateServiceImpl.getService();
        KeyStore ks = scs.createCertForHost(hostname);

        kmf.init(ks, SslCertificateService.PASSPHRASE);
        java.security.SecureRandom x = new java.security.SecureRandom();
        x.setSeed(System.currentTimeMillis());
        ctx.init(kmf.getKeyManagers(), null, x);

        SSLSocketFactory tunnelSSLFactory = createDecoratedServerSslSocketFactory(ctx.getSocketFactory());

        return tunnelSSLFactory;

    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | UnrecoverableKeyException
            | KeyManagementException | InvalidKeyException | NoSuchProviderException | SignatureException
            | IOException e) {
        // Turn into RuntimeException. How to handle this error in a user
        // friendly way?
        throw new RuntimeException(e);
    }
}

From source file:android.webkit.cts.CtsTestServer.java

private URLConnection openConnection(URL url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    if (mSsl == SslMode.INSECURE) {
        return url.openConnection();
    } else {//  w  ww. j  a v  a2s.c  o m
        // Install hostname verifiers and trust managers that don't do
        // anything in order to get around the client not trusting
        // the test server due to a lack of certificates.

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(new CtsHostnameVerifier());

        SSLContext context = SSLContext.getInstance("TLS");
        try {
            context.init(ServerThread.getKeyManagers(), getTrustManagers(), null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        connection.setSSLSocketFactory(context.getSocketFactory());

        return connection;
    }
}

From source file:com.siviton.huanapi.data.HuanApi.java

public void DeviceActive() {
    if (huanItemInfo.getDnum() != null && huanItemInfo.getActivekey() != null) {
        mHuanLoginListen.StateChange(STATE_DEVICEACTIVE, STATE_DEVICEACTIVE_ISALREADYACTIVE,
                "is already active", null, null, null);
        return;//from  w ww . j a v a2s .c  o  m
    }
    new Thread() {
        public void run() {
            JSONObject jsonObject2 = new JSONObject();
            try {
                jsonObject2.putOpt("deviceid", getdeviceid());
                jsonObject2.putOpt("devmodel", getdevmodel());
                jsonObject2.putOpt("devserial", getdevserial());
                jsonObject2.putOpt("devmac", getdevmac());
            } catch (JSONException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.putOpt("action", "DeviceActive");
                jsonObject.putOpt("locale", getlocale());
                jsonObject.putOpt("timezone", gettimezone());
                jsonObject.putOpt("region", getregion());
                jsonObject.putOpt("device", jsonObject2);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            System.out.println("===pengbdata==DeviceActive====" + jsonObject.toString());
            try {
                byte[] entity = jsonObject.toString().getBytes();
                URL url = new URL(getDeviceUrl());
                conn = (HttpsURLConnection) url.openConnection();
                if (conn instanceof HttpsURLConnection) {
                    // Trust all certificates
                    SSLContext context = SSLContext.getInstance("SSL");
                    context.init(new KeyManager[0], xtmArray, new SecureRandom());
                    SSLSocketFactory socketFactory = context.getSocketFactory();
                    ((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory);
                    ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);
                }
                conn.setConnectTimeout(5 * 1000);
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);// ??
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
                OutputStream outStream = conn.getOutputStream();
                outStream.write(entity);
                outStream.flush();
                outStream.close();
                if (conn.getResponseCode() == 200) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line = "";
                    StringBuilder stringBuffer = new StringBuilder();
                    while ((line = in.readLine()) != null) {
                        stringBuffer.append("" + line + "\n");
                        System.out.println("==pengbdata==DeviceActive======" + line);
                    }
                    in.close();

                    JSONObject object = new JSONObject("" + stringBuffer.toString());

                    JSONObject object2 = null;
                    try {
                        object2 = object.getJSONObject("error");
                        String code = object2.getString("code");
                        String info = object2.getString("info");
                        if (!code.equals("0")) {
                            mHuanLoginListen.StateChange(STATE_DEVICEACTIVE, STATE_DEVICEACTIVE_ERROR_COCDE,
                                    "" + info, null, null, null);
                        } else {
                            object2 = object.getJSONObject("device");
                            String dnum = object2.getString("dnum");
                            String activekey = object2.getString("activekey");
                            if (dnum != null && activekey != null) {
                                huanItemInfo.setDnum(dnum);
                                huanItemInfo.setActivekey(activekey);
                                huanItemInfo.setDidtoken(getMD5(getdeviceid() + getactivekey()));
                                System.out.println("==pengbdata==DeviceActive======" + dnum.getBytes().length
                                        + "==" + huanItemInfo.getDeviceid() + "==="
                                        + huanItemInfo.getDevicemodel() + "===" + huanItemInfo.getDidtoken()
                                        + "===" + huanItemInfo.getActivekey() + "===" + huanItemInfo.getDnum());
                                updateData();
                                mHuanLoginListen.StateChange(STATE_DEVICEACTIVE, STATE_DEVICEACTIVE_ACTIVE_SUCC,
                                        "active succ", null, null, null);
                            } else {
                                // ?
                                mHuanLoginListen.StateChange(STATE_DEVICEACTIVE,
                                        STATE_DEVICEACTIVE_DNUMORACTIVE_NULL, "dnum or activekey is null", null,
                                        null, null);
                            }
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                        mHuanLoginListen.StateChange(STATE_DEVICEACTIVE, STATE_DEVICEACTIVE_JESON_EXCEPTION,
                                e.toString(), null, null, null);
                    }

                } else {
                    // 
                    mHuanLoginListen.StateChange(STATE_DEVICEACTIVE, STATE_DEVICEACTIVE_NETCODE_ISNO200,
                            "active net error", null, null, null);
                }

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                mHuanLoginListen.StateChange(STATE_DEVICEACTIVE, STATE_DEVICEACTIVE_NET_EXCEPTION, e.toString(),
                        null, null, null);
            }

        };

    }.start();
}

From source file:com.siviton.huanapi.data.HuanApi.java

public void DeviceLogin() {

    new Thread() {

        public void run() {

            JSONObject jsonObject2 = new JSONObject();
            try {
                jsonObject2.putOpt("dnum", getdnum());
                jsonObject2.putOpt("didtoken", getdidtoken());
                jsonObject2.putOpt("activekey", getactivekey());
            } catch (JSONException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();//  w  w  w  .  j a va 2  s.  com
            }
            JSONObject jsonObject3 = new JSONObject();
            try {
                jsonObject3.putOpt("ostype", getostype());
                jsonObject3.putOpt("osversion", getosversion());
                jsonObject3.putOpt("kernelversion", getkernelversion());
                jsonObject3.putOpt("webinfo", getwebinfo());
                jsonObject3.putOpt("javainfo", getjavainfo());
                jsonObject3.putOpt("flashinfo", getflashinfo());
            } catch (JSONException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.putOpt("action", "DeviceLogin");
                jsonObject.putOpt("device", jsonObject2);
                jsonObject.putOpt("param", jsonObject3);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                byte[] entity = jsonObject.toString().getBytes();
                URL url = new URL(getDeviceUrl());
                HttpsURLConnection connections = (HttpsURLConnection) url.openConnection();
                if (connections instanceof HttpsURLConnection) {
                    // Trust all certificates
                    SSLContext context = SSLContext.getInstance("SSL");
                    context.init(new KeyManager[0], xtmArray, new SecureRandom());
                    SSLSocketFactory socketFactory = context.getSocketFactory();
                    ((HttpsURLConnection) connections).setSSLSocketFactory(socketFactory);
                    ((HttpsURLConnection) connections).setHostnameVerifier(HOSTNAME_VERIFIER);
                }
                connections.setConnectTimeout(5 * 1000);
                connections.setRequestMethod("POST");
                connections.setDoOutput(true);// ??
                connections.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connections.setRequestProperty("Content-Length", String.valueOf(entity.length));
                OutputStream outStream = connections.getOutputStream();
                outStream.write(entity);
                outStream.flush();
                outStream.close();
                if (connections.getResponseCode() == 200) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connections.getInputStream()));
                    String line = "";
                    StringBuilder stringBuffer = new StringBuilder();
                    while ((line = in.readLine()) != null) {
                        stringBuffer.append("" + line + "\n");
                        System.out.println("==pengbdata==DeviceLogin=====" + line);
                    }
                    in.close();

                    JSONObject object = new JSONObject("" + stringBuffer.toString());

                    JSONObject object2 = null;
                    try {
                        object2 = object.getJSONObject("error");
                        String code = object2.getString("code");
                        String info = object2.getString("info");
                        if (!code.equals("0")) {
                            mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_ERROR_COCDE,
                                    "" + info, null, null, null);
                        } else {
                            object2 = object.getJSONObject("device");
                            String activekey = object2.getString("activekey");
                            if (activekey != null) {
                                huanItemInfo.setActivekey(activekey);
                                huanItemInfo.setDidtoken(getMD5(getdeviceid() + getactivekey()));
                                System.out.println("==pengbdata==DeviceLogin======" + huanItemInfo.getDeviceid()
                                        + "===" + huanItemInfo.getDevicemodel() + "==="
                                        + huanItemInfo.getDidtoken() + "===" + huanItemInfo.getActivekey()
                                        + "===" + huanItemInfo.getDnum());
                                updateData();
                                mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_LOGIN_SUCC,
                                        "DeviceLogin succ", null, null, null);
                            } else {
                                // ?
                                mHuanLoginListen.StateChange(STATE_DEVICELOGIN,
                                        STATE_DEVICELOGIN_ACTIVEKEY_NULL, "dnum or activekey is null", null,
                                        null, null);
                            }
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                        mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_JESON_EXCEPTION,
                                e.toString(), null, null, null);
                    }

                } else {
                    // 
                    mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_NETCODE_ISNO200,
                            "DeviceLogin   network error", null, null, null);
                }

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_NETCODE_EXCEPTION,
                        "DeviceLogin   network error" + e.toString(), null, null, null);
            }

        };

    }.start();

}

From source file:org.apache.nifi.registry.security.ldap.tenants.LdapUserGroupProvider.java

@Override
public void onConfigured(final AuthorizerConfigurationContext configurationContext)
        throws SecurityProviderCreationException {
    final LdapContextSource context = new LdapContextSource();

    final Map<String, Object> baseEnvironment = new HashMap<>();

    // connect/read time out
    setTimeout(configurationContext, baseEnvironment, PROP_CONNECT_TIMEOUT,
            "com.sun.jndi.ldap.connect.timeout");
    setTimeout(configurationContext, baseEnvironment, PROP_READ_TIMEOUT, "com.sun.jndi.ldap.read.timeout");

    // authentication strategy
    final PropertyValue rawAuthenticationStrategy = configurationContext
            .getProperty(PROP_AUTHENTICATION_STRATEGY);
    final LdapAuthenticationStrategy authenticationStrategy;
    try {/*ww w .j a  va 2  s  .  c  o  m*/
        authenticationStrategy = LdapAuthenticationStrategy.valueOf(rawAuthenticationStrategy.getValue());
    } catch (final IllegalArgumentException iae) {
        throw new SecurityProviderCreationException(
                String.format("Unrecognized authentication strategy '%s'. Possible values are [%s]",
                        rawAuthenticationStrategy.getValue(),
                        StringUtils.join(LdapAuthenticationStrategy.values(), ", ")));
    }

    switch (authenticationStrategy) {
    case ANONYMOUS:
        context.setAnonymousReadOnly(true);
        break;
    default:
        final String userDn = configurationContext.getProperty(PROP_MANAGER_DN).getValue();
        final String password = configurationContext.getProperty(PROP_MANAGER_PASSWORD).getValue();

        context.setUserDn(userDn);
        context.setPassword(password);

        switch (authenticationStrategy) {
        case SIMPLE:
            context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy());
            break;
        case LDAPS:
            context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy());

            // indicate a secure connection
            baseEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");

            // get the configured ssl context
            final SSLContext ldapsSslContext = getConfiguredSslContext(configurationContext);
            if (ldapsSslContext != null) {
                // initialize the ldaps socket factory prior to use
                LdapsSocketFactory.initialize(ldapsSslContext.getSocketFactory());
                baseEnvironment.put("java.naming.ldap.factory.socket", LdapsSocketFactory.class.getName());
            }
            break;
        case START_TLS:
            final AbstractTlsDirContextAuthenticationStrategy tlsAuthenticationStrategy = new DefaultTlsDirContextAuthenticationStrategy();

            // shutdown gracefully
            final String rawShutdownGracefully = configurationContext.getProperty("TLS - Shutdown Gracefully")
                    .getValue();
            if (StringUtils.isNotBlank(rawShutdownGracefully)) {
                final boolean shutdownGracefully = Boolean.TRUE.toString()
                        .equalsIgnoreCase(rawShutdownGracefully);
                tlsAuthenticationStrategy.setShutdownTlsGracefully(shutdownGracefully);
            }

            // get the configured ssl context
            final SSLContext startTlsSslContext = getConfiguredSslContext(configurationContext);
            if (startTlsSslContext != null) {
                tlsAuthenticationStrategy.setSslSocketFactory(startTlsSslContext.getSocketFactory());
            }

            // set the authentication strategy
            context.setAuthenticationStrategy(tlsAuthenticationStrategy);
            break;
        }
        break;
    }

    // referrals
    final String rawReferralStrategy = configurationContext.getProperty(PROP_REFERRAL_STRATEGY).getValue();

    final ReferralStrategy referralStrategy;
    try {
        referralStrategy = ReferralStrategy.valueOf(rawReferralStrategy);
    } catch (final IllegalArgumentException iae) {
        throw new SecurityProviderCreationException(
                String.format("Unrecognized referral strategy '%s'. Possible values are [%s]",
                        rawReferralStrategy, StringUtils.join(ReferralStrategy.values(), ", ")));
    }

    // using the value as this needs to be the lowercase version while the value is configured with the enum constant
    context.setReferral(referralStrategy.getValue());

    // url
    final String urls = configurationContext.getProperty(PROP_URL).getValue();

    if (StringUtils.isBlank(urls)) {
        throw new SecurityProviderCreationException("LDAP identity provider 'Url' must be specified.");
    }

    // connection
    context.setUrls(StringUtils.split(urls));

    // raw user search base
    final PropertyValue rawUserSearchBase = configurationContext.getProperty(PROP_USER_SEARCH_BASE);
    final PropertyValue rawUserObjectClass = configurationContext.getProperty(PROP_USER_OBJECT_CLASS);
    final PropertyValue rawUserSearchScope = configurationContext.getProperty(PROP_USER_SEARCH_SCOPE);

    // if loading the users, ensure the object class set
    if (rawUserSearchBase.isSet() && !rawUserObjectClass.isSet()) {
        throw new SecurityProviderCreationException(
                "LDAP user group provider 'User Object Class' must be specified when 'User Search Base' is set.");
    }

    // if loading the users, ensure the search scope is set
    if (rawUserSearchBase.isSet() && !rawUserSearchScope.isSet()) {
        throw new SecurityProviderCreationException(
                "LDAP user group provider 'User Search Scope' must be specified when 'User Search Base' is set.");
    }

    // user search criteria
    userSearchBase = rawUserSearchBase.getValue();
    userObjectClass = rawUserObjectClass.getValue();
    userSearchFilter = configurationContext.getProperty(PROP_USER_SEARCH_FILTER).getValue();
    userIdentityAttribute = configurationContext.getProperty(PROP_USER_IDENTITY_ATTRIBUTE).getValue();
    userGroupNameAttribute = configurationContext.getProperty(PROP_USER_GROUP_ATTRIBUTE).getValue();
    userGroupReferencedGroupAttribute = configurationContext
            .getProperty(PROP_USER_GROUP_REFERENCED_GROUP_ATTRIBUTE).getValue();

    try {
        userSearchScope = SearchScope.valueOf(rawUserSearchScope.getValue());
    } catch (final IllegalArgumentException iae) {
        throw new SecurityProviderCreationException(
                String.format("Unrecognized user search scope '%s'. Possible values are [%s]",
                        rawUserSearchScope.getValue(), StringUtils.join(SearchScope.values(), ", ")));
    }

    // determine user behavior
    useDnForUserIdentity = StringUtils.isBlank(userIdentityAttribute);
    performUserSearch = StringUtils.isNotBlank(userSearchBase);

    // raw group search criteria
    final PropertyValue rawGroupSearchBase = configurationContext.getProperty(PROP_GROUP_SEARCH_BASE);
    final PropertyValue rawGroupObjectClass = configurationContext.getProperty(PROP_GROUP_OBJECT_CLASS);
    final PropertyValue rawGroupSearchScope = configurationContext.getProperty(PROP_GROUP_SEARCH_SCOPE);

    // if loading the groups, ensure the object class is set
    if (rawGroupSearchBase.isSet() && !rawGroupObjectClass.isSet()) {
        throw new SecurityProviderCreationException(
                "LDAP user group provider 'Group Object Class' must be specified when 'Group Search Base' is set.");
    }

    // if loading the groups, ensure the search scope is set
    if (rawGroupSearchBase.isSet() && !rawGroupSearchScope.isSet()) {
        throw new SecurityProviderCreationException(
                "LDAP user group provider 'Group Search Scope' must be specified when 'Group Search Base' is set.");
    }

    // group search criteria
    groupSearchBase = rawGroupSearchBase.getValue();
    groupObjectClass = rawGroupObjectClass.getValue();
    groupSearchFilter = configurationContext.getProperty(PROP_GROUP_SEARCH_FILTER).getValue();
    groupNameAttribute = configurationContext.getProperty(PROP_GROUP_NAME_ATTRIBUTE).getValue();
    groupMemberAttribute = configurationContext.getProperty(PROP_GROUP_MEMBER_ATTRIBUTE).getValue();
    groupMemberReferencedUserAttribute = configurationContext
            .getProperty(PROP_GROUP_MEMBER_REFERENCED_USER_ATTRIBUTE).getValue();

    try {
        groupSearchScope = SearchScope.valueOf(rawGroupSearchScope.getValue());
    } catch (final IllegalArgumentException iae) {
        throw new SecurityProviderCreationException(
                String.format("Unrecognized group search scope '%s'. Possible values are [%s]",
                        rawGroupSearchScope.getValue(), StringUtils.join(SearchScope.values(), ", ")));
    }

    // determine group behavior
    useDnForGroupName = StringUtils.isBlank(groupNameAttribute);
    performGroupSearch = StringUtils.isNotBlank(groupSearchBase);

    // ensure we are either searching users or groups (at least one must be specified)
    if (!performUserSearch && !performGroupSearch) {
        throw new SecurityProviderCreationException(
                "LDAP user group provider 'User Search Base' or 'Group Search Base' must be specified.");
    }

    // ensure group member attribute is set if searching groups but not users
    if (performGroupSearch && !performUserSearch && StringUtils.isBlank(groupMemberAttribute)) {
        throw new SecurityProviderCreationException(
                "'Group Member Attribute' is required when searching groups but not users.");
    }

    // ensure that performUserSearch is set when groupMemberReferencedUserAttribute is specified
    if (StringUtils.isNotBlank(groupMemberReferencedUserAttribute) && !performUserSearch) {
        throw new SecurityProviderCreationException(
                "''User Search Base' must be set when specifying 'Group Member Attribute - Referenced User Attribute'.");
    }

    // ensure that performGroupSearch is set when userGroupReferencedGroupAttribute is specified
    if (StringUtils.isNotBlank(userGroupReferencedGroupAttribute) && !performGroupSearch) {
        throw new SecurityProviderCreationException(
                "'Group Search Base' must be set when specifying 'User Group Name Attribute - Referenced Group Attribute'.");
    }

    // get the page size if configured
    final PropertyValue rawPageSize = configurationContext.getProperty(PROP_PAGE_SIZE);
    if (rawPageSize.isSet() && StringUtils.isNotBlank(rawPageSize.getValue())) {
        pageSize = rawPageSize.asInteger();
    }

    // extract the identity mappings from nifi-registry.properties if any are provided
    identityMappings = Collections.unmodifiableList(IdentityMappingUtil.getIdentityMappings(properties));

    // set the base environment is necessary
    if (!baseEnvironment.isEmpty()) {
        context.setBaseEnvironmentProperties(baseEnvironment);
    }

    try {
        // handling initializing beans
        context.afterPropertiesSet();
    } catch (final Exception e) {
        throw new SecurityProviderCreationException(e.getMessage(), e);
    }

    final PropertyValue rawSyncInterval = configurationContext.getProperty(PROP_SYNC_INTERVAL);
    final long syncInterval;
    if (rawSyncInterval.isSet()) {
        try {
            syncInterval = FormatUtils.getTimeDuration(rawSyncInterval.getValue(), TimeUnit.MILLISECONDS);
        } catch (final IllegalArgumentException iae) {
            throw new SecurityProviderCreationException(
                    String.format("The %s '%s' is not a valid time duration", PROP_SYNC_INTERVAL,
                            rawSyncInterval.getValue()));
        }
    } else {
        throw new SecurityProviderCreationException("The 'Sync Interval' must be specified.");
    }

    try {
        // perform the initial load, tenants must be loaded as the configured UserGroupProvider is supplied
        // to the AccessPolicyProvider for granting initial permissions
        load(context);

        // ensure the tenants were successfully synced
        if (tenants.get() == null) {
            throw new SecurityProviderCreationException("Unable to sync users and groups.");
        }

        // schedule the background thread to load the users/groups
        ldapSync.scheduleWithFixedDelay(() -> load(context), syncInterval, syncInterval, TimeUnit.MILLISECONDS);
    } catch (final AuthorizationAccessException e) {
        throw new SecurityProviderCreationException(e);
    }
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Downloads the string that's in the url with any certificate.
 *///from   w  w  w . java2  s.c  o  m
private String downloadWithoutCA(String url_string) {
    String string = "";
    try {

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        class DefaultTrustManager implements X509TrustManager {

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());

        URL url = new URL(url_string);
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(context.getSocketFactory());
        urlConnection.setHostnameVerifier(hostnameVerifier);
        string = new Scanner(urlConnection.getInputStream()).useDelimiter("\\A").next();
        System.out.println("String ignoring certificate = " + string);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        string = formatErrorMessage(R.string.malformed_url);
    } catch (IOException e) {
        // The downloaded certificate doesn't validate our https connection.
        e.printStackTrace();
        string = formatErrorMessage(R.string.certificate_error);
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return string;
}