Search in sources :

Example 1 with ConnectionFactory

use of org.forgerock.opendj.ldap.ConnectionFactory in project OpenAM by OpenRock.

the class AddAMSDKIdRepoPlugin method loadLDIFs.

private void loadLDIFs() throws Exception {
    CommandManager mgr = getCommandManager();
    List ldifs = getLDIFs();
    for (Iterator i = directoryServers.iterator(); i.hasNext(); ) {
        String dshost = (String) i.next();
        try (ConnectionFactory factory = getLDAPConnection(new DSEntry(dshost));
            Connection ld = factory.getConnection()) {
            String dbName = LDAPUtils.getDBName(basedn, ld);
            for (Iterator j = ldifs.iterator(); j.hasNext(); ) {
                String file = (String) j.next();
                String content = CLIUtil.getFileContent(mgr, file);
                String swapped = tagswap(content, dbName);
                loadLDIF(ld, swapped);
            }
        }
    }
}
Also used : ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) CommandManager(com.sun.identity.cli.CommandManager) Iterator(java.util.Iterator) Connection(org.forgerock.opendj.ldap.Connection) List(java.util.List) ArrayList(java.util.ArrayList)

Example 2 with ConnectionFactory

use of org.forgerock.opendj.ldap.ConnectionFactory in project OpenAM by OpenRock.

the class LocalLdapAuthModule method authenticate.

private boolean authenticate(String dn, String passwd) throws LoginException {
    // LDAP connection used for authentication
    Connection localConn = null;
    String host;
    int port;
    Options ldapOptions = Options.defaultOptions();
    // Check if organization is present in options
    String orgUrl = (String) options.get(LoginContext.ORGNAME);
    if ((orgUrl == null) || (orgUrl.equals(LoginContext.LDAP_AUTH_URL)) || (orgUrl.equals(LoginContext.LDAPS_AUTH_URL)) || !(orgUrl.startsWith(LoginContext.LDAP_AUTH_URL) || orgUrl.startsWith(LoginContext.LDAPS_AUTH_URL))) {
        try {
            DSConfigMgr dscm = DSConfigMgr.getDSConfigMgr();
            // We need a handle on server instance so we can know the
            // Connection type. If it is SSL, the connection needs to be
            // accordingly created. Note: The user type does not make
            // a difference, as the connection type is Server group based,
            // so passing any user type for the second argument.
            ServerInstance si = dscm.getServerInstance(DSConfigMgr.DEFAULT, LDAPUser.Type.AUTH_BASIC);
            String hostName = dscm.getHostName(DSConfigMgr.DEFAULT);
            if (si.getConnectionType() == Server.Type.CONN_SSL) {
                try {
                    ldapOptions.set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
                } catch (GeneralSecurityException e) {
                    debug.error("getConnection.JSSESocketFactory", e);
                    throw new LDAPServiceException(AuthI18n.authI18n.getString(IUMSConstants.DSCFG_JSSSFFAIL));
                }
            }
            if (dn != null && passwd != null) {
                // The 389 port number passed is overridden by the
                // hostName:port
                // constructed by the getHostName method. So, this is not
                // a hardcoded port number.
                host = hostName;
                port = 389;
            } else {
                // Throw LoginException
                throw new LoginException(AuthI18n.authI18n.getString(IUMSConstants.DSCFG_CONNECTFAIL));
            }
        } catch (LDAPServiceException ex) {
            debug.error("Authenticate failed: " + ex);
            throw new LoginException(ex.getMessage());
        }
    } else {
        try {
            if (debug.messageEnabled()) {
                debug.message("authenticate(): orgUrl= " + orgUrl);
            }
            // Get hostname
            int start;
            boolean useSSL = false;
            if (orgUrl.startsWith(LoginContext.LDAPS_AUTH_URL)) {
                start = LoginContext.LDAPS_AUTH_URL.length();
                useSSL = true;
            } else {
                start = LoginContext.LDAP_AUTH_URL.length();
            }
            int end = orgUrl.indexOf(':', start);
            if (end == -1) {
                end = orgUrl.indexOf('/', start);
                if (end == -1)
                    end = orgUrl.length();
            }
            String hostName = orgUrl.substring(start, end);
            // Get port number
            String portNumber = "389";
            start = end + 1;
            if (start < orgUrl.length()) {
                end = orgUrl.indexOf('/', start);
                if (end == -1)
                    end = orgUrl.length();
                portNumber = orgUrl.substring(start, end);
            }
            if (useSSL) {
                try {
                    ldapOptions.set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
                } catch (GeneralSecurityException e) {
                    debug.error("authentication().JSSESocketFactory()", e);
                    throw (new LoginException(e.getMessage()));
                }
            }
            if (debug.messageEnabled()) {
                debug.message("before connect(), hostName=" + hostName + ",port=" + portNumber);
            }
            host = hostName;
            port = Integer.parseInt(portNumber);
        } catch (Exception e) {
            debug.error("authentication", e);
            throw (new LoginException(e.getMessage()));
        }
    }
    try (ConnectionFactory factory = LDAPUtils.createFailoverConnectionFactory(host, port, dn, passwd, ldapOptions);
        Connection conn = factory.getConnection()) {
        return true;
    } catch (LdapException e) {
        throw new LoginException(e.getMessage());
    }
}
Also used : Options(org.forgerock.util.Options) GeneralSecurityException(java.security.GeneralSecurityException) Connection(org.forgerock.opendj.ldap.Connection) DSConfigMgr(com.iplanet.services.ldap.DSConfigMgr) LoginException(javax.security.auth.login.LoginException) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) LdapException(org.forgerock.opendj.ldap.LdapException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) LoginException(javax.security.auth.login.LoginException) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) ServerInstance(com.iplanet.services.ldap.ServerInstance) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder) LdapException(org.forgerock.opendj.ldap.LdapException)

