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.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void getGroups(UserGroupSink sink) throws Throwable {
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
    long highestdeltaSyncGroupTime = deltaSyncGroupTime;
    try {/* w w w. j a  v  a 2s.  c  om*/
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        extendedGroupSearchFilter = "(objectclass=" + groupObjectClass + ")";
        if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) {
            String customFilter = groupSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }
            extendedGroupSearchFilter = extendedGroupSearchFilter + customFilter;
        }

        extendedAllGroupsSearchFilter = "(&" + extendedGroupSearchFilter + "(|(uSNChanged>="
                + deltaSyncGroupTime + ")(modifyTimestamp>=" + deltaSyncGroupTimeStamp + "Z)))";

        LOG.info("extendedAllGroupsSearchFilter = " + extendedAllGroupsSearchFilter);
        for (int ou = 0; ou < groupSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                int paged = 0;
                do {
                    groupSearchResultEnum = ldapContext.search(groupSearchBase[ou],
                            extendedAllGroupsSearchFilter, groupSearchControls);
                    while (groupSearchResultEnum.hasMore()) {
                        final SearchResult groupEntry = groupSearchResultEnum.next();
                        if (groupEntry == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("groupEntry null, skipping sync for the entry");
                            }
                            continue;
                        }
                        counter++;
                        Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute);
                        if (groupNameAttr == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(groupNameAttribute + " empty for entry "
                                        + groupEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }
                        String gName = (String) groupNameAttr.get();
                        String transformGroupName = groupNameTransform(gName);
                        // If group based search is enabled, then
                        // update the group name to ranger admin
                        // check for group members and populate userInfo object with user's full name and group mapping
                        if (groupSearchFirstEnabled) {
                            LOG.debug("Update Ranger admin with " + transformGroupName);
                            sink.addOrUpdateGroup(transformGroupName);
                        }
                        Attribute timeStampAttr = groupEntry.getAttributes().get("uSNChanged");
                        if (timeStampAttr != null) {
                            String uSNChangedVal = (String) timeStampAttr.get();
                            long currentDeltaSyncTime = Long.parseLong(uSNChangedVal);
                            if (currentDeltaSyncTime > highestdeltaSyncGroupTime) {
                                highestdeltaSyncGroupTime = currentDeltaSyncTime;
                            }
                        } else {
                            timeStampAttr = groupEntry.getAttributes().get("modifytimestamp");
                            if (timeStampAttr != null) {
                                String timeStampVal = (String) timeStampAttr.get();
                                Date parseDate = dateFormat.parse(timeStampVal);
                                long currentDeltaSyncTime = parseDate.getTime();
                                LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = "
                                        + currentDeltaSyncTime);
                                if (currentDeltaSyncTime > highestdeltaSyncGroupTime) {
                                    highestdeltaSyncGroupTime = currentDeltaSyncTime;
                                    deltaSyncGroupTimeStamp = timeStampVal;
                                }
                            }
                        }
                        Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName);
                        int userCount = 0;
                        if (groupMemberAttr == null || groupMemberAttr.size() <= 0) {
                            LOG.info("No members available for " + gName);
                            continue;
                        }

                        NamingEnumeration<?> userEnum = groupMemberAttr.getAll();
                        while (userEnum.hasMore()) {
                            String originalUserFullName = (String) userEnum.next();
                            if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) {
                                continue;
                            }
                            userCount++;
                            String userName = getShortUserName(originalUserFullName);
                            originalUserFullName = originalUserFullName.toLowerCase();
                            if (groupSearchFirstEnabled && !userSearchEnabled) {
                                String transformUserName = userNameTransform(userName);
                                try {
                                    sink.addOrUpdateUser(transformUserName);
                                } catch (Throwable t) {
                                    LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage()
                                            + ", for user: " + transformUserName);
                                }
                                userNameMap.put(originalUserFullName, transformUserName);
                            }
                            //System.out.println("Adding " + userNameMap.get(originalUserFullName) + " and fullname = " + originalUserFullName + " to " + gName);
                            if (userNameMap.get(originalUserFullName) != null) {
                                groupUserTable.put(gName, originalUserFullName,
                                        userNameMap.get(originalUserFullName));
                            } else {
                                groupUserTable.put(gName, originalUserFullName, originalUserFullName);
                            }
                            groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName);
                        }
                        LOG.info("No. of members in the group " + gName + " = " + userCount);
                    }
                    // Examine the paged results control response
                    Control[] controls = ldapContext.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) {
                                    LOG.debug("END-OF-PAGE total : " + total);
                                } else {
                                    LOG.debug("END-OF-PAGE total : unknown");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOG.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    if (pagedResultsEnabled) {
                        LOG.debug(String.format("Fetched paged results round: %s", ++paged));
                        ldapContext.setRequestControls(new Control[] {
                                new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.getGroups() completed with group count: " + counter);
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.getGroups() failed with exception: " + t);
                LOG.info("LdapDeltaUserGroupBuilder.getGroups() group count: " + counter);
            }
        }

    } finally {
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
        closeLdapContext();
    }

    if (groupHierarchyLevels > 0) {
        LOG.debug("deltaSyncGroupTime = " + deltaSyncGroupTime);
        if (deltaSyncGroupTime > 0) {
            LOG.info(
                    "LdapDeltaUserGroupBuilder.getGroups(): Going through group hierarchy for nested group evaluation for deltasync");
            goUpGroupHierarchyLdap(groupNameMap.keySet(), groupHierarchyLevels - 1);
        }
    }

    if (deltaSyncGroupTime < highestdeltaSyncGroupTime) {
        // Incrementing highestdeltaSyncGroupTime (for AD) in order to avoid search record repetition for next sync cycle.
        deltaSyncGroupTime = highestdeltaSyncGroupTime + 1;
        // Incrementing the highest timestamp value (for OpenLdap) with 1min in order to avoid search record repetition for next sync cycle.
        deltaSyncGroupTimeStamp = dateFormat.format(new Date(highestdeltaSyncGroupTime + 60000l));
    }
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * @param userName Username of the user.
 * @param searchBase Searchbase which the user should be searched for.
 * @param searchFilter Search filter of the username.
 * @return DN of the user whose usename is given.
 * @throws UserStoreException If an error occurs while connecting to the LDAP userstore.
 *///from ww  w  . j a v a 2s . c  o  m
private String getNameInSpaceForUserName(String userName, String searchBase, String searchFilter)
        throws UserStoreException {
    boolean debug = log.isDebugEnabled();

    String userDN = null;

    DirContext dirContext = this.connectionSource.getContext();
    NamingEnumeration<SearchResult> answer = null;
    try {
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        if (log.isDebugEnabled()) {
            try {
                log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: "
                        + dirContext.getNameInNamespace());
            } catch (NamingException e) {
                log.debug("Error while getting DN of search base", e);
            }
        }
        SearchResult userObj;
        String[] searchBases = searchBase.split(CommonConstants.XML_PATTERN_SEPERATOR);
        for (String base : searchBases) {
            answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls);
            if (answer.hasMore()) {
                userObj = answer.next();
                if (userObj != null) {
                    //no need to decode since , if decoded the whole string, can't be encoded again
                    //eg CN=Hello\,Ok=test\,test, OU=Industry
                    userDN = userObj.getNameInNamespace();
                    break;
                }
            }
        }
        if (debug) {
            log.debug("Name in space for " + userName + " is " + userDN);
        }
    } catch (Exception e) {
        log.debug(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return userDN;
}

From source file:org.lsc.jndi.JndiServices.java

private SearchResult doGetEntry(final String base, final String filter, final SearchControls sc,
        final int scope) throws NamingException {
    //sanity checks
    String searchBase = base == null ? "" : base;
    String searchFilter = filter == null ? DEFAULT_FILTER : filter;

    NamingEnumeration<SearchResult> ne = null;
    try {/*from w ww.java2 s  . com*/
        sc.setSearchScope(scope);
        String rewrittenBase = null;
        if (contextDn != null && searchBase.toLowerCase().endsWith(contextDn.toString().toLowerCase())) {
            if (!searchBase.equalsIgnoreCase(contextDn.toString())) {
                rewrittenBase = searchBase.substring(0,
                        searchBase.toLowerCase().lastIndexOf(contextDn.toString().toLowerCase()) - 1);
            } else {
                rewrittenBase = "";
            }
        } else {
            rewrittenBase = searchBase;
        }
        ne = ctx.search(rewrittenBase, searchFilter, sc);

    } catch (NamingException nex) {
        LOGGER.error("Error while looking for {} in {}: {}", new Object[] { searchFilter, searchBase, nex });
        throw nex;
    }

    SearchResult sr = null;
    if (ne.hasMoreElements()) {
        sr = (SearchResult) ne.nextElement();
        if (ne.hasMoreElements()) {
            LOGGER.error("Too many entries returned (base: \"{}\", filter: \"{}\")", searchBase, searchFilter);
            throw new SizeLimitExceededException("Too many entries returned (base: \"" + searchBase
                    + "\", filter: \"" + searchFilter + "\")");
        } else {
            return sr;
        }
    } else {
        // try hasMore method to throw exceptions if there are any and we didn't get our entry
        ne.hasMore();
    }
    return sr;
}

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public List<String> getGroups(String username, DirContext context) throws MappingException {

    List<String> userGroups = new ArrayList<String>();

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {/* ww  w.j av  a  2  s . co m*/

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String groupEntry = null;
        try {
            //try to look the user up
            User user = userManager.findUser(username);
            if (user instanceof LdapUser) {
                LdapUser ldapUser = LdapUser.class.cast(user);
                Attribute dnAttribute = ldapUser.getOriginalAttributes().get(getLdapDnAttribute());
                if (dnAttribute != null) {
                    groupEntry = String.class.cast(dnAttribute.get());
                }

            }
        } catch (UserNotFoundException e) {
            log.warn("Failed to look up user {}. Computing distinguished name manually", username, e);
        } catch (UserManagerException e) {
            log.warn("Failed to look up user {}. Computing distinguished name manually", username, e);
        }
        if (groupEntry == null) {
            //failed to look up the user's groupEntry directly
            StringBuilder builder = new StringBuilder();
            String posixGroup = "posixGroup";
            if (posixGroup.equals(getLdapGroupClass())) {
                builder.append(username);
            } else {
                builder.append(this.userIdAttribute).append("=").append(username).append(",")
                        .append(getBaseDn());
            }
            groupEntry = builder.toString();
        }

        String filter = new StringBuilder().append("(&").append("(objectClass=" + getLdapGroupClass() + ")")
                .append("(").append(getLdapGroupMember()).append("=").append(Rdn.escapeValue(groupEntry))
                .append(")").append(")").toString();

        log.debug("filter: {}", filter);

        namingEnumeration = context.search(getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            List<String> allMembers = new ArrayList<String>();

            Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember());

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {

                    String userName = allMembersEnum.next();
                    //the original dn
                    allMembers.add(userName);
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    allMembers.add(userName);
                }
                close(allMembersEnum);
            }

            if (allMembers.contains(username)) {
                String groupName = searchResult.getName();
                // cn=blabla we only want bla bla
                groupName = StringUtils.substringAfter(groupName, "=");
                userGroups.add(groupName);

            } else if (allMembers.contains(groupEntry)) {
                String groupName = searchResult.getName();
                // cn=blabla we only want bla bla
                groupName = StringUtils.substringAfter(groupName, "=");
                userGroups.add(groupName);
            }

        }

        return userGroups;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    } finally {
        close(namingEnumeration);
    }
}

