Example usage for javax.naming NamingEnumeration hasMore

List of usage examples for javax.naming NamingEnumeration hasMore

Introduction

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

Prototype

public boolean hasMore() throws NamingException;

Source Link

Document

Determines whether there are any more elements in the enumeration.

Usage

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 .  ja va 2 s .  co 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.dattack.naming.AbstractContext.java

@Override
public void destroySubcontext(final Name name) throws NamingException {

    if (name.size() > 1) {
        if (subContexts.containsKey(name.getPrefix(1))) {
            final Context subContext = subContexts.get(name.getPrefix(1));
            subContext.destroySubcontext(name.getSuffix(1));
            return;
        }/*from w ww. java  2  s  . com*/
        throw new NameNotFoundException();
    }

    if (objectTable.containsKey(name) || !subContexts.containsKey(name)) {
        throw new NameNotFoundException(String.format("Context not found: %s", name));
    }

    final Context subContext = subContexts.get(name);
    final NamingEnumeration<NameClassPair> names = subContext.list("");
    if (names.hasMore()) {
        throw new ContextNotEmptyException();
    }

    subContexts.get(name).close();
    subContexts.remove(name);
}

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.
 * //from  ww  w .  j  ava2  s  .  c  o m
 * @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.pegadi.server.user.LDAPUserServerImpl.java

/**
 * @param roleID the ID of a role/*  w  ww  .  ja  v  a 2  s. co m*/
 * @param user   the user
 * @return <code>true</code> if the user has that role.
 */
public boolean hasRole(int roleID, Person user) {
    String dn = this.getDN(user.getUsername());
    try {
        SearchControls sc = new SearchControls();
        NamingEnumeration e = ctx.search("ou=roles", "(&(roleID=" + roleID + ")(member=" + dn + "))", sc);
        if (e.hasMore())
            return true;

    } catch (NamingException er) {
        log.error("Error checking for role: " + roleID + "for user" + user.getUsername(), er);
    } catch (Exception e) {
        log.error("Something else", e);
    }
    return false;
}

From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java

/** Function to extract users from LDAP. */
private List<String> getUserList(JndiLdapRealm r, String searchText, int numUsersToFetch) {
    List<String> userList = new ArrayList<>();
    String userDnTemplate = r.getUserDnTemplate();
    String userDn[] = userDnTemplate.split(",", 2);
    String userDnPrefix = userDn[0].split("=")[0];
    String userDnSuffix = userDn[1];
    JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
    try {/*  ww w .  ja  v a2  s . c  o  m*/
        LdapContext ctx = cf.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setCountLimit(numUsersToFetch);
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userDnPrefix };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userDnPrefix) != null) {
                String currentUser = attrs.get(userDnPrefix).toString();
                userList.add(currentUser.split(":")[1].trim());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error retrieving User list from Ldap Realm", e);
    }
    LOGGER.info("UserList: " + userList);
    return userList;
}

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

protected boolean authenticate(String username) throws Exception {
    DirContext context = open();/* w  w  w. j a  va  2 s.com*/
    try {

        String filter = userSearchMatchingFormat.format(new String[] { username });
        SearchControls constraints = new SearchControls();
        if (userSearchSubtreeBool) {
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }

        // setup attributes
        String[] attribs;
        if (userRoleName == null) {
            attribs = new String[] {};
        } else {
            attribs = new String[] { userRoleName };
        }
        constraints.setReturningAttributes(attribs);

        NamingEnumeration results = context.search(userBase, filter, constraints);

        if (results == null || !results.hasMore()) {
            log.error("No roles associated with user " + username);
            loginSucceeded = false;
            throw new FailedLoginException();
        }

        SearchResult result = (SearchResult) results.next();

        if (results.hasMore()) {
            // ignore for now
        }
        NameParser parser = context.getNameParser("");
        Name contextName = parser.parse(context.getNameInNamespace());
        Name baseName = parser.parse(userBase);
        Name entryName = parser.parse(result.getName());
        Name name = contextName.addAll(baseName);
        name = name.addAll(entryName);
        String dn = name.toString();

        Attributes attrs = result.getAttributes();
        if (attrs == null) {
            return false;
        }
        ArrayList<String> roles = null;
        if (userRoleName != null) {
            roles = addAttributeValues(userRoleName, attrs, roles);
        }
        // check the credentials by binding to server
        // bindUser(context, dn);
        // if authenticated add more roles
        roles = getRoles(context, dn, username, roles);
        for (String role : roles) {
            groups.add(role);
        }
        if (groups.isEmpty()) {
            log.error("No roles associated with user " + username);
            loginSucceeded = false;
            throw new FailedLoginException();
        } else
            loginSucceeded = true;

    } catch (CommunicationException e) {
        close(context);
        throw (LoginException) new FailedLoginException().initCause(e);
    } catch (NamingException e) {
        close(context);
        throw (LoginException) new FailedLoginException().initCause(e);
    }
    return true;
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPTreeReference.java

/**
 * Fetches single parent, cutting the dn and trying to get the given entry.
 *
 * @see org.nuxeo.ecm.directory.Reference#getSourceIdsForTarget(String)
 *///w  w  w .  j a va  2 s . co  m
@Override
public List<String> getSourceIdsForTarget(String targetId) throws DirectoryException {
    Set<String> sourceIds = new TreeSet<>();
    String targetDn = null;

    // step #1: fetch the dn of the targetId entry in the target
    // directory by the static dn valued strategy
    LDAPDirectory targetDir = getTargetLDAPDirectory();
    try (LDAPSession targetSession = (LDAPSession) targetDir.getSession()) {
        SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId, true);
        if (targetLdapEntry == null) {
            // no parent accessible => return empty list
            return EMPTY_STRING_LIST;
        }
        targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace());
    } catch (NamingException e) {
        throw new DirectoryException("error fetching " + targetId, e);
    }

    // step #2: search for entries that reference parent dn in the
    // source directory and collect its id
    LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory();
    String parentDn = getParentDn(targetDn);
    String filterExpr = String.format("(&%s)", ldapSourceDirectory.getBaseFilter());
    String[] filterArgs = {};

    // get a copy of original search controls
    SearchControls sctls = ldapSourceDirectory.getSearchControls(true);
    sctls.setSearchScope(SearchControls.OBJECT_SCOPE);
    try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        if (log.isDebugEnabled()) {
            log.debug(String.format(
                    "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'"
                            + " filter='%s' args='%s' scope='%s' [%s]",
                    targetId, parentDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(),
                    this));
        }
        NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(parentDn, filterExpr,
                filterArgs, sctls);

        try {
            while (results.hasMore()) {
                Attributes attributes = results.next().getAttributes();
                // NXP-2461: check that id field is filled
                Attribute attr = attributes.get(sourceSession.idAttribute);
                if (attr != null) {
                    Object value = attr.get();
                    if (value != null) {
                        sourceIds.add(value.toString());
                        // only supposed to get one result anyway
                        break;
                    }
                }
            }
        } finally {
            results.close();
        }
    } catch (NamingException e) {
        throw new DirectoryException("error during reference search for " + targetDn, e);
    }

    return new ArrayList<>(sourceIds);
}