Example 3 with ConnectionFactory

use of org.forgerock.opendj.ldap.ConnectionFactory in project OpenAM by OpenRock.

the class IdRepoUtils method tagSwapAndImportSchema.

private static void tagSwapAndImportSchema(String schemaFile, Map attrValues, ServletContext servletCtx, String idRepoType) throws Exception {
    DataInputStream dis = null;
    try (ConnectionFactory factory = getLDAPConnection(attrValues);
        Connection ld = factory.getConnection();
        InputStreamReader fin = new InputStreamReader(servletCtx.getResourceAsStream(schemaFile))) {
        StringBuilder sbuf = new StringBuilder();
        char[] cbuf = new char[1024];
        int len;
        while ((len = fin.read(cbuf)) > 0) {
            sbuf.append(cbuf, 0, len);
        }
        String schemaStr = sbuf.toString();
        String suffix = CollectionHelper.getMapAttr(attrValues, "sun-idrepo-ldapv3-config-organization_name");
        if (suffix != null) {
            schemaStr = StringUtils.strReplaceAll(schemaStr, "@userStoreRootSuffix@", suffix);
            String dbName = LDAPUtils.getDBName(suffix, ld);
            schemaStr = StringUtils.strReplaceAll(schemaStr, "@DB_NAME@", dbName);
        }
        if (idRepoType.equals(LDAPv3ForADAM)) {
            String adamInstanceGUID = getADAMInstanceGUID(attrValues);
            if (adamInstanceGUID != null) {
                schemaStr = StringUtils.strReplaceAll(schemaStr, "@INSTANCE_GUID@", adamInstanceGUID);
            }
        }
        schemaStr = ServicesDefaultValues.tagSwap(schemaStr);
        dis = new DataInputStream(new ByteArrayInputStream(schemaStr.getBytes()));
        LdifUtils.createSchemaFromLDIF(dis, ld);
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (Exception ex) {
            //No handling requried
            }
        }
    }
}
Also used : ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) Connection(org.forgerock.opendj.ldap.Connection) DataInputStream(java.io.DataInputStream) IdRepoException(com.sun.identity.idm.IdRepoException) ServerEntryNotFoundException(com.iplanet.services.naming.ServerEntryNotFoundException) SMSException(com.sun.identity.sm.SMSException) SSOException(com.iplanet.sso.SSOException)

Example 4 with ConnectionFactory

use of org.forgerock.opendj.ldap.ConnectionFactory in project OpenAM by OpenRock.

the class LDAPUtils method createFailoverConnectionFactory.

/**
     * Creates a ConnectionFactory from the host string and associated details. The host string can be any of the
     * following:
     * <ul>
     *     <li>A plain hostname/IP address</li>
     *     <li>A hostname and port, in the format <code>[host]:[port]</code></li>
     *     <li>A space-separated list of hostnames in priority order, e.g. <code>host1 host2 host3</code></li>
     *     <li>
     *         A space-separated list of hostnames with port numbers in priority order, e.g.
     *         <code>host1:389 host2:50389</code>
     *     </li>
     * </ul>
     * If a list of hosts is given, a load balanced {@code ConnectionFactory} is returned. All factories are
     * pre-authenticated using the supplied credentials.
     * @param host The host/host-port string.
     * @param defaultPort The port number to use for hosts that do not specify a port in the string.
     * @param authDN The DN to bind with.
     * @param authPasswd The password to bind with.
     * @param options Any additional options.
     * @return A connection factory.
     */