From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void getUsers(UserGroupSink sink) throws Throwable {
    NamingEnumeration<SearchResult> userSearchResultEnum = null;
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    try {//from  www.j  a va 2  s  . c o  m
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        extendedUserSearchFilter = "(objectclass=" + userObjectClass + ")(|(uSNChanged>=" + deltaSyncUserTime
                + ")(modifyTimestamp>=" + deltaSyncUserTimeStamp + "Z))";

        if (userSearchFilter != null && !userSearchFilter.trim().isEmpty()) {
            String customFilter = userSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }

            extendedUserSearchFilter = "(&" + extendedUserSearchFilter + customFilter + ")";
        } else {
            extendedUserSearchFilter = "(&" + extendedUserSearchFilter + ")";
        }
        LOG.info("extendedUserSearchFilter = " + extendedUserSearchFilter);

        long highestdeltaSyncUserTime = deltaSyncUserTime;

        // When multiple OUs are configured, go through each OU as the user search base to search for users.
        for (int ou = 0; ou < userSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                int paged = 0;
                do {
                    userSearchResultEnum = ldapContext.search(userSearchBase[ou], extendedUserSearchFilter,
                            userSearchControls);

                    while (userSearchResultEnum.hasMore()) {
                        // searchResults contains all the user entries
                        final SearchResult userEntry = userSearchResultEnum.next();

                        if (userEntry == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("userEntry null, skipping sync for the entry");
                            }
                            continue;
                        }
                        //System.out.println("userEntry = " + userEntry);

                        Attributes attributes = userEntry.getAttributes();
                        if (attributes == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("attributes  missing for entry " + userEntry.getNameInNamespace()
                                        + ", skipping sync");
                            }
                            continue;
                        }

                        Attribute userNameAttr = attributes.get(userNameAttribute);
                        if (userNameAttr == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(userNameAttribute + " missing for entry "
                                        + userEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }

                        String userFullName = (userEntry.getNameInNamespace()).toLowerCase();
                        String userName = (String) userNameAttr.get();

                        if (userName == null || userName.trim().isEmpty()) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(userNameAttribute + " empty for entry "
                                        + userEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }

                        Attribute timeStampAttr = attributes.get("uSNChanged");
                        if (timeStampAttr != null) {
                            String uSNChangedVal = (String) timeStampAttr.get();
                            long currentDeltaSyncTime = Long.parseLong(uSNChangedVal);
                            LOG.info("uSNChangedVal = " + uSNChangedVal + "and currentDeltaSyncTime = "
                                    + currentDeltaSyncTime);
                            if (currentDeltaSyncTime > highestdeltaSyncUserTime) {
                                highestdeltaSyncUserTime = currentDeltaSyncTime;
                            }
                        } else {
                            timeStampAttr = attributes.get("modifytimestamp");
                            if (timeStampAttr != null) {
                                String timeStampVal = (String) timeStampAttr.get();
                                Date parseDate = dateFormat.parse(timeStampVal);
                                long currentDeltaSyncTime = parseDate.getTime();
                                LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = "
                                        + currentDeltaSyncTime);
                                if (currentDeltaSyncTime > highestdeltaSyncUserTime) {
                                    highestdeltaSyncUserTime = currentDeltaSyncTime;
                                    deltaSyncUserTimeStamp = timeStampVal;
                                }
                            }
                        }

                        if (!groupSearchFirstEnabled) {
                            String transformUserName = userNameTransform(userName);
                            try {
                                sink.addOrUpdateUser(transformUserName);
                            } catch (Throwable t) {
                                LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage()
                                        + ", for user: " + transformUserName);
                            }
                            //System.out.println("Adding user fullname = " + userFullName + " username = " + transformUserName);
                            userNameMap.put(userFullName, transformUserName);
                            Set<String> groups = new HashSet<String>();

                            // Get all the groups from the group name attribute of the user only when group search is not enabled.
                            if (!groupSearchEnabled) {
                                for (String useGroupNameAttribute : userGroupNameAttributeSet) {
                                    Attribute userGroupfAttribute = userEntry.getAttributes()
                                            .get(useGroupNameAttribute);
                                    if (userGroupfAttribute != null) {
                                        NamingEnumeration<?> groupEnum = userGroupfAttribute.getAll();
                                        while (groupEnum.hasMore()) {
                                            String gName = getShortGroupName((String) groupEnum.next());
                                            String transformGroupName = groupNameTransform(gName);
                                            groups.add(transformGroupName);
                                        }
                                    }
                                }
                            }

                            List<String> groupList = new ArrayList<String>(groups);
                            try {
                                sink.addOrUpdateUser(transformUserName, groupList);

                            } catch (Throwable t) {
                                LOG.error("sink.addOrUpdateUserGroups failed with exception: " + t.getMessage()
                                        + ", for user: " + transformUserName + " and groups: " + groupList);
                            }
                            counter++;
                            if (counter <= 2000) {
                                if (LOG.isInfoEnabled()) {
                                    LOG.info("Updating user count: " + counter + ", userName: " + userName
                                            + ", groupList: " + groupList);
                                }
                                if (counter == 2000) {
                                    LOG.info(
                                            "===> 2000 user records have been synchronized so far. From now on, only a summary progress log will be written for every 100 users. To continue to see detailed log for every user, please enable Trace level logging. <===");
                                }
                            } else {
                                if (LOG.isTraceEnabled()) {
                                    LOG.trace("Updating user count: " + counter + ", userName: " + userName
                                            + ", groupList: " + groupList);
                                } else {
                                    if (counter % 100 == 0) {
                                        LOG.info("Synced " + counter + " users till now");
                                    }
                                }
                            }
                        } else {
                            // If the user from the search result is present in the group user table,
                            // then addorupdate user to ranger admin.
                            LOG.debug("Chekcing if the user " + userFullName
                                    + " is part of the retrieved groups");
                            if (groupUserTable.containsColumn(userFullName)
                                    || groupUserTable.containsColumn(userName)) {
                                String transformUserName = userNameTransform(userName);
                                try {
                                    sink.addOrUpdateUser(transformUserName);
                                } catch (Throwable t) {
                                    LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage()
                                            + ", for user: " + transformUserName);
                                }
                                userNameMap.put(userFullName, transformUserName);
                                //Also update the username in the groupUserTable with the one from username attribute.
                                Map<String, String> userMap = groupUserTable.column(userFullName);
                                for (Map.Entry<String, String> entry : userMap.entrySet()) {
                                    LOG.debug("Updating groupUserTable " + entry.getValue() + " with: "
                                            + transformUserName + " for " + entry.getKey());
                                    groupUserTable.put(entry.getKey(), userFullName, transformUserName);
                                }
                            }
                        }

                    }

                    // Examine the paged results control response
                    Control[] controls = ldapContext.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) {
                                    LOG.debug("END-OF-PAGE total : " + total);
                                } else {
                                    LOG.debug("END-OF-PAGE total : unknown");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOG.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    if (pagedResultsEnabled) {
                        LOG.debug(String.format("Fetched paged results round: %s", ++paged));
                        ldapContext.setRequestControls(new Control[] {
                                new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.getUsers() completed with user count: " + counter);
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.getUsers() failed with exception: " + t);
                LOG.info("LdapDeltaUserGroupBuilder.getUsers() user count: " + counter);
            }
        }
        if (deltaSyncUserTime < highestdeltaSyncUserTime) {
            // Incrementing highestdeltaSyncUserTime (for AD) in order to avoid search record repetition for next sync cycle.
            deltaSyncUserTime = highestdeltaSyncUserTime + 1;
            // Incrementing the highest timestamp value (for Openldap) with 1sec in order to avoid search record repetition for next sync cycle.
            deltaSyncUserTimeStamp = dateFormat.format(new Date(highestdeltaSyncUserTime + 60l));
        }
    } finally {
        if (userSearchResultEnum != null) {
            userSearchResultEnum.close();
        }
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
        closeLdapContext();
    }
}

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