From source file:org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl.java

public List findAll() {
    DirContext ctx = createAnonymousContext();

    LinkedList list = new LinkedList();
    NamingEnumeration results = null;
    try {/*from  w  w  w . j a  va 2 s  .c  o m*/
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        results = ctx.search("", "(objectclass=person)", controls);

        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            String dn = searchResult.getName();
            Attributes attributes = searchResult.getAttributes();
            list.add(mapToPerson(dn, attributes));
        }
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
    return list;
}

From source file:org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl.java

public List getAllPersonNames() {
    DirContext ctx = createAnonymousContext();

    LinkedList list = new LinkedList();
    NamingEnumeration results = null;
    try {/* w  w  w .java2s .c o m*/
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        results = ctx.search("", "(objectclass=person)", controls);

        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            Attribute attr = attributes.get("cn");
            String cn = (String) attr.get();
            list.add(cn);
        }
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
    return list;
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPTreeReference.java

/**
 * Fetches children, onelevel or subtree given the reference configuration.
 * <p>//from   w  ww. j  ava2  s .co  m
 * Removes entries with same id than parent to only get real children.
 *
 * @see org.nuxeo.ecm.directory.Reference#getTargetIdsForSource(String)
 */
// TODO: optimize reusing the same ldap session (see LdapReference optim
// method)
@Override
public List<String> getTargetIdsForSource(String sourceId) throws DirectoryException {
    Set<String> targetIds = new TreeSet<>();
    String sourceDn = null;

    // step #1: fetch the dn of the sourceId entry in the source
    // directory by the static dn valued strategy
    LDAPDirectory sourceDir = getSourceLDAPDirectory();
    try (LDAPSession sourceSession = (LDAPSession) sourceDir.getSession()) {
        SearchResult sourceLdapEntry = sourceSession.getLdapEntry(sourceId, true);
        if (sourceLdapEntry == null) {
            throw new DirectoryException(sourceId + " does not exist in " + sourceDirectoryName);
        }
        sourceDn = pseudoNormalizeDn(sourceLdapEntry.getNameInNamespace());
    } catch (NamingException e) {
        throw new DirectoryException("error fetching " + sourceId, e);
    }

    // step #2: search for entries with sourceDn as base dn and collect
    // their ids
    LDAPDirectory ldapTargetDirectory = getTargetLDAPDirectory();

    String filterExpr = String.format("(&%s)", ldapTargetDirectory.getBaseFilter());
    String[] filterArgs = {};

    // get a copy of original search controls
    SearchControls sctls = ldapTargetDirectory.getSearchControls(true);
    sctls.setSearchScope(getScope());
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) {
        if (log.isDebugEnabled()) {
            log.debug(String.format(
                    "LDAPReference.getTargetIdsForSource(%s): LDAP search search base='%s'"
                            + " filter='%s' args='%s' scope='%s' [%s]",
                    sourceId, sourceDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(),
                    this));
        }
        NamingEnumeration<SearchResult> results = targetSession.dirContext.search(sourceDn, filterExpr,
                filterArgs, sctls);

        try {
            while (results.hasMore()) {
                Attributes attributes = results.next().getAttributes();
                // NXP-2461: check that id field is filled
                Attribute attr = attributes.get(targetSession.idAttribute);
                if (attr != null) {
                    Object value = attr.get();
                    if (value != null) {
                        // always remove self as child
                        String targetId = value.toString();
                        if (!sourceId.equals(targetId)) {
                            targetIds.add(targetId);
                        }
                    }
                }
            }
        } finally {
            results.close();
        }
    } catch (NamingException e) {
        throw new DirectoryException("error during reference search for " + sourceDn, e);
    }

    return new ArrayList<>(targetIds);
}