Example usage for javax.naming NamingEnumeration next

List of usage examples for javax.naming NamingEnumeration next

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration next.

Prototype

public T next() throws NamingException;

Source Link

Document

Retrieves the next element in the enumeration.

Usage

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected ArrayList<String> getRoles(DirContext context, String dn, String username, ArrayList<String> list)
        throws NamingException {
    if (list == null) {
        list = new ArrayList<String>();
    }//  ww w  .j av a2 s .c om
    if (roleName == null || "".equals(roleName)) {
        return list;
    }
    String filter = roleSearchMatchingFormat.format(new String[] { doRFC2254Encoding(dn), username });

    SearchControls constraints = new SearchControls();
    if (roleSearchSubtreeBool) {
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    } else {
        constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    }
    NamingEnumeration results = context.search(roleBase, filter, constraints);
    while (results.hasMore()) {
        SearchResult result = (SearchResult) results.next();
        Attributes attrs = result.getAttributes();
        if (attrs == null) {
            continue;
        }
        list = addAttributeValues(roleName, attrs, list);
    }
    return list;
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

private boolean addLDAPSearchResult(List<User> users, NamingEnumeration<SearchResult> results)
        throws NamingException {
    boolean somethingAdded = false;
    while (results != null && results.hasMore()) {
        // Display an entry
        SearchResult entry = results.next();
        User user = processEntry(entry);
        if (user != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Success reading from LDAP: {0}, {1} <{2}>", user.getUserId(),
                        user.getDisplayName(), user.getEmail()));
            }//w w  w. j  a  v  a2s.  c o m
            users.add(user);
            somethingAdded = true;
        }
    }
    return somethingAdded;
}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

public boolean authenticateUser(String userLogin, UserEdit edit, String password) {
    Hashtable env = new Hashtable();
    InitialDirContext ctx;//w w w .j  av  a 2  s .c o m

    String INIT_CTX = "com.sun.jndi.ldap.LdapCtxFactory";
    String MY_HOST = getLdapHost() + ":" + getLdapPort();
    String cn;
    boolean returnVal = false;

    if (!password.equals("")) {

        env.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
        env.put(Context.PROVIDER_URL, MY_HOST);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_CREDENTIALS, "secret");

        String[] returnAttribute = { "ou" };
        SearchControls srchControls = new SearchControls();
        srchControls.setReturningAttributes(returnAttribute);
        srchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(userLogin) + "))";

        try {
            ctx = new InitialDirContext(env);
            NamingEnumeration answer = ctx.search(getBasePath(), searchFilter, srchControls);
            String trobat = "false";

            while (answer.hasMore() && trobat.equals("false")) {

                SearchResult sr = (SearchResult) answer.next();
                String dn = sr.getName().toString() + "," + getBasePath();

                // Second binding
                Hashtable authEnv = new Hashtable();
                try {
                    authEnv.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
                    authEnv.put(Context.PROVIDER_URL, MY_HOST);
                    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
                    authEnv.put(Context.SECURITY_PRINCIPAL, sr.getName() + "," + getBasePath());
                    authEnv.put(Context.SECURITY_CREDENTIALS, password);
                    try {
                        DirContext authContext = new InitialDirContext(authEnv);
                        returnVal = true;
                        trobat = "true";
                        authContext.close();
                    } catch (AuthenticationException ae) {
                        M_log.info("Access forbidden");
                    }

                } catch (NamingException namEx) {
                    M_log.info("User doesn't exist");
                    returnVal = false;
                    namEx.printStackTrace();
                }
            }
            if (trobat.equals("false"))
                returnVal = false;

        } catch (NamingException namEx) {
            namEx.printStackTrace();
            returnVal = false;
        }
    }
    return returnVal;
}

From source file:org.pegadi.server.user.LDAPUserServerImpl.java

/**
 * Returns an array of users./*from www.j  a  va2s . com*/
 *
 * @param inactive <code>true</code> if inactive users should be included.
 * @return an array of <code>User</code>s.
 */
