Search in sources :

Example 1 with ShutdownManager

use of com.sun.identity.common.ShutdownManager in project OpenAM by OpenRock.

the class LDAPFilterCondition method setPolicyConfig.

/**
     * Sets the policy configuration parameters used by this condition.
     */
private synchronized void setPolicyConfig(Map configParams, String realmDn) throws PolicyException {
    if (System.currentTimeMillis() < policyConfigExpiresAt) {
        return;
    }
    if (debug.messageEnabled()) {
        debug.message("LDAPFilterCondition.setPolicyConfig():policy config expired, resetting");
    }
    if (configParams == null) {
        debug.error("LDAPFilterCondition.setPolicyConfig():configParams is null");
        throw new PolicyException(ResBundleUtils.rbName, "ldapfiltercondition_setpolicyconfig_null_policy_config", null, null);
    }
    String configuredLdapServer = (String) configParams.get(PolicyConfig.LDAP_SERVER);
    if (configuredLdapServer == null) {
        debug.error("LDAPFilterCondition.initialize(): failed to get LDAP " + "server name. If you enter more than one server name " + "in the policy config service's Primary LDAP Server " + "field, please make sure the ldap server name is preceded " + "with the local server name.");
        throw new PolicyException(ResBundleUtils.rbName, "invalid_ldap_server_host", null, null);
    }
    ldapServer = configuredLdapServer.toLowerCase();
    aliasEnabled = Boolean.valueOf((String) configParams.get(PolicyConfig.USER_ALIAS_ENABLED));
    authid = (String) configParams.get(PolicyConfig.LDAP_BIND_DN);
    authpw = (String) configParams.get(PolicyConfig.LDAP_BIND_PASSWORD);
    if (authpw != null) {
        authpw = PolicyUtils.decrypt(authpw);
    }
    baseDN = (String) configParams.get(PolicyConfig.LDAP_USERS_BASE_DN);
    userSearchFilter = (String) configParams.get(PolicyConfig.LDAP_USERS_SEARCH_FILTER);
    String scope = (String) configParams.get(PolicyConfig.LDAP_USERS_SEARCH_SCOPE);
    userSearchScope = LDAPUtils.getSearchScope(scope, SearchScope.WHOLE_SUBTREE);
    userRDNAttrName = (String) configParams.get(PolicyConfig.LDAP_USER_SEARCH_ATTRIBUTE);
    try {
        timeLimit = Integer.parseInt((String) configParams.get(PolicyConfig.LDAP_SEARCH_TIME_OUT));
        maxResults = Integer.parseInt((String) configParams.get(PolicyConfig.LDAP_SEARCH_LIMIT));
        minPoolSize = Integer.parseInt((String) configParams.get(PolicyConfig.LDAP_CONNECTION_POOL_MIN_SIZE));
        maxPoolSize = Integer.parseInt((String) configParams.get(PolicyConfig.LDAP_CONNECTION_POOL_MAX_SIZE));
    } catch (NumberFormatException nfe) {
        throw new PolicyException(nfe);
    }
    String ssl = (String) configParams.get(PolicyConfig.LDAP_SSL_ENABLED);
    if (ssl.equalsIgnoreCase("true")) {
        sslEnabled = true;
    } else {
        sslEnabled = false;
    }
    // get the organization name
    if (realmDn != null) {
        orgName = realmDn;
    }
    if (debug.messageEnabled()) {
        debug.message("LDAPFilterCondition.setPolicyConfig(): " + "getting params" + "\nldapServer: " + ldapServer + "\nauthid: " + authid + "\nbaseDN: " + baseDN + "\nuserSearchFilter: " + userSearchFilter + "\nuserRDNAttrName: " + userRDNAttrName + "\ntimeLimit: " + timeLimit + "\nmaxResults: " + maxResults + "\nminPoolSize: " + minPoolSize + "\nmaxPoolSize: " + maxPoolSize + "\nSSLEnabled: " + sslEnabled + "\nOrgName: " + orgName);
    }
    // initialize the connection pool for the ldap server
    Options options = Options.defaultOptions().set(CONNECT_TIMEOUT, new Duration((long) timeLimit, TimeUnit.MILLISECONDS));
    LDAPConnectionPools.initConnectionPool(ldapServer, authid, authpw, sslEnabled, minPoolSize, maxPoolSize, options);
    connPool = LDAPConnectionPools.getConnectionPool(ldapServer);
    ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
    shutdownMan.addShutdownListener(new ShutdownListener() {

        public void shutdown() {
            if (connPool != null) {
                connPool.close();
            }
        }
    });
    policyConfigExpiresAt = System.currentTimeMillis() + PolicyConfig.getSubjectsResultTtl(configParams);
}
Also used : ShutdownListener(org.forgerock.util.thread.listener.ShutdownListener) Options(org.forgerock.util.Options) PolicyException(com.sun.identity.policy.PolicyException) ShutdownManager(com.sun.identity.common.ShutdownManager) Duration(org.forgerock.util.time.Duration)

