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:ru.runa.wfe.security.logic.LdapLogic.java

private int synchronizeActors(DirContext dirContext, Map<String, Actor> actorsByDistinguishedName)
        throws Exception {
    int changesCount = 0;
    List<Actor> existingActorsList = executorDao.getAllActors(BatchPresentationFactory.ACTORS.createNonPaged());
    Map<String, Actor> existingActorsMap = Maps.newHashMap();
    for (Actor actor : existingActorsList) {
        existingActorsMap.put(actor.getName().toLowerCase(), actor);
    }/*from  w  ww .j  a  va  2s . com*/
    Set<Actor> ldapActorsToDelete = Sets.newHashSet();
    if (LdapProperties.isSynchronizationDeleteExecutors()) {
        ldapActorsToDelete.addAll(executorDao.getGroupActors(importGroup));
    }
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    for (String ou : LdapProperties.getSynchronizationOrganizationUnits()) {
        List<SearchResult> resultList = Lists.newArrayList();
        try {
            NamingEnumeration<SearchResult> list = dirContext.search(ou, OBJECT_CLASS_USER_FILTER, controls);
            while (list.hasMore()) {
                SearchResult searchResult = list.next();
                resultList.add(searchResult);
            }
            list.close();
        } catch (SizeLimitExceededException e) {
            resultList.clear();
            for (String y : ALPHABETS) {
                NamingEnumeration<SearchResult> list = dirContext.search(ou,
                        MessageFormat.format(LOGIN_FIRST_LETTER_FILTER, ATTR_ACCOUNT_NAME, y, y.toLowerCase(),
                                OBJECT_CLASS_USER_FILTER),
                        controls);
                while (list.hasMore()) {
                    SearchResult searchResult = list.next();
                    resultList.add(searchResult);
                }
                list.close();
            }
        }
        for (SearchResult searchResult : resultList) {
            String name = getStringAttribute(searchResult, ATTR_ACCOUNT_NAME);
            String description = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserDescriptionAttribute());
            String fullName = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserFullNameAttribute());
            String email = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserEmailAttribute());
            String phone = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserPhoneAttribute());
            String title = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserTitleAttribute());
            String department = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserDepartmentAttribute());
            ToStringHelper toStringHelper = MoreObjects.toStringHelper("user info");
            toStringHelper.add("name", name).add("description", description).add("fullName", fullName)
                    .add("email", email);
            toStringHelper.add("phone", phone).add("title", title).add("department", department)
                    .omitNullValues();
            log.debug("Read " + toStringHelper.toString());
            Actor actor = existingActorsMap.get(name.toLowerCase());
            if (actor == null) {
                if (!LdapProperties.isSynchronizationCreateExecutors()) {
                    continue;
                }
                actor = new Actor(name, description, fullName, null, email, phone, title, department);
                log.info("Creating " + actor);
                executorDao.create(actor);
                executorDao.addExecutorsToGroup(Lists.newArrayList(actor), importGroup);
                permissionDao.setPermissions(importGroup, Lists.newArrayList(Permission.LIST), actor);
                changesCount++;
            } else {
                ldapActorsToDelete.remove(actor);
                if (LdapProperties.isSynchronizationUpdateExecutors()) {
                    List<IChange> changes = Lists.newArrayList();
                    if (isAttributeNeedsChange(description, actor.getDescription())) {
                        changes.add(new AttributeChange("description", actor.getDescription(), description));
                        actor.setDescription(description);
                    }
                    if (isAttributeNeedsChange(fullName, actor.getFullName())) {
                        changes.add(new AttributeChange("fullName", actor.getFullName(), fullName));
                        actor.setFullName(fullName);
                    }
                    if (isAttributeNeedsChange(email, actor.getEmail())) {
                        changes.add(new AttributeChange("email", actor.getEmail(), email));
                        actor.setEmail(email);
                    }
                    if (isAttributeNeedsChange(phone, actor.getPhone())) {
                        changes.add(new AttributeChange("phone", actor.getPhone(), phone));
                        actor.setPhone(phone);
                    }
                    if (isAttributeNeedsChange(title, actor.getTitle())) {
                        changes.add(new AttributeChange("title", actor.getTitle(), title));
                        actor.setTitle(title);
                    }
                    if (isAttributeNeedsChange(department, actor.getDepartment())) {
                        changes.add(new AttributeChange("department", actor.getDepartment(), department));
                        actor.setDepartment(department);
                    }
                    if (!actor.isActive()) {
                        if (LdapProperties.isSynchronizationUserStatusEnabled()) {
                            actor.setActive(true);
                            changes.add(new AttributeChange("active", "false", "true"));
                        }
                        if (executorDao.removeExecutorFromGroup(actor, wasteGroup)) {
                            changes.add(new Change("waste group removal"));
                        }
                        if (executorDao.addExecutorToGroup(actor, importGroup)) {
                            changes.add(new Change("import group addition"));
                        }
                    }
                    if (!changes.isEmpty()) {
                        executorDao.update(actor);
                        log.info("Updating " + actor + ": " + changes);
                        changesCount++;
                    }
                }
            }
            actorsByDistinguishedName.put(searchResult.getNameInNamespace(), actor);
        }
    }
    if (LdapProperties.isSynchronizationDeleteExecutors() && ldapActorsToDelete.size() > 0) {
        if (LdapProperties.isSynchronizationUserStatusEnabled()) {
            for (Actor actor : ldapActorsToDelete) {
                actor.setActive(false);
                executorDao.update(actor);
                log.info("Inactivating " + actor);
                changesCount++;
            }
        }
        executorDao.removeExecutorsFromGroup(ldapActorsToDelete, importGroup);
        executorDao.addExecutorsToGroup(ldapActorsToDelete, wasteGroup);
        changesCount += ldapActorsToDelete.size();
    }
    return changesCount;
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private List searchGroupMember(DirContext context, Map filters) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    Set userList = new HashSet();
    String filter = buildFilter(filters);
    if (log.isInfoEnabled())
        log.info("Search User from " + userBase + " by " + filter);
    NamingEnumeration searchResultEnum = context.search(this.groupBase, filter, searchControls);

    while (searchResultEnum.hasMore()) {
        SearchResult searchResult = (SearchResult) searchResultEnum.next();
        Attributes attrs = searchResult.getAttributes();
        String dn = searchResult.getName() + "," + groupBase;
        String uniquememberAttrName = "uniqueMember";
        if (this.propAttrMap.containsKey("org_member")) {
            try {
                uniquememberAttrName = (String) this.propAttrMap.get("org_member");
            } catch (Exception ex) {
                //ignore
            }//from  w w w.j ava2s .c o  m
        }
        Attribute uniquememberAttr = attrs.get(uniquememberAttrName);
        if (uniquememberAttr == null)
            continue;
        NamingEnumeration memberDNs = uniquememberAttr.getAll();
        while (memberDNs.hasMoreElements()) {
            //System.out.println(memberDNs[j]);
            userList.add(memberDNs.next());//DN of user
        }
    }

    List members = new ArrayList();

    for (Iterator userDns = userList.iterator(); userDns.hasNext();) {

        /* Next directory entry */
        String userDn = (String) userDns.next();
        Attributes userEntry = null;
        try {
            userEntry = context.getAttributes(userDn);//DN of user
        } catch (Exception e) {
            log.error(userDn + ": " + e.getMessage());
        }
        if (userEntry == null)
            continue;

        LDAPAccount user = createLDAPUser(userDn, userEntry);
        if (user.getUid() == null)
            continue;

        members.add(user);

    }

    return members;

}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * //from w ww .ja  va 2s .c om
 * @see edu.internet2.middleware.subject.provider.BaseSourceAdapter#search(java.lang.String)
 */