public List<Person> getAllUsers(boolean inactive) {
    ArrayList<Person> users = new ArrayList<Person>();
    try {
        SearchControls sc = new SearchControls();
        String[] getThese = { "sn", "gn", "mail", "uid", "employeeNumber" };
        sc.setReturningAttributes(getThese);
        if (inactive) {
            Attributes attrs = ctx.getAttributes("ou=people", getThese);
            users.add(this.createUser(attrs));
        } else {
            NamingEnumeration e = ctx.search("ou=people", "(active=1)", sc);
            while (e.hasMore()) {
                SearchResult sr = (SearchResult) e.next();
                users.add(this.createUser(sr.getAttributes()));
            }
        }
        Collections.sort(users);
        return users;
    } catch (NamingException er) {
        log.error("Could not get users", er);
    } catch (Exception e) {
        log.error("Something else", e);
    }
    return null;
}

From source file:org.pegadi.server.user.LDAPUserServerImpl.java

/**
 * Find a user by ID.  This id may be a compound ID, like the
 * LDAP database's DN structure. Otherwise it might be an empoyeeNumber
 * like this implementation use.//from w w  w  .jav  a2s . c  o m
 * <p/>
 * Tries first to get the user by pegadiID, which is the old method.
 *
 * @param id
 * @return the Userobject if found, or null if not.
 */
public Person getUserById(String id) {
    if (id == null || id.equals(0))
        return null;
    Person user = null;
    String[] getThese = { "sn", "gn", "mail", "uid", "employeeNumber" };
    try {
        //int nr = Integer.parseInt(id); //only needed if we can get the dn.
        SearchControls sc = new SearchControls();
        sc.setReturningAttributes(getThese);
        NamingEnumeration e = ctx.search("ou=people", "employeeNumber=" + id, sc);
        if (e.hasMore()) {
            SearchResult sr = (SearchResult) e.next();
            user = this.createUser(sr.getAttributes());
        }
    } catch (NamingException e) {
        log.error("An error occured while trying to getUserById(" + id + ")", e);
        /*FIXME does not work.
         * try {
                
        Attributes attrs = ctx.getAttributes("dn=" + id,getThese);
        return createUser(attrs);
                
        } catch (NamingException e) {
        e.printStackTrace();
        }*/
    }
    return user;
}

From source file:com.openkm.principal.LdapPrincipalAdapter.java

@SuppressWarnings("unchecked")
private List<String> ldapSearch(List<String> searchBases, String searchFilter, String attribute) {
    log.debug("ldapSearch({}, {}, {})", new Object[] { searchBases, searchFilter, attribute });
    List<String> al = new ArrayList<String>();
    DirContext ctx = null;/*from ww  w  . ja v a 2 s  . c  om*/
    Hashtable<String, String> env = getEnvironment();

    try {
        ctx = new InitialDirContext(env);
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        for (String searchBase : searchBases) {
            NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchCtls);

            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                Attributes attributes = searchResult.getAttributes();

                if (attribute.equals("")) {
                    StringBuilder sb = new StringBuilder();

                    for (NamingEnumeration<?> ne = attributes.getAll(); ne.hasMore();) {
                        Attribute attr = (Attribute) ne.nextElement();
                        sb.append(attr.toString());
                        sb.append("\n");
                    }

                    al.add(sb.toString());
                } else {
                    Attribute attrib = attributes.get(attribute);

                    if (attrib != null) {
                        // Handle multi-value attributes
                        for (NamingEnumeration<?> ne = attrib.getAll(); ne.hasMore();) {
                            String value = (String) ne.nextElement();

                            // If FQDN get only main part
                            if (value.startsWith("CN=") || value.startsWith("cn=")) {
                                String cn = value.substring(3, value.indexOf(','));
                                log.debug("FQDN: {}, CN: {}", value, cn);
                                al.add(cn);
                            } else {
                                al.add(value);
                            }
                        }
                    }
                }
            }
        }
    } catch (ReferralException e) {
        log.error("ReferralException: {}", e.getMessage());
        log.error("ReferralInfo: {}", e.getReferralInfo());
        log.error("ResolvedObj: {}", e.getResolvedObj());

        try {
            log.error("ReferralContext: {}", e.getReferralContext());
        } catch (NamingException e1) {
            log.error("NamingException logging context: {}", e1.getMessage());
        }
    } catch (NamingException e) {
        log.error("NamingException: {} (Base: {} - Filter: {} - Attribute: {})",
                new Object[] { e.getMessage(), searchBases, searchFilter, attribute });
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException e) {
            log.error("NamingException closing context: {}", e.getMessage());
        }
    }

    log.debug("ldapSearch: {}", al);
    return al;
}