Example 2 with ShutdownManager

use of com.sun.identity.common.ShutdownManager in project OpenAM by OpenRock.

the class EmbeddedOpenDS method startServer.

/**
     * Starts the embedded <code>OpenDJ</code> instance.
     *
     * @param odsRoot File system directory where <code>OpenDJ</code>
     *                is installed.
     * @throws Exception upon encountering errors.
     */
public static void startServer(String odsRoot) throws Exception {
    if (isStarted()) {
        return;
    }
    Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
    debug.message("EmbeddedOpenDS.startServer(" + odsRoot + ")");
    DirectoryEnvironmentConfig config = new DirectoryEnvironmentConfig();
    config.setServerRoot(new File(odsRoot));
    config.setForceDaemonThreads(true);
    config.setConfigClass(ConfigFileHandler.class);
    config.setConfigFile(new File(odsRoot + "/config", "config.ldif"));
    debug.message("EmbeddedOpenDS.startServer:starting DS Server...");
    EmbeddedUtils.startServer(config);
    debug.message("...EmbeddedOpenDS.startServer:DS Server started.");
    int sleepcount = 0;
    while (!EmbeddedUtils.isRunning() && (sleepcount < 60)) {
        sleepcount++;
        SetupProgress.reportStart("emb.waitingforstarted", null);
        Thread.sleep(1000);
    }
    if (EmbeddedUtils.isRunning()) {
        SetupProgress.reportEnd("emb.success", null);
    } else {
        SetupProgress.reportEnd("emb.failed", null);
    }
    serverStarted = true;
    ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
    shutdownMan.addShutdownListener(new ShutdownListener() {

        public void shutdown() {
            try {
                shutdownServer("Graceful Shutdown");
            } catch (Exception ex) {
                Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
                debug.error("EmbeddedOpenDS:shutdown hook failed", ex);
            }
        }
    }, ShutdownPriority.LOWEST);
}
Also used : ShutdownListener(org.forgerock.util.thread.listener.ShutdownListener) ShutdownManager(com.sun.identity.common.ShutdownManager) DirectoryEnvironmentConfig(org.opends.server.types.DirectoryEnvironmentConfig) ZipFile(java.util.zip.ZipFile) File(java.io.File) Debug(com.sun.identity.shared.debug.Debug) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LdapException(org.forgerock.opendj.ldap.LdapException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException)

Example 3 with ShutdownManager

use of com.sun.identity.common.ShutdownManager in project OpenAM by OpenRock.

the class LDAPAuthUtils method createConnectionPool.