/**
 * @param sr/*w ww. j  a  v a2 s . com*/
 * @param groupAttributeName
 * @return
 */
private List<String> parseSearchResult(SearchResult sr, String groupAttributeName) {
    List<String> list = new ArrayList<String>();
    Attributes attrs = sr.getAttributes();

    if (attrs != null) {
        try {
            NamingEnumeration ae = null;
            for (ae = attrs.getAll(); ae.hasMore();) {
                Attribute attr = (Attribute) ae.next();
                if (groupAttributeName == null || groupAttributeName.equals(attr.getID())) {
                    NamingEnumeration e = null;
                    for (e = attr.getAll(); e.hasMore();) {
                        String value = e.next().toString();
                        int begin = value.indexOf("=") + 1;
                        int end = value.indexOf(",");
                        if (begin > -1 && end > -1) {
                            value = value.substring(begin, end);
                        }
                        list.add(value);
                    }
                    JNDIUtil.closeNamingEnumeration(e);
                }
            }
            JNDIUtil.closeNamingEnumeration(ae);
        } catch (NamingException e) {
            log.debug(e.getMessage(), e);
        }
    }
    return list;
}

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

/**
 * @param searchFilter/*from w w  w  .ja  v a2s .c  o m*/
 * @param returnedAtts
 * @param dirContext
 * @return
 * @throws UserStoreException
 */