From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java

private MetricValue getMetric(Metric metric, String tree, String attr)
        throws MetricNotFoundException, NamingException {
    NamingEnumeration enumer = null;
    try {// w  w  w.jav a2 s  . c  o m
        String[] a = { attr };
        SearchControls cons = new SearchControls();
        cons.setSearchScope(SearchControls.OBJECT_SCOPE);
        cons.setReturningAttributes(a);
        enumer = getDirContext(metric.getProperties()).search(tree, "(&(objectClass=*))", cons);
        while (enumer.hasMore()) {
            SearchResult searchresult = (SearchResult) enumer.next();
            Attributes attrs = searchresult.getAttributes();
            Attribute val;
            if (null != (val = attrs.get(attr))) {
                return new MetricValue(new Double(val.get().toString()), System.currentTimeMillis());
            }
        }
        throw new MetricNotFoundException("");
    } finally {
        if (enumer != null) {
            enumer.close();
        }
    }
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Returns a HashMap <login name, TPersonBean> for all LDAP objects found in
 * the directory und the DN configured in the Genji server configuration.
 * //w  w  w .j  av a2s  .c  om
 * @return Map with <login name, TPersonBean>
 */
public static HashMap<String, TPersonBean> getAllLdapPersonsPaged(TSiteBean siteBean, String filter)
        throws Exception {
    if (filter == null || "".equals(filter) || "*".equals(filter)) {
        filter = siteBean.getLdapAttributeLoginName() + "=*";
    }
    if (!(filter.startsWith("(") && filter.endsWith(")"))) {
        filter = "(" + filter + ")";
    }
    LOGGER.debug("User filter expression " + filter);
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    HashMap<String, TPersonBean> ldapPersonsMap = new HashMap<String, TPersonBean>();
    LdapContext context = getInitialContext(siteBean.getLdapServerURL(), bindDN, bindPassword);
    if (context == null) {
        return ldapPersonsMap;
    }
    int recordCount = 0;
    // Create initial context
    // Control the search
    SearchControls ctls = null;
    try {
        // Activate paged results
        int pageSize = 5;
        byte[] cookie = null;
        context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;
        // Control the search
        ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers()
                + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle
                                                                                                                                                                     // anyways
        if (ldapMap == null || ldapMap.isEmpty()) {
            LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!");
            return null;
        }
        String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME);
        String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME);
        String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL);
        String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE);
        String loginAttributeName = siteBean.getLdapAttributeLoginName();
        do {
            /* perform the search */
            NamingEnumeration<SearchResult> results = context.search("", filter, ctls);
            /* for each entry print out name + all attrs and values */
            while (results != null && results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                // Attributes atrs = sr.getAttributes();
                TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName,
                        lastNameAttributName, emailAttributeName, phoneAttributName);
                if (personBean != null) {
                    ldapPersonsMap.put(personBean.getLoginName(), personBean);
                }
                ++recordCount;
            }
            // Examine the paged results control response
            Control[] controls = context.getResponseControls();
            if (controls != null) {
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i] instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                        total = prrc.getResultSize();
                        if (total != 0) {
                            LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total
                                    + ") *****************\n");
                        } else {
                            LOGGER.debug(
                                    "***************** END-OF-PAGE " + "(total: unknown) ***************\n");
                        }
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                LOGGER.debug("No controls were sent from the server");
            }
            // Re-activate paged results
            context.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

        } while (cookie != null);
    } catch (SizeLimitExceededException sle) {
        if (recordCount < ctls.getCountLimit()) {
            LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server.");
            LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with "
                    + sle.getMessage());
            LOGGER.error(
                    "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter.");
        } else {
            LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server ("
                    + recordCount + ").");
            LOGGER.error(
                    "You have to get more user licenses for Genji or specify a more suitable search base or filter.");
        }
        LOGGER.error("The LDAP synchronization is most likely incomplete.");
    } catch (NamingException e) {
        LOGGER.error("PagedSearch failed.");
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (IOException ie) {
        LOGGER.error("PagedSearch failed.");
        LOGGER.debug(ExceptionUtils.getStackTrace(ie));
    } finally {
        if (context != null) {
            context.close();
        }
    }
    return ldapPersonsMap;
}