@Override
public Set<Subject> search(String searchValue) {
    Set<Subject> result = new HashSet<Subject>();
    Search search = getSearch("search");
    if (search == null) {
        log.error("searchType: \"search\" not defined.");
        return result;
    }
    String[] attributeNames = { this.nameAttributeName, this.subjectIDAttributeName,
            this.descriptionAttributeName };
    NamingEnumeration ldapResults = getLdapResults(search, searchValue, attributeNames);
    if (ldapResults == null) {
        return result;
    }
    try {
        while (ldapResults.hasMore()) {
            SearchResult si = (SearchResult) ldapResults.next();
            Attributes attributes1 = si.getAttributes();
            Subject subject = createSubject(attributes1);
            result.add(subject);
        }
    } catch (NamingException ex) {
        log.error("LDAP Naming Except: " + ex.getMessage(), ex);
    }

    return result;
}

From source file:org.pentaho.platform.plugin.services.security.userrole.ldap.search.GenericLdapSearch.java

public List search(final Object[] filterArgs) {
    Object[] transformedArgs = filterArgs;
    // transform the filterArgs
    if (null != filterArgsTransformer) {
        transformedArgs = (Object[]) filterArgsTransformer.transform(filterArgs);
    }//from  w ww.j av  a2s  .  co  m
    LdapSearchParams params = paramsFactory.createParams(transformedArgs);
    // use a set internally to store intermediate results
    Set results = new HashSet();
    NamingEnumeration matches = null;
    try {
        matches = contextSource.getReadOnlyContext().search(params.getBase(), params.getFilter(),
                params.getFilterArgs(), params.getSearchControls());
    } catch (NamingException e1) {
        if (GenericLdapSearch.logger.isErrorEnabled()) {
            // TODO: Throw an exception here
            GenericLdapSearch.logger.error("Directory search failed", e1); //$NON-NLS-1$
        }
        return new ArrayList(results);
    }
    try {
        while (matches.hasMore()) {
            SearchResult result = (SearchResult) matches.next();
            if (null != resultsTransformer) {
                results.addAll((Collection) resultsTransformer.transform(result));
            } else {
                results.add(result);
            }
        }
    } catch (NamingException e) {
        if (GenericLdapSearch.logger.isErrorEnabled()) {
            // TODO: Throw an exception here
            GenericLdapSearch.logger.error("Enumerating directory search results failed", e); //$NON-NLS-1$
        }
    }
    return new ArrayList(results);
}