protected NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts,
        DirContext dirContext) throws UserStoreException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String searchBases = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    if (returnedAtts != null && returnedAtts.length > 0) {
        searchCtls.setReturningAttributes(returnedAtts);
    }

    if (log.isDebugEnabled()) {
        try {
            log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: "
                    + dirContext.getNameInNamespace());
        } catch (NamingException e) {
            log.debug("Error while getting DN of search base", e);
        }
        if (returnedAtts == null) {
            log.debug("No attributes requested");
        } else {
            for (String attribute : returnedAtts) {
                log.debug("Requesting attribute :" + attribute);
            }
        }
    }

    String[] searchBaseAraay = searchBases.split("#");
    NamingEnumeration<SearchResult> answer = null;

    try {
        for (String searchBase : searchBaseAraay) {
            answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);
            if (answer.hasMore()) {
                return answer;
            }
        }
    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error occurred while search user for filter : " + searchFilter;
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while search user for filter : " + searchFilter;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
    return answer;
}

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

@SuppressWarnings("rawtypes")
protected List<String> getAttributeListOfOneElement(String searchBases, String searchFilter,
        SearchControls searchCtls) throws UserStoreException {
    List<String> list = new ArrayList<String>();
    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    try {//w w w .j  ava2 s . c  om
        dirContext = connectionSource.getContext();
        // handle multiple search bases
        String[] searchBaseArray = searchBases.split("#");
        for (String searchBase : searchBaseArray) {
            try {
                answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);
                int count = 0;
                if (answer.hasMore()) {
                    while (answer.hasMore()) {
                        if (count > 0) {
                            log.error("More than element user exist with name");
                            throw new UserStoreException("More than element user exist with name");
                        }
                        SearchResult sr = (SearchResult) answer.next();
                        count++;
                        list = parseSearchResult(sr, null);
                    }
                    break;
                }
            } catch (NamingException e) {
                //ignore
                if (log.isDebugEnabled()) {
                    log.debug(e);
                }
            }
        }
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return list;
}

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

