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.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl.java

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

    LinkedList list = new LinkedList();
    NamingEnumeration results = null;
    try {/*from   w  w w .  ja va  2s.  co 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.springframework.ldap.demo.dao.PersonDaoImpl.java

public List<Person> findAll() {
    DirContext ctx = createAnonymousContext();

    LinkedList<Person> list = new LinkedList<Person>();
    NamingEnumeration<?> results = null;
    try {//from  w  ww  .  j  a  v  a 2s  . co 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.demo.dao.PersonDaoImpl.java

public List<String> getAllPersonNames() {
    DirContext ctx = createAnonymousContext();

    LinkedList<String> list = new LinkedList<String>();
    NamingEnumeration<?> results = null;
    try {/*from   w ww  .  j  ava 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();
            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.craftercms.studio.impl.v1.service.security.DbWithLdapExtensionSecurityProvider.java

@Override
public String authenticate(String username, String password)
        throws BadCredentialsException, AuthenticationSystemException {

    // Mapper for user data if user is successfully authenticated
    AuthenticatedLdapEntryContextMapper<User> mapper = new AuthenticatedLdapEntryContextMapper<User>() {
        @Override//from   w w  w  .jav  a2  s .c o m
        public User mapWithContext(DirContext dirContext, LdapEntryIdentification ldapEntryIdentification) {
            try {
                // User entry - extract attributes
                DirContextOperations dirContextOperations = (DirContextOperations) dirContext
                        .lookup(ldapEntryIdentification.getRelativeName());
                Attributes attributes = dirContextOperations.getAttributes();
                String emailAttribName = studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_EMAIL);
                String firstNameAttribName = studioConfiguration
                        .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_FIRST_NAME);
                String lastNameAttribName = studioConfiguration
                        .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_LAST_NAME);
                String siteIdAttribName = studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_SITE_ID);
                String groupNameAttribName = studioConfiguration
                        .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_GROUP_NAME);
                Attribute emailAttrib = attributes.get(emailAttribName);
                Attribute firstNameAttrib = attributes.get(firstNameAttribName);
                Attribute lastNameAttrib = attributes.get(lastNameAttribName);
                Attribute siteIdAttrib = attributes.get(siteIdAttribName);
                Attribute groupNameAttrib = attributes.get(groupNameAttribName);

                User user = new User();
                user.setGroups(new ArrayList<>());
                user.setActive(1);
                user.setUsername(username);

                if (emailAttrib != null && emailAttrib.get() != null) {
                    user.setEmail(emailAttrib.get().toString());
                } else {
                    logger.error("No LDAP attribute " + emailAttribName + " found for username " + username
                            + ". User will not be imported into DB.");
                    return null;
                }
                if (firstNameAttrib != null && firstNameAttrib.get() != null) {
                    user.setFirstname(firstNameAttrib.get().toString());
                } else {
                    logger.warn("No LDAP attribute " + firstNameAttribName + " found for username " + username);
                }
                if (lastNameAttrib != null && lastNameAttrib.get() != null) {
                    user.setLastname(lastNameAttrib.get().toString());
                } else {
                    logger.warn("No LDAP attribute " + lastNameAttribName + " found for username " + username);
                }

                if (siteIdAttrib != null && siteIdAttrib.get() != null) {
                    Map<String, Object> params = new HashMap<>();
                    NamingEnumeration siteIdValues = siteIdAttrib.getAll();
                    while (siteIdValues.hasMore()) {
                        Object siteIdObj = siteIdValues.next();
                        if (siteIdObj != null) {
                            String[] siteIdAndGroupName = extractSiteIdAndGroupNameFromAttributeValue(
                                    siteIdObj.toString());

                            if (siteIdAndGroupName.length > 0) {
                                params.put("siteId", siteIdAndGroupName[0]);

                                SiteFeed siteFeed = siteFeedMapper.getSite(params);
                                if (siteFeed != null) {
                                    // Add groups, first the one that's specific to the site
                                    if (siteIdAndGroupName.length > 1) {
                                        addGroupToUser(user, siteIdAndGroupName[1], siteFeed);
                                    }

                                    extractGroupsFromAttribute(user, groupNameAttribName, groupNameAttrib,
                                            siteFeed);
                                } else {
                                    logger.warn("Not site found for ID " + siteIdAndGroupName[0]);
                                }
                            }
                        }
                    }
                } else {
                    String defaultSiteId = studioConfiguration.getProperty(SECURITY_LDAP_DEFAULT_SITE_ID);

                    logger.debug("Assigning user " + username + " to default site " + defaultSiteId);

                    Map<String, Object> params = new HashMap<>();
                    params.put("siteId", defaultSiteId);

                    SiteFeed siteFeed = siteFeedMapper.getSite(params);
                    if (siteFeed != null) {
                        extractGroupsFromAttribute(user, groupNameAttribName, groupNameAttrib, siteFeed);
                    } else {
                        logger.warn("No site found for default site ID " + defaultSiteId);
                    }
                }

                return user;
            } catch (NamingException e) {
                logger.error("Error getting details from LDAP for username " + username, e);

                return null;
            }
        }
    };

    // Create ldap query to authenticate user
    LdapQuery ldapQuery = query().where(studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_USERNAME))
            .is(username);
    User user;
    try {
        user = ldapTemplate.authenticate(ldapQuery, password, mapper);
    } catch (EmptyResultDataAccessException e) {
        logger.info("User " + username
                + " not found with external security provider. Trying to authenticate against studio database");
        // When user not found try to authenticate against studio database
        return super.authenticate(username, password);
    } catch (CommunicationException e) {
        logger.info("Failed to connect with external security provider. "
                + "Trying to authenticate against studio database");
        // When user not found try to authenticate against studio database
        return super.authenticate(username, password);
    } catch (AuthenticationException e) {
        logger.error("Authentication failed with the LDAP system", e);

        throw new BadCredentialsException();
    } catch (Exception e) {
        logger.error("Authentication failed with the LDAP system", e);

        throw new AuthenticationSystemException("Authentication failed with the LDAP system", e);
    }

    if (user != null) {
        // When user authenticated against LDAP, upsert user data into studio database
        if (super.userExists(username)) {
            try {
                boolean success = updateUserInternal(user.getUsername(), user.getFirstname(),
                        user.getLastname(), user.getEmail());
                if (success) {
                    ActivityService.ActivityType activityType = ActivityService.ActivityType.UPDATED;
                    Map<String, String> extraInfo = new HashMap<>();
                    extraInfo.put(DmConstants.KEY_CONTENT_TYPE, StudioConstants.CONTENT_TYPE_USER);
                    activityService.postActivity(getSystemSite(), user.getUsername(), user.getUsername(),
                            activityType, ActivityService.ActivitySource.API, extraInfo);
                }
            } catch (UserNotFoundException e) {
                logger.error(
                        "Error updating user " + username + " with data from external authentication provider",
                        e);

                throw new AuthenticationSystemException(
                        "Error updating user " + username + " with data from external authentication provider",
                        e);
            }
        } else {
            try {
                boolean success = createUser(user.getUsername(), password, user.getFirstname(),
                        user.getLastname(), user.getEmail(), true);
                if (success) {
                    ActivityService.ActivityType activityType = ActivityService.ActivityType.CREATED;
                    Map<String, String> extraInfo = new HashMap<>();
                    extraInfo.put(DmConstants.KEY_CONTENT_TYPE, StudioConstants.CONTENT_TYPE_USER);
                    activityService.postActivity(getSystemSite(), user.getUsername(), user.getUsername(),
                            activityType, ActivityService.ActivitySource.API, extraInfo);
                }
            } catch (UserAlreadyExistsException e) {
                logger.error("Error adding user " + username + " from external authentication provider", e);

                throw new AuthenticationSystemException(
                        "Error adding user " + username + " from external authentication provider", e);
            }
        }
        for (Group group : user.getGroups()) {
            try {
                upsertUserGroup(group.getSite(), group.getName(), user.getUsername());
            } catch (GroupAlreadyExistsException | SiteNotFoundException | UserNotFoundException
                    | UserAlreadyExistsException | GroupNotFoundException e) {
                logger.error("Failed to upsert user groups data from LDAP", e);
            }
        }

        String token = createToken(user);
        storeSessionTicket(token);
        storeSessionUsername(username);

        return token;
    } else {
        logger.error("Failed to retrieve LDAP user details");

        throw new AuthenticationSystemException("Failed to retrieve LDAP user details");
    }
}

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

/**
 * Get all ldap groups//from   w  w  w.j  ava2 s. c o  m
 * 
 * @param siteBean
 * @param baseDnGroup
 * @param ldapFilterGroups
 * @param groupAttributeName
 * @param groupToMemberReferencesMap
 * @return
 * @throws Exception
 */
public static Map<String, TPersonBean> getLdapGroupsPaged(String baseURL, TSiteBean siteBean,
        String baseDnGroup, String ldapFilterGroups, String groupAttributeName,
        Map<String, List<String>> groupToMemberReferencesMap) throws Exception {
    if (ldapFilterGroups == null || "".equals(ldapFilterGroups) || "*".equals(ldapFilterGroups)) {
        ldapFilterGroups = "(" + groupAttributeName + "=*)";
    }
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    LdapContext context = getInitialContext(baseURL + baseDnGroup, bindDN, bindPassword);
    HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>();
    if (context == null) {
        LOGGER.warn("Context is null");
        return ldapGroupsMap;
    }
    int recordCount = 0;
    SearchControls ctls = null;
    String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER);
    if (groupMemberAttributName == null) {
        groupMemberAttributName = DEFAULT_GROUP_MEMBER;
    }
    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
        do {
            /* perform the search */
            NamingEnumeration<SearchResult> results = context.search("", ldapFilterGroups, ctls);
            /* for each entry print out name + all attrs and values */
            while (results != null && results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                // Attributes atrs = sr.getAttributes();
                Attributes attributes = searchResult.getAttributes();
                if (attributes == null) {
                    LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName());
                    return null;
                }
                TPersonBean personBean = new TPersonBean();
                try {
                    Attribute groupNameAttribute = attributes.get(groupAttributeName);
                    if (groupNameAttribute != null) {
                        String groupName = (String) groupNameAttribute.get();
                        LOGGER.debug("Groupname: " + groupName);
                        if (groupName == null || "".equals(groupName)) {
                            LOGGER.info("No value for group name attribute " + groupAttributeName);
                            return null;
                        } else {
                            personBean.setLoginName(groupName);
                            ldapGroupsMap.put(personBean.getLoginName(), personBean);
                        }
                        Attribute memberAttribute = attributes.get(groupMemberAttributName);
                        if (memberAttribute != null) {
                            NamingEnumeration<?> members = memberAttribute.getAll();
                            while (members != null && members.hasMore()) {
                                String memberSearchResult = (String) members.next();
                                List<String> memberDNList = groupToMemberReferencesMap.get(groupName);
                                if (memberDNList == null) {
                                    memberDNList = new ArrayList<String>();
                                    groupToMemberReferencesMap.put(groupName, memberDNList);
                                }
                                memberDNList.add(memberSearchResult);
                            }
                        } else {
                            LOGGER.info("Could not find value(s) for group member attribute "
                                    + groupMemberAttributName + " for group " + groupName);
                        }
                    }
                    LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get());
                    LOGGER.debug("Processed " + personBean.getLoginName() + " (" + personBean.getFirstName()
                            + " " + personBean.getLastName() + ")");
                } catch (Exception e) {
                    LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage());
                    LOGGER.warn(
                            "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml");
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Stack trace:", e);
                    }
                }
                ++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 {
        context.close();
    }
    return ldapGroupsMap;
}