From source file:ldap.SearchUtility.java

public boolean userHasAttribute(String DN, String attrType, String attrValue, DirContext context)
        throws NamingException {
    Attributes atts = new BasicAttributes();
    atts.put(attrType, attrValue);//  ww  w.jav a2  s. c o m
    NamingEnumeration<SearchResult> userResults = context.search(new LdapName(DN), "(" + attrType + "={0})",
            new String[] { attrValue }, getSearchControls());
    return (userResults.hasMore());
}

From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java

/**
 * Check if organizational unit is created in tenant.
 *
 * @param orgName           Organization name.
 * @param initialDirContext The directory connection.
 * @throws UserStoreException If an error occurred while searching.
 *//*from w  ww  . j  a  v  a2s .  co  m*/
protected boolean isOrganizationalUnitCreated(String orgName, DirContext initialDirContext)
        throws UserStoreException {

    //construct search filter,eg. (&(objectClass=organizationalUnit)(ou=wso2.com))
    String partitionDN = tenantMgtConfig.getTenantStoreProperties()
            .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ROOT_PARTITION);
    String organizationalObjectClass = tenantMgtConfig.getTenantStoreProperties()
            .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORGANIZATIONAL_OBJECT_CLASS);
    String organizationalAttribute = tenantMgtConfig.getTenantStoreProperties()
            .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORGANIZATIONAL_ATTRIBUTE);
    String searchFilter = "(&(objectClass=" + organizationalObjectClass + ")(" + organizationalAttribute + "="
            + orgName + "))";

    SearchControls userSearchControl = new SearchControls();
    userSearchControl.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    NamingEnumeration<SearchResult> userSearchResults = null;

    try {
        userSearchResults = initialDirContext.search(partitionDN, searchFilter, userSearchControl);
        return userSearchResults.hasMore();
    } catch (NamingException e) {
        String errorMessage = "Error occurred while searching in root partition for organization : " + orgName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

/**
* Tries to find the value of the given attribute. Note that this method
* only uses the first search result./*from  ww  w.  j av a  2 s  . com*/
* 
* @param username
*            a username
* @param attrName
*            the name of the attribute to find
* @return the value of the attribute, or an empty string
*/
public String getAttr(String username, String attrName) {
    String val = "";
    try {
        DirContext dc = new InitialDirContext(env);
        NamingEnumeration<SearchResult> ne = performLdapSearch(username, dc);

        if (ne.hasMore()) {
            val = getAttrValue(attrName, ne.next());
        }

        ne.close();
        dc.close();
    } catch (NamingException ne) {
        log.warn("Failed LDAP lookup getAttr", ne);
        log.warn("username:", username);
        log.warn("attrName:", attrName);
    }

    log.trace(String.format("getAttr search result: %s", val));
    return val;
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

private String performRoleSearch(String location, String roleName) {
    String val = null;
    try {/*from   w w w.  j  a  v a  2  s .c  om*/

        DirContext dc = new InitialDirContext(env);
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);

        //String filter = "(" + filterPrefix + roleName + ")";
        NamingEnumeration<SearchResult> ne = dc.search(location, roleName, sc);
        if (ne.hasMore()) {
            val = getAttrValue("memberOf", ne.next());
        }
        ne.close();
        dc.close();
    } catch (NamingException ne) {
        log.warn("Failed LDAP lookup getAttr", ne);
        log.warn("roleName:", roleName);
        log.warn("location:", location);
    }
    return val;

}

From source file:org.tolven.gatekeeper.bean.LdapBean.java

private List<TolvenPerson> findTolvenPerson(LdapContext ctx, String peopleBaseName, String principalLdapName,
        String realm, int maxResults, int timeLimit) {
    NamingEnumeration<SearchResult> namingEnum = null;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setCountLimit(maxResults);/*from  w w w.  j a  v a2  s . c  om*/
    ctls.setTimeLimit(timeLimit);
    ArrayList<TolvenPerson> searchResults = new ArrayList<TolvenPerson>(10);
    try {
        namingEnum = ctx.search(peopleBaseName, principalLdapName, ctls);
        while (namingEnum.hasMore()) {
            SearchResult rslt = namingEnum.next();
            searchResults.add(new TolvenPerson(rslt));
        }
    } catch (GatekeeperSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RuntimeException(
                "Could not search for TolvenPerson: " + principalLdapName + " in realm: " + realm + ": ", ex);
    }
    return searchResults;
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

/**
 * Tries to find the value(s) of the given attribute. Note that this method
 * uses all search results.//from  w ww  . j a  va  2 s  .co  m
 * 
 * @param username
 *            a username
 * @param attrName
 *            the name of the attribute to find
 * @return a list of values for the attribute, or an empty list
 */
public List<String> getAllAttrs(String username, String attrName) {
    List<String> resultList = new ArrayList<String>();

    try {
        DirContext dc = new InitialDirContext(env);
        NamingEnumeration<SearchResult> ne = performLdapSearch(username, dc);

        while (ne.hasMore()) {
            resultList.add(getAttrValue(attrName, ne.next()));
        }

        ne.close();
        dc.close();
    } catch (NamingException ne) {
        log.warn("Failed LDAP lookup getAllAttrs" + username, ne);
    }

    log.trace("getAllAttrs search result: " + resultList);
    if (log.isTraceEnabled()) {
        log.trace("getAllAttrs search result: " + resultList);
    }

    return resultList;
}