private ConnectionFactory createConnectionPool(Map<String, ConnectionFactory> connectionPools, String bindingUser, char[] bindingPwd) throws LdapException, LDAPUtilException {
    ConnectionFactory connPool;
    try {
        String configName = servers.toString() + ":" + bindingUser;
        connPool = connectionPools.get(configName);
        if (connPool == null) {
            synchronized (connectionPools) {
                connPool = connectionPools.get(configName);
                Options options = Options.defaultOptions().set(REQUEST_TIMEOUT, new Duration((long) operationsTimeout, TimeUnit.MILLISECONDS));
                if (connPool == null) {
                    if (debug.messageEnabled()) {
                        debug.message("Create ConnectionPool for servers:\n" + servers);
                    }
                    // Since connection pool for search and authentication
                    // are different, each gets half the configured size
                    int min = minDefaultPoolSize / 2 + 1;
                    int max = maxDefaultPoolSize / 2;
                    if (min >= max) {
                        min = max - 1;
                    }
                    Set<LDAPURL> primaryUrls = convertToLDAPURLs(primaryServers);
                    Set<LDAPURL> secondaryUrls = convertToLDAPURLs(secondaryServers);
                    if (poolSize != null && !poolSize.isEmpty()) {
                        String tmpmin = null;
                        String tmpmax = null;
                        for (String val : poolSize) {
                            // host:port:min:max
                            StringTokenizer stz = new StringTokenizer(val, ":");
                            if (stz.countTokens() == 4) {
                                LDAPURL url = LDAPURL.valueOf(stz.nextToken() + ":" + stz.nextToken());
                                if (primaryUrls.contains(url) || secondaryUrls.contains(url)) {
                                    tmpmin = stz.nextToken();
                                    tmpmax = stz.nextToken();
                                    break;
                                }
                            }
                        }
                        if (tmpmin != null) {
                            try {
                                min = Integer.parseInt(tmpmin);
                                max = Integer.parseInt(tmpmax);
                                if (max < min) {
                                    debug.error("ldap connection pool max size is less than min size");
                                    min = minDefaultPoolSize;
                                    max = maxDefaultPoolSize;
                                }
                            } catch (NumberFormatException ex) {
                                debug.error("Invalid ldap connection pool size", ex);
                                min = minDefaultPoolSize;
                                max = maxDefaultPoolSize;
                            }
                        }
                    }
                    if (debug.messageEnabled()) {
                        debug.message("LDAPAuthUtils.LDAPAuthUtils: min=" + min + ", max=" + max);
                    }
                    if (isSecure) {
                        SSLContextBuilder builder = new SSLContextBuilder();
                        if (trustAll) {
                            builder.setTrustManager(TrustManagers.trustAll());
                        }
                        SSLContext sslContext = builder.getSSLContext();
                        options.set(SSL_CONTEXT, sslContext);
                        if (useStartTLS) {
                            options.set(SSL_USE_STARTTLS, true);
                        }
                    }
                    final ConnectionFactory connFactory;
                    ConnectionFactory primaryCf = newFailoverConnectionPool(primaryUrls, bindingUser, bindingPwd, max, heartBeatInterval, heartBeatTimeUnit, options);
                    if (secondaryServers.isEmpty()) {
                        connFactory = primaryCf;
                    } else {
                        ConnectionFactory secondaryCf = newFailoverConnectionPool(secondaryUrls, bindingUser, bindingPwd, max, heartBeatInterval, heartBeatTimeUnit, options);
                        connFactory = Connections.newFailoverLoadBalancer(asList(primaryCf, secondaryCf), options);
                    }
                    ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
                    shutdownMan.addShutdownListener(new ShutdownListener() {

                        public void shutdown() {
                            connFactory.close();
                        }
                    });
                    connPool = connFactory;
                    connectionPools.put(configName, connPool);
                }
            }
        }
    } catch (GeneralSecurityException gse) {
        debug.error("Unable to create connection pool", gse);
        throw new LDAPUtilException(gse);
    }
    return connPool;
}
Also used : Options(org.forgerock.util.Options) DecodeOptions(org.forgerock.opendj.ldap.DecodeOptions) GeneralSecurityException(java.security.GeneralSecurityException) ShutdownManager(com.sun.identity.common.ShutdownManager) Duration(org.forgerock.util.time.Duration) ByteString(org.forgerock.opendj.ldap.ByteString) SSLContext(javax.net.ssl.SSLContext) ShutdownListener(org.forgerock.util.thread.listener.ShutdownListener) ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) StringTokenizer(java.util.StringTokenizer) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder)

Aggregations

ShutdownManager (com.sun.identity.common.ShutdownManager)3 ShutdownListener (org.forgerock.util.thread.listener.ShutdownListener)3 Options (org.forgerock.util.Options)2 Duration (org.forgerock.util.time.Duration)2 PolicyException (com.sun.identity.policy.PolicyException)1 Debug (com.sun.identity.shared.debug.Debug)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 GeneralSecurityException (java.security.GeneralSecurityException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 StringTokenizer (java.util.StringTokenizer)1 ZipFile (java.util.zip.ZipFile)1 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)1 SSLContext (javax.net.ssl.SSLContext)1 ByteString (org.forgerock.opendj.ldap.ByteString)1 ConnectionFactory (org.forgerock.opendj.ldap.ConnectionFactory)1 DecodeOptions (org.forgerock.opendj.ldap.DecodeOptions)1 LDAPConnectionFactory (org.forgerock.opendj.ldap.LDAPConnectionFactory)1 LdapException (org.forgerock.opendj.ldap.LdapException)1