From source file:org.apache.directory.studio.connection.core.io.jndi.LdifSearchLogger.java

/**
 * {@inheritDoc}/*from  w  ww .  j  a  va  2 s .c  o m*/
 */
public void logSearchResultEntry(Connection connection, StudioSearchResult studioSearchResult, long requestNum,
        NamingException ex) {
    if (!isSearchResultEntryLogEnabled()) {
        return;
    }

    try {
        String formattedString;
        if (studioSearchResult != null) {
            String dn = studioSearchResult.getNameInNamespace();
            Attributes attributes = studioSearchResult.getAttributes();

            LdifContentRecord record = new LdifContentRecord(LdifDnLine.create(dn));
            NamingEnumeration<? extends Attribute> attributeEnumeration = attributes.getAll();
            while (attributeEnumeration.hasMore()) {
                Attribute attribute = attributeEnumeration.next();
                String attributeName = attribute.getID();
                NamingEnumeration<?> valueEnumeration = attribute.getAll();
                while (valueEnumeration.hasMore()) {
                    Object o = valueEnumeration.next();
                    if (o instanceof String) {
                        record.addAttrVal(LdifAttrValLine.create(attributeName, (String) o));
                    }
                    if (o instanceof byte[]) {
                        record.addAttrVal(LdifAttrValLine.create(attributeName, (byte[]) o));
                    }
                }
            }
            record.finish(LdifSepLine.create());
            formattedString = record.toFormattedString(LdifFormatParameters.DEFAULT);
        } else {
            formattedString = LdifFormatParameters.DEFAULT.getLineSeparator();
        }

        log(formattedString, "SEARCH RESULT ENTRY (" + requestNum + ")", ex, connection); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (NamingException e) {
    }
}

From source file:ru.runa.wfe.security.logic.LdapLogic.java

private void fillTargetActorsRecursively(DirContext dirContext, Set<Actor> recursiveActors,
        SearchResult searchResult, Map<String, SearchResult> groupResultsByDistinguishedName,
        Map<String, Actor> actorsByDistinguishedName) throws NamingException {
    NamingEnumeration<String> namingEnum = (NamingEnumeration<String>) searchResult.getAttributes()
            .get(ATTR_GROUP_MEMBER).getAll();
    while (namingEnum.hasMore()) {
        String executorDistinguishedName = namingEnum.next();
        SearchResult groupSearchResult = groupResultsByDistinguishedName.get(executorDistinguishedName);
        if (groupSearchResult != null) {
            fillTargetActorsRecursively(dirContext, recursiveActors, groupSearchResult,
                    groupResultsByDistinguishedName, actorsByDistinguishedName);
        } else {/*from ww  w. jav a 2s  . c om*/
            Actor actor = actorsByDistinguishedName.get(executorDistinguishedName);
            if (actor != null) {
                recursiveActors.add(actor);
            } else {
                Matcher m = getPatternForMissedPeople().matcher(executorDistinguishedName);
                String executorPath = m.replaceAll("");
                Attribute samAttribute = dirContext.getAttributes(executorPath).get(ATTR_ACCOUNT_NAME);
                if (samAttribute != null) {
                    String executorName = samAttribute.get().toString();
                    log.debug("Executor name " + executorDistinguishedName + " fetched by invocation: "
                            + executorName);
                    try {
                        Executor executor = executorDao.getExecutor(executorName);
                        if (executor instanceof Actor) {
                            recursiveActors.add((Actor) executor);
                        }
                    } catch (ExecutorDoesNotExistException e) {
                        log.warn(e.getMessage() + " for '" + executorDistinguishedName + "'");
                    }
                } else {
                    log.warn("Not found '" + executorDistinguishedName
                            + "' neither in group or actor maps or by invocation");
                }
            }
        }
    }
}

From source file:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java

private void populateDCMap() throws UserStoreException {
    try {//  www.ja  v  a 2  s. co m
        //get the directory context for DNS
        DirContext dnsContext = new InitialDirContext(environmentForDNS);
        //compose the DNS service to be queried
        String DNSServiceName = LDAPConstants.ACTIVE_DIRECTORY_DOMAIN_CONTROLLER_SERVICE + DNSDomainName;
        //query the DNS
        Attributes attributes = dnsContext.getAttributes(DNSServiceName,
                new String[] { LDAPConstants.SRV_ATTRIBUTE_NAME });
        Attribute srvRecords = attributes.get(LDAPConstants.SRV_ATTRIBUTE_NAME);
        //there can be multiple records with same domain name - get them all
        NamingEnumeration srvValues = srvRecords.getAll();
        dcMap = new TreeMap<Integer, SRVRecord>();
        //extract all SRV Records for _ldap._tcp service under the specified domain and populate dcMap
        //int forcedPriority = 0;
        while (srvValues.hasMore()) {
            String value = srvValues.next().toString();
            SRVRecord srvRecord = new SRVRecord();
            String valueItems[] = value.split(" ");
            String priority = valueItems[0];
            if (priority != null) {
                int priorityInt = Integer.parseInt(priority);

                /*if ((priorityInt == forcedPriority) || (priorityInt < forcedPriority)) {
                forcedPriority++;
                priorityInt = forcedPriority;
                }*/
                srvRecord.setPriority(priorityInt);
            } /* else {
              forcedPriority++;
              srvRecord.setPriority(forcedPriority);
              }*/
            String weight = valueItems[1];
            if (weight != null) {
                srvRecord.setWeight(Integer.parseInt(weight));
            }
            String port = valueItems[2];
            if (port != null) {
                srvRecord.setPort(Integer.parseInt(port));
            }
            String host = valueItems[3];
            if (host != null) {
                srvRecord.setHostName(host);
            }
            //we index dcMap on priority basis, therefore, priorities must be different
            dcMap.put(srvRecord.getPriority(), srvRecord);
        }
        //iterate over the SRVRecords for Active Directory Domain Controllers and figure out the
        //host records for that
        for (SRVRecord srvRecord : dcMap.values()) {
            Attributes hostAttributes = dnsContext.getAttributes(srvRecord.getHostName(),
                    new String[] { LDAPConstants.A_RECORD_ATTRIBUTE_NAME });
            Attribute hostRecord = hostAttributes.get(LDAPConstants.A_RECORD_ATTRIBUTE_NAME);
            //we know there is only one IP value for a given host. So we do just get, not getAll
            srvRecord.setHostIP((String) hostRecord.get());
        }
    } catch (NamingException e) {
        log.error("Error obtaining information from DNS Server" + e.getMessage(), e);
        throw new UserStoreException("Error obtaining information from DNS Server " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.appfactory.userstore.OTAppFactoryUserStore.java

@Override
public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException {
    String[] userNames = new String[0];

    if (maxItemLimit == 0) {
        return userNames;
    }// w ww  .j  a  v  a  2 s.  com

    int givenMax = Integer
            .parseInt(realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST));

    if (maxItemLimit < 0 || maxItemLimit > givenMax) {
        maxItemLimit = givenMax;
    }

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setCountLimit(maxItemLimit);

    if (filter.contains("?") || filter.contains("**")) {
        throw new UserStoreException(
                "Invalid character sequence entered for user serch. Please enter valid sequence.");
    }

    StringBuffer searchFilter = null;
    searchFilter = new StringBuffer(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    StringBuffer buff = new StringBuffer();
    buff.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=").append(filter)
            .append("))");

    String serviceNameAttribute = "sn";
    String mailAttribute = "mail";
    String returnedAtts[] = { userNameProperty, serviceNameAttribute, mailAttribute };

    searchCtls.setReturningAttributes(returnedAtts);
    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    String[] allUserNames = null;
    try {
        dirContext = connectionSource.getContext();
        answer = dirContext.search(searchBase, buff.toString(), searchCtls);
        List<String> list = new ArrayList<String>();
        int i = 0;
        while (answer.hasMoreElements() && i < maxItemLimit) {
            SearchResult sr = (SearchResult) answer.next();
            if (sr.getAttributes() != null) {
                Attribute attr = sr.getAttributes().get(mailAttribute);

                /*
                 * If this is a service principle, just ignore and iterate rest of the array.
                 * The entity is a service if value of surname is Service
                 */
                Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute);

                if (attrSurname != null) {
                    String serviceName = (String) attrSurname.get();
                    if (serviceName != null
                            && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) {
                        continue;
                    }
                }

                if (attr != null) {
                    String name = (String) attr.get();
                    //append the domain if exist
                    String domain = userRealm.getRealmConfiguration()
                            .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
                    if (domain != null) {
                        domain = domain + "/";
                        name = domain + name;
                    }
                    list.add(name);
                    i++;
                }
            }
        }
        userNames = list.toArray(new String[list.size()]);
        //get secondary user lists
        UserStoreManager secUserManager = this.getSecondaryUserStoreManager();
        if (secUserManager != null) {
            String[] secUserNames = secUserManager.listUsers(filter, maxItemLimit);
            allUserNames = UserCoreUtil.combineArrays(userNames, secUserNames);
        } else {
            allUserNames = userNames;
        }
        Arrays.sort(allUserNames);
    } catch (NamingException e) {
        log.error(e.getMessage(), e);
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return allUserNames;
}

From source file:ru.runa.wfe.security.logic.LdapLogic.java

private int synchronizeGroups(DirContext dirContext, Map<String, Actor> actorsByDistinguishedName)
        throws NamingException {
    int changesCount = 0;
    List<Group> existingGroupsList = executorDao.getAllGroups();
    Map<String, Group> existingGroupsByLdapNameMap = Maps.newHashMap();
    for (Group group : existingGroupsList) {
        if (!Strings.isNullOrEmpty(group.getLdapGroupName())) {
            existingGroupsByLdapNameMap.put(group.getLdapGroupName(), group);
        }/*from ww  w .j a v  a2  s.  co m*/
    }
    Set<Group> ldapGroupsToDelete = Sets.newHashSet();
    if (LdapProperties.isSynchronizationDeleteExecutors()) {
        Set<Executor> ldapExecutors = executorDao.getGroupChildren(importGroup);
        for (Executor executor : ldapExecutors) {
            if (executor instanceof Group) {
                ldapGroupsToDelete.add((Group) executor);
            }
        }
    }
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    Map<String, SearchResult> groupResultsByDistinguishedName = Maps.newHashMap();
    for (String ou : LdapProperties.getSynchronizationOrganizationUnits()) {
        NamingEnumeration<SearchResult> list = dirContext.search(ou, OBJECT_CLASS_GROUP_FILTER, controls);
        while (list.hasMore()) {
            SearchResult searchResult = list.next();
            if (searchResult.getAttributes().get(ATTR_GROUP_MEMBER) == null) {
                continue;
            }
            groupResultsByDistinguishedName.put(searchResult.getNameInNamespace(), searchResult);
        }
    }
    for (SearchResult searchResult : groupResultsByDistinguishedName.values()) {
        String name = getStringAttribute(searchResult, ATTR_ACCOUNT_NAME);
        String description = getStringAttribute(searchResult,
                LdapProperties.getSynchronizationGroupDescriptionAttribute());
        ToStringHelper toStringHelper = MoreObjects.toStringHelper("group info");
        toStringHelper.add("name", name).add("description", description).omitNullValues();
        log.debug("Read " + toStringHelper.toString());
        Group group = existingGroupsByLdapNameMap.get(name);
        if (group == null) {
            if (!LdapProperties.isSynchronizationCreateExecutors()) {
                continue;
            }
            group = new Group(name, description);
            group.setLdapGroupName(name);
            log.info("Creating " + group);
            executorDao.create(group);
            executorDao.addExecutorsToGroup(Lists.newArrayList(group), importGroup);
            permissionDao.setPermissions(importGroup, Lists.newArrayList(Permission.LIST), group);
            changesCount++;
        } else {
            ldapGroupsToDelete.remove(group);
            if (LdapProperties.isSynchronizationUpdateExecutors()) {
                List<IChange> changes = Lists.newArrayList();
                if (isAttributeNeedsChange(description, group.getDescription())) {
                    changes.add(new AttributeChange("description", group.getDescription(), description));
                    group.setDescription(description);
                    executorDao.update(group);
                }
                if (executorDao.removeExecutorFromGroup(group, wasteGroup)) {
                    changes.add(new Change("waste group removal"));
                }
                if (executorDao.addExecutorToGroup(group, importGroup)) {
                    changes.add(new Change("import group addition"));
                }
                if (!changes.isEmpty()) {
                    log.info("Updating " + group + ": " + changes);
                    changesCount++;
                }
            }
        }

        Set<Actor> actorsToDelete = Sets.newHashSet(executorDao.getGroupActors(group));
        Set<Actor> actorsToAdd = Sets.newHashSet();
        Set<Actor> groupTargetActors = Sets.newHashSet();
        fillTargetActorsRecursively(dirContext, groupTargetActors, searchResult,
                groupResultsByDistinguishedName, actorsByDistinguishedName);
        for (Actor targetActor : groupTargetActors) {
            if (!actorsToDelete.remove(targetActor)) {
                actorsToAdd.add(targetActor);
            }
        }
        if (actorsToAdd.size() > 0) {
            log.info("Adding to " + group + ": " + actorsToAdd);
            executorDao.addExecutorsToGroup(actorsToAdd, group);
            changesCount++;
        }
        if (actorsToDelete.size() > 0) {
            executorDao.removeExecutorsFromGroup(Lists.newArrayList(actorsToDelete), group);
            changesCount++;
        }
    }
    if (LdapProperties.isSynchronizationDeleteExecutors() && ldapGroupsToDelete.size() > 0) {
        executorDao.removeExecutorsFromGroup(ldapGroupsToDelete, importGroup);
        executorDao.addExecutorsToGroup(ldapGroupsToDelete, wasteGroup);
        log.info("Inactivating " + ldapGroupsToDelete);
        changesCount += ldapGroupsToDelete.size();
    }
    return changesCount;
}