/**
 * @param searchBase/* ww  w. j  a va 2s  .  c  om*/
 * @param searchFilter
 * @param searchCtls
 * @param objectSid
 * @param primaryGroupID
 * @param userAttributeId
 * @param groupAttributeName
 * @return
 * @throws UserStoreException
 */
private List<String> getAttributeListOfOneElementWithPrimarGroup(String searchBase, String searchFilter,
        SearchControls searchCtls, String objectSid, String primaryGroupID, String userAttributeId,
        String groupAttributeName) throws UserStoreException {
    boolean debug = log.isDebugEnabled();

    List<String> list = new ArrayList<String>();
    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;

    if (debug) {
        log.debug("GetAttributeListOfOneElementWithPrimarGroup. SearchBase: " + searchBase + " SearchFilter: "
                + searchFilter);
    }
    try {
        dirContext = connectionSource.getContext();
        answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);
        int count = 0;
        while (answer.hasMore()) {
            if (count > 0) {
                log.error("More than element user exist with name");
                throw new UserStoreException("More than element user exist with name");
            }
            SearchResult sr = (SearchResult) answer.next();
            count++;

            list = parseSearchResult(sr, groupAttributeName);

            String primaryGroupSID = LDAPUtil.getPrimaryGroupSID(sr, objectSid, primaryGroupID);
            String primaryGroupName = LDAPUtil.findGroupBySID(dirContext, searchBase, primaryGroupSID,
                    userAttributeId);
            if (primaryGroupName != null) {
                list.add(primaryGroupName);
            }
        }

    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error occurred while GetAttributeListOfOneElementWithPrimarGroup. SearchBase: "
                + searchBase + " SearchFilter: " + searchFilter;
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage(), e);
        }
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }

    if (debug) {
        log.debug("GetAttributeListOfOneElementWithPrimarGroup. SearchBase: " + searchBase + " SearchFilter: "
                + searchFilter);
        Iterator<String> ite = list.iterator();
        while (ite.hasNext()) {
            log.debug("result: " + ite.next());
        }
    }
    return list;
}