public static ConnectionFactory createFailoverConnectionFactory(String host, int defaultPort, String authDN, String authPasswd, Options options) {
    StringTokenizer st = new StringTokenizer(host);
    String[] hostList = new String[st.countTokens()];
    int[] portList = new int[st.countTokens()];
    int hostCount = 0;
    while (st.hasMoreTokens()) {
        String s = st.nextToken();
        int colon = s.indexOf(':');
        if (colon > 0) {
            hostList[hostCount] = s.substring(0, colon);
            portList[hostCount] = Integer.parseInt(s.substring(colon + 1));
        } else {
            hostList[hostCount] = s;
            portList[hostCount] = defaultPort;
        }
        hostCount++;
    }
    if (hostCount > 1) {
        List<ConnectionFactory> factories = new ArrayList<>();
        for (int i = 0; i < hostCount; i++) {
            factories.add(createSingleHostConnectionFactory(hostList[i], portList[i], authDN, authPasswd, options));
        }
        return Connections.newFailoverLoadBalancer(factories, options);
    } else {
        return createSingleHostConnectionFactory(hostList[0], portList[0], authDN, authPasswd, options);
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) ArrayList(java.util.ArrayList) ByteString(org.forgerock.opendj.ldap.ByteString)

Example 5 with ConnectionFactory

use of org.forgerock.opendj.ldap.ConnectionFactory in project OpenAM by OpenRock.

the class LDAPUtils method newFailoverConnectionPool.

/**
     * Creates a new connection pool that is capable to failover to the servers defined in case there is an error.
     *
     * @param servers The set of LDAP URLs that will be used to set up the connection factory.
     * @param username The directory user's DN. May be null if this is an anonymous connection.
     * @param password The directory user's password.
     * @param maxSize The max size of the created pool.
     * @param heartBeatInterval The interval for sending out heartbeat requests.
     * @param heartBeatTimeUnit The timeunit for the heartbeat interval.
     * @param ldapOptions Additional LDAP settings used to create the pool
     * @return A failover loadbalanced authenticated/anonymous connection pool, which may also send heartbeat requests.
     */
public static ConnectionFactory newFailoverConnectionPool(Set<LDAPURL> servers, String username, char[] password, int maxSize, int heartBeatInterval, String heartBeatTimeUnit, Options ldapOptions) {
    List<ConnectionFactory> factories = new ArrayList<ConnectionFactory>(servers.size());
    for (LDAPURL ldapurl : servers) {
        ConnectionFactory cf = Connections.newFixedConnectionPool(newConnectionFactory(ldapurl, username, password, heartBeatInterval, heartBeatTimeUnit, ldapOptions), maxSize);
        factories.add(cf);
    }
    return loadBalanceFactories(factories);
}
Also used : ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) ArrayList(java.util.ArrayList)

Aggregations

ConnectionFactory (org.forgerock.opendj.ldap.ConnectionFactory)14 LDAPConnectionFactory (org.forgerock.opendj.ldap.LDAPConnectionFactory)12 Connection (org.forgerock.opendj.ldap.Connection)6 SSLContextBuilder (org.forgerock.opendj.ldap.SSLContextBuilder)5 Options (org.forgerock.util.Options)5 DSConfigMgr (com.iplanet.services.ldap.DSConfigMgr)4 LDAPServiceException (com.iplanet.services.ldap.LDAPServiceException)4 ByteString (org.forgerock.opendj.ldap.ByteString)4 ArrayList (java.util.ArrayList)3 LdapException (org.forgerock.opendj.ldap.LdapException)3 ShutdownListener (org.forgerock.util.thread.listener.ShutdownListener)3 Duration (org.forgerock.util.time.Duration)3 ServerGroup (com.iplanet.services.ldap.ServerGroup)2 ServerInstance (com.iplanet.services.ldap.ServerInstance)2 SMSException (com.sun.identity.sm.SMSException)2 IOException (java.io.IOException)2 GeneralSecurityException (java.security.GeneralSecurityException)2 StringTokenizer (java.util.StringTokenizer)2 ShutdownManager (org.forgerock.util.thread.listener.ShutdownManager)2 SystemProperties (com.iplanet.am.util.SystemProperties)1