From source file:org.wso2.carbon.connector.ldap.SearchEntry.java

@Override
public void connect(MessageContext messageContext) throws ConnectException {
    String objectClass = (String) getParameter(messageContext, LDAPConstants.OBJECT_CLASS);
    String filter = (String) getParameter(messageContext, LDAPConstants.FILTERS);
    String dn = (String) getParameter(messageContext, LDAPConstants.DN);
    String returnAttributes[] = ((String) getParameter(messageContext, LDAPConstants.ATTRIBUTES)).split(",");
    boolean onlyOneReference = Boolean
            .valueOf((String) getParameter(messageContext, LDAPConstants.ONLY_ONE_REFERENCE));

    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace(LDAPConstants.CONNECTOR_NAMESPACE, LDAPConstants.NAMESPACE);
    OMElement result = factory.createOMElement(LDAPConstants.RESULT, ns);

    try {//  w ww . ja  v  a  2 s  .  c  om
        DirContext context = LDAPUtils.getDirectoryContext(messageContext);

        String attrFilter = generateAttrFilter(filter);
        String searchFilter = generateSearchFilter(objectClass, attrFilter);
        NamingEnumeration<SearchResult> results = null;
        try {
            results = searchInUserBase(dn, searchFilter, returnAttributes, SearchControls.SUBTREE_SCOPE,
                    context);
            SearchResult entityResult = null;

            if (!onlyOneReference) {
                if (results != null && results.hasMore()) {
                    while (results.hasMore()) {
                        entityResult = results.next();
                        result.addChild(prepareNode(entityResult, factory, ns, returnAttributes));
                    }
                }
            } else {
                entityResult = makeSureOnlyOneMatch(results);
                if (entityResult == null)
                    throw new NamingException(
                            "Multiple objects for the searched target have been found. Try to "
                                    + "change onlyOneReference option");
                result.addChild(prepareNode(entityResult, factory, ns, returnAttributes));
            }

            LDAPUtils.preparePayload(messageContext, result);

            if (context != null) {
                context.close();
            }

        } catch (NamingException e) { //LDAP Errors are catched
            LDAPUtils.handleErrorResponse(messageContext, LDAPConstants.ErrorConstants.SEARCH_ERROR, e);
            throw new SynapseException(e);
        }

    } catch (NamingException e) { //Authentication failures are catched
        LDAPUtils.handleErrorResponse(messageContext, LDAPConstants.ErrorConstants.INVALID_LDAP_CREDENTIALS, e);
        throw new SynapseException(e);
    }
}

From source file:com.konakart.bl.LDAPMgrCore.java

/**
 * Called if the LDAP module is installed and active. This method should return:
 * <ul>// w ww  .  j  av a  2s.c o m
 * <li>A negative number in order for the login attempt to fail. The KonaKart login() method
 * will return a null sessionId</li>
 * <li>Zero to signal that this method is not implemented. The KonaKart login() method will
 * perform the credential check.</li>
 * <li>A positive number for the login attempt to pass. The KonaKart login() will not check
 * credentials, and will log in the customer, returning a valid session id.</li>
 * </ul>
 * This method may need to be modified slightly depending on the structure of your LDAP. The
 * example works when importing the exampleData.ldif file in the LDAP module jar:
 * 
 * dn: cn=Robert Smith,ou=people,dc=example,dc=com<br/>
 * objectclass: inetOrgPerson<br/>
 * cn: Robert Smith<br/>
 * cn: Robert J Smith<br/>
 * cn: bob smith<br/>
 * sn: smith<br/>
 * uid: rjsmith<br/>
 * userpassword: rJsmitH<br/>
 * carlicense: HISCAR 123<br/>
 * homephone: 555-111-2222<br/>
 * mail: r.smith@example.com<br/>
 * mail: rsmith@example.com<br/>
 * mail: bob.smith@example.com<br/>
 * description: swell guy<br/>
 * 
 * The code attempts to connect to LDAP using the username, password and URL in the
 * configuration variables set when the module was installed through the admin app.<br/>
 * 
 * After having connected, the person object is searched for using the email address of the
 * user. If found we use the "cn" attribute and the password of the user to attempt to bind to
 * LDAP. If the bind is successful, we return a positive number which means that authentication
 * was successful.
 * 
 * @param emailAddr
 *            The user name required to log in
 * @param password
 *            The log in password
 * @return Returns an integer
 * @throws Exception
 */
public int checkCredentials(String emailAddr, String password) throws Exception {
    DirContext ctx = null;

    try {
        Hashtable<String, String> environment = new Hashtable<String, String>();

        if (log.isDebugEnabled()) {
            log.debug("LDAP connection URL                          =   " + url);
            log.debug("LDAP user name                               =   " + ldapUserName);
            log.debug("LDAP person object distinguished name (DN)   =   " + personDN);
        }

        if (ldapUserName == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_USER_NAME configuration variable hasn't been set.");
        }
        if (ldapPassword == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_PASSWORD configuration variable hasn't been set.");
        }
        if (url == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_URL configuration variable hasn't been set.");
        }
        if (personDN == null) {
            throw new KKException(
                    "Cannot validate through LDAP because the MODULE_OTHER_LDAP_PERSON_DN (Distinguished Name of Person Object) configuration variable hasn't been set.");
        }

        environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.PROVIDER_URL, url);
        environment.put(Context.SECURITY_PRINCIPAL, ldapUserName);
        environment.put(Context.SECURITY_CREDENTIALS, ldapPassword);

        /*
         * connect to LDAP using the credentials and connection string from the configuration
         * variables
         */
        try {
            ctx = new InitialDirContext(environment);
        } catch (Exception e) {
            log.error("Cannot connect to LDAP", e);
            return -1;
        }

        /* Specify the search filter on the eMail address */
        String filter = "(mail=" + emailAddr + ")";

        /*
         * limit returned attributes to those we care about. In this case we only require the
         * "cn" attribute which we will use to attempt to bind the user in order to validate his
         * password
         */
        String[] attrIDs = { "cn" };
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(attrIDs);
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        /* Search for objects using filter and controls */
        NamingEnumeration<SearchResult> answer = ctx.search(personDN, filter, ctls);

        /* close the connection */
        ctx.close();

        if (answer == null || !answer.hasMore()) {
            return -1;
        }

        SearchResult sr = answer.next();
        Attributes attrs = sr.getAttributes();
        String cn = attrs.get("cn").toString();
        if (log.isDebugEnabled()) {
            log.debug("cn of user with eMail (" + emailAddr + ") is " + cn);
        }

        /*
         * cn could be in the format "cn: Peter Smith, Pete Smith, Smithy" so we need to capture
         * just the first entry
         */
        if (cn != null) {
            if (cn.contains(",")) {
                cn = cn.split(",")[0];
                if (cn.contains(":")) {
                    cn = cn.split(":")[1];
                }
            } else if (cn.contains(":")) {
                cn = cn.split(":")[1];
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Cleaned cn of user with eMail (" + emailAddr + ") is " + cn);
        }

        /* Now we try to bind as the user */
        String userName = "cn=" + cn + "," + personDN;

        if (log.isDebugEnabled()) {
            log.debug("LDAP user name of user with eMail (" + emailAddr + ") is " + userName);
        }

        /* Bind as the user */
        environment.put(Context.SECURITY_PRINCIPAL, userName);
        environment.put(Context.SECURITY_CREDENTIALS, password);
        try {
            ctx = new InitialDirContext(environment);
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Could not bind user " + userName);
            }
            return -1;
        }
        ctx.close();
        if (log.isDebugEnabled()) {
            log.debug("user with eMail (" + emailAddr + ") was successfully authenticated using LDAP");
        }
        return 1;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.error("Received an exception while closing the LDAP DirContext", e);
            }
        }
    }
}