Search in sources :

Example 26 with SearchResult

use of javax.naming.directory.SearchResult in project ranger by apache.

the class UserSync method findBasicGroupProperties.

private void findBasicGroupProperties(LdapContext ldapContext) throws Throwable {
    int noOfGroups;
    Attribute groupNameAttr;
    String groupBase;
    String groupFilter;
    Attribute groupMemberAttr;
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    SearchControls groupSearchControls = new SearchControls();
    groupSearchControls.setSearchScope(config.getGroupSearchScope());
    try {
        if (groupName == null || groupName.isEmpty()) {
            groupSearchResultEnum = ldapContext.search(searchBase, null);
        } else {
            int baseIndex = groupName.indexOf(",");
            groupBase = groupName.substring(baseIndex + 1);
            groupFilter = groupName.substring(0, baseIndex);
            groupSearchResultEnum = ldapContext.search(groupBase, groupFilter, groupSearchControls);
        }
        noOfGroups = 0;
        while (groupSearchResultEnum.hasMore()) {
            if (noOfGroups >= 1) {
                break;
            }
            final SearchResult groupEntry = groupSearchResultEnum.next();
            if (groupEntry == null) {
                continue;
            }
            Attributes groupAttributes = groupEntry.getAttributes();
            if (groupAttributes == null) {
                logFile.println("WARN: Attributes missing for entry " + groupEntry.getNameInNamespace());
                continue;
            }
            Attribute groupObjClassAttr = groupAttributes.get("objectClass");
            if (groupObjClassAttr != null) {
                NamingEnumeration<?> groupObjClassEnum = groupObjClassAttr.getAll();
                while (groupObjClassEnum.hasMore()) {
                    String groupObjClassStr = groupObjClassEnum.next().toString();
                    for (int i = 0; i < groupObjectClassValues.length; i++) {
                        if (groupObjClassStr.equalsIgnoreCase(groupObjectClassValues[i])) {
                            groupObjClassName = groupObjClassStr;
                            break;
                        }
                    }
                }
            } else {
                logFile.println("WARN: Failed to find group objectClass attribute for " + groupEntry.getNameInNamespace());
                continue;
            }
            if (groupNameAttrName == null || groupNameAttrName.isEmpty()) {
                for (int i = 0; i < groupNameAttrValues.length; i++) {
                    groupNameAttr = groupAttributes.get(groupNameAttrValues[i]);
                    if (groupNameAttr != null) {
                        groupNameAttrName = groupNameAttrValues[i];
                        break;
                    }
                }
            }
            for (int i = 0; i < groupMemAttrValues.length; i++) {
                groupMemberAttr = groupAttributes.get(groupMemAttrValues[i]);
                if (groupMemberAttr != null) {
                    groupMemberName = groupMemAttrValues[i];
                    break;
                }
            }
            noOfGroups++;
        }
        installProps.println("\n# Possible values for group search related properties:");
        installProps.println("SYNC_GROUP_MEMBER_ATTRIBUTE_NAME=" + groupMemberName);
        installProps.println("SYNC_GROUP_NAME_ATTRIBUTE=" + groupNameAttrName);
        installProps.println("SYNC_GROUP_OBJECT_CLASS=" + groupObjClassName);
        ambariProps.println("\n# Possible values for group search related properties:");
        ambariProps.println("ranger.usersync.group.memberattributename=" + groupMemberName);
        ambariProps.println("ranger.usersync.group.nameattribute=" + groupNameAttrName);
        ambariProps.println("ranger.usersync.group.objectclass=" + groupObjClassName);
    } finally {
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
    }
}
Also used : Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) SearchControls(javax.naming.directory.SearchControls)

Example 27 with SearchResult

use of javax.naming.directory.SearchResult in project ranger by apache.

the class UserSync method findAdvGroupProperties.

private void findAdvGroupProperties(LdapContext ldapContext) throws Throwable {
    int noOfGroups = 0;
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    SearchControls groupSearchControls = new SearchControls();
    groupSearchControls.setSearchScope(config.getGroupSearchScope());
    Set<String> groupSearchAttributes = new HashSet<>();
    groupSearchAttributes.add(groupNameAttrName);
    groupSearchAttributes.add(groupMemberName);
    groupSearchAttributes.add("distinguishedName");
    groupSearchControls.setReturningAttributes(groupSearchAttributes.toArray(new String[groupSearchAttributes.size()]));
    String extendedGroupSearchFilter = "(objectclass=" + groupObjClassName + ")";
    try {
        HashMap<String, Integer> ouOccurences = new HashMap<>();
        if (groupSearchBase == null || groupSearchBase.isEmpty()) {
            groupSearchResultEnum = ldapContext.search(searchBase, extendedGroupSearchFilter, groupSearchControls);
        } else {
            groupSearchResultEnum = ldapContext.search(groupSearchBase, extendedGroupSearchFilter, groupSearchControls);
        }
        while (groupSearchResultEnum.hasMore()) {
            if (noOfGroups >= 20) {
                break;
            }
            final SearchResult groupEntry = groupSearchResultEnum.next();
            if (groupEntry == null) {
                continue;
            }
            Attributes groupAttributes = groupEntry.getAttributes();
            if (groupAttributes == null) {
                logFile.println("WARN: Attributes missing for entry " + groupEntry.getNameInNamespace());
                continue;
            }
            String dnValue;
            Attribute dnAttr = groupAttributes.get("distinguishedName");
            if (dnAttr != null) {
                dnValue = dnAttr.get().toString();
                String ouStr = "OU=";
                int indexOfOU = dnValue.indexOf(ouStr);
                if (indexOfOU > 0) {
                    dnValue = dnValue.substring(indexOfOU);
                } else {
                    dnValue = dnValue.substring(dnValue.indexOf(",") + 1);
                }
            } else {
                // If distinguishedName is not found,
                // strip off the userName from the long name for OU or sub domain
                dnValue = groupEntry.getNameInNamespace();
                dnValue = dnValue.substring(dnValue.indexOf(",") + 1);
            }
            // System.out.println("OU from dn = " + dnValue);
            Integer ouOccrs = ouOccurences.get(dnValue);
            if (ouOccrs == null) {
                // System.out.println("value = 0");
                ouOccrs = Integer.valueOf(0);
            }
            int val = ouOccrs.intValue();
            ouOccrs = Integer.valueOf(++val);
            ouOccurences.put(dnValue, ouOccrs);
            noOfGroups++;
        }
        if (!ouOccurences.isEmpty()) {
            Set<String> keys = ouOccurences.keySet();
            int maxOUOccr = 0;
            for (String key : keys) {
                int ouOccurVal = ouOccurences.get(key).intValue();
                logFile.println("INFO: No. of groups from " + key + " = " + ouOccurVal);
                if (ouOccurVal > maxOUOccr) {
                    maxOUOccr = ouOccurVal;
                    groupSearchBase = key;
                }
            }
        }
        if (groupSearchFilter == null || groupSearchFilter.isEmpty()) {
            groupSearchFilter = groupNameAttrName + "=*";
        }
        installProps.println("SYNC_GROUP_SEARCH_BASE=" + groupSearchBase);
        installProps.println("SYNC_LDAP_GROUP_SEARCH_FILTER=" + groupSearchFilter);
        ambariProps.println("ranger.usersync.group.searchbase=" + groupSearchBase);
        ambariProps.println("ranger.usersync.group.searchfilter=" + groupSearchFilter);
    } finally {
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
    }
}
Also used : HashMap(java.util.HashMap) Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) SearchControls(javax.naming.directory.SearchControls) HashSet(java.util.HashSet)

Example 28 with SearchResult

use of javax.naming.directory.SearchResult in project ranger by apache.

the class UserSync method findBasicUserProperties.

/* Use the provided bind dn or the user search base and user search filter for sample user and determine the basic user attribute.
     */
private void findBasicUserProperties(LdapContext ldapContext, boolean isOutputNeeded) throws Throwable {
    String bindDn = config.getLdapBindDn();
    String userSFilter = config.getUserSearchFilter();
    String userSBase = config.getUserSearchBase();
    Attribute userNameAttr = null;
    Attribute groupMemberAttr;
    SearchControls userSearchControls = new SearchControls();
    userSearchControls.setSearchScope(config.getUserSearchScope());
    userSearchControls.setReturningAttributes(new java.lang.String[] { "*", "+" });
    int noOfUsers = 0;
    NamingEnumeration<SearchResult> userSearchResultEnum = null;
    try {
        if (userSBase == null || userSBase.isEmpty()) {
            if (bindDn.contains("@")) {
                userSBase = bindDn.substring(bindDn.indexOf("@") + 1);
                userSBase = "dc=".concat(userSBase);
                userSBase = userSBase.replaceAll("\\.", ",dc=");
            } else {
                // int dcIndex = bindDn.toLowerCase().indexOf("dc=");
                userSBase = bindDn.substring(bindDn.indexOf(",") + 1);
            }
        // System.out.println("Derived user search base = " + userSearchBase);
        }
        if (userSFilter == null || userSFilter.isEmpty()) {
            if (bindDn.contains("@")) {
                userSFilter = "userPrincipalName=" + bindDn;
            } else {
                int cnEndIndex = bindDn.indexOf(",");
                userSFilter = bindDn.substring(0, cnEndIndex);
            }
        // System.out.println("Derived user search filter = " + userSearchFilter);
        }
        try {
            userSearchResultEnum = ldapContext.search(userSBase, userSFilter, userSearchControls);
            while (userSearchResultEnum.hasMore()) {
                if (noOfUsers >= 5) {
                    break;
                }
                final SearchResult userEntry = userSearchResultEnum.next();
                if (userEntry == null) {
                    logFile.println("WARN: userEntry null");
                    continue;
                }
                Attributes attributes = userEntry.getAttributes();
                if (attributes == null) {
                    logFile.println("WARN: Attributes missing for entry " + userEntry.getNameInNamespace());
                    continue;
                }
                if (userNameAttribute == null || userNameAttribute.isEmpty()) {
                    for (int i = 0; i < userNameAttrValues.length; i++) {
                        userNameAttr = attributes.get(userNameAttrValues[i]);
                        if (userNameAttr != null) {
                            userNameAttribute = userNameAttrValues[i];
                            break;
                        }
                    }
                    if (userNameAttr == null) {
                        logFile.print("WARN: Failed to find any of ( ");
                        for (int i = 0; i < userNameAttrValues.length; i++) {
                            logFile.print(userNameAttrValues[i] + " ");
                        }
                        logFile.println(") for entry " + userEntry.getNameInNamespace());
                        continue;
                    }
                } else {
                    userNameAttr = attributes.get(userNameAttribute);
                    if (userNameAttr == null) {
                        logFile.println("WARN: Failed to find " + userNameAttribute + " for entry " + userEntry.getNameInNamespace());
                        continue;
                    }
                }
                String userName = (String) userNameAttr.get();
                if (userName == null || userName.trim().isEmpty()) {
                    logFile.println("WARN: " + userNameAttribute + " empty for entry " + userEntry.getNameInNamespace());
                    continue;
                }
                userName = userName.toLowerCase();
                Attribute userObjClassAttr = attributes.get("objectClass");
                NamingEnumeration<?> userObjClassEnum = userObjClassAttr.getAll();
                String userObjClass = null;
                while (userObjClassEnum.hasMore()) {
                    userObjClass = userObjClassEnum.next().toString();
                    if (userObjClassName == null || userObjClassName.isEmpty()) {
                        if (userObjClass != null) {
                            for (int i = 0; i < userObjClassValues.length; i++) {
                                if (userObjClass.equalsIgnoreCase(userObjClassValues[i])) {
                                    userObjClassName = userObjClass;
                                    break;
                                }
                            }
                        } else {
                            logFile.println("WARN: Failed to find objectClass attribute for " + userName);
                        // continue;
                        }
                    }
                }
                if (userObjClassName == null || userObjClassName.isEmpty()) {
                    userObjClassName = userObjClass;
                }
                for (int i = 0; i < userGroupMemAttrValues.length; i++) {
                    groupMemberAttr = attributes.get(userGroupMemAttrValues[i]);
                    if (groupMemberAttr != null) {
                        userGroupMemberName = userGroupMemAttrValues[i];
                        groupName = groupMemberAttr.get(0).toString();
                        break;
                    }
                }
                noOfUsers++;
            }
        } catch (NamingException ne) {
            String msg = "Exception occured while discovering basic user properties:\n" + "ranger.usersync.ldap.user.nameattribute\n" + "ranger.usersync.ldap.user.objectclass\n" + "ranger.usersync.ldap.user.groupnameattribute\n";
            if ((config.getUserSearchBase() != null && !config.getUserSearchBase().isEmpty()) || (config.getUserSearchFilter() != null && !config.getUserSearchFilter().isEmpty())) {
                throw new Exception(msg + "Please verify values for ranger.usersync.ldap.user.searchbase and ranger.usersync.ldap.user.searchfilter");
            } else {
                throw new Exception(msg + ne);
            }
        }
        if (isOutputNeeded) {
            installProps.println("# Possible values for user search related properties:");
            installProps.println("SYNC_LDAP_USER_NAME_ATTRIBUTE=" + userNameAttribute);
            installProps.println("SYNC_LDAP_USER_OBJECT_CLASS=" + userObjClassName);
            installProps.println("SYNC_LDAP_USER_GROUP_NAME_ATTRIBUTE=" + userGroupMemberName);
            ambariProps.println("# Possible values for user search related properties:");
            ambariProps.println("ranger.usersync.ldap.user.nameattribute=" + userNameAttribute);
            ambariProps.println("ranger.usersync.ldap.user.objectclass=" + userObjClassName);
            ambariProps.println("ranger.usersync.ldap.user.groupnameattribute=" + userGroupMemberName);
        }
    } finally {
        try {
            if (userSearchResultEnum != null) {
                userSearchResultEnum.close();
            }
        } catch (NamingException ne) {
            throw new Exception("Exception occured while closing user search result: " + ne);
        }
    }
}
Also used : Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) NamingException(javax.naming.NamingException)

Example 29 with SearchResult

use of javax.naming.directory.SearchResult in project ranger by apache.

the class UserSync method getAllUsers.

public void getAllUsers(LdapContext ldapContext) throws Throwable {
    int noOfUsers = 0;
    Attribute userNameAttr = null;
    // String groupName = null;
    Attribute groupMemberAttr = null;
    NamingEnumeration<SearchResult> userSearchResultEnum = null;
    SearchControls userSearchControls = new SearchControls();
    userSearchControls.setSearchScope(config.getUserSearchScope());
    Set<String> userSearchAttributes = new HashSet<>();
    if (userNameAttribute != null) {
        userSearchAttributes.add(userNameAttribute);
    }
    if (userGroupMemberName != null) {
        userSearchAttributes.add(userGroupMemberName);
    }
    if (userSearchAttributes.size() > 0) {
        userSearchControls.setReturningAttributes(userSearchAttributes.toArray(new String[userSearchAttributes.size()]));
    } else {
        userSearchControls.setReturningAttributes(new java.lang.String[] { "*", "+" });
    }
    String extendedUserSearchFilter = "(objectclass=" + userObjClassName + ")";
    if (userSearchFilter != null && !userSearchFilter.trim().isEmpty()) {
        String customFilter = userSearchFilter.trim();
        if (!customFilter.startsWith("(")) {
            customFilter = "(" + customFilter + ")";
        }
        extendedUserSearchFilter = "(&" + extendedUserSearchFilter + customFilter + ")";
    }
    byte[] cookie = null;
    logFile.println();
    logFile.println("INFO: First 20 Users and associated groups are:");
    try {
        do {
            userSearchResultEnum = ldapContext.search(userSearchBase, extendedUserSearchFilter, userSearchControls);
            while (userSearchResultEnum.hasMore()) {
                final SearchResult userEntry = userSearchResultEnum.next();
                if (userEntry == null) {
                    logFile.println("WARN: userEntry null");
                    continue;
                }
                Attributes attributes = userEntry.getAttributes();
                if (attributes == null) {
                    logFile.println("WARN: Attributes missing for entry " + userEntry.getNameInNamespace());
                    continue;
                }
                if (userNameAttribute == null || userNameAttribute.isEmpty()) {
                    for (int i = 0; i < userNameAttrValues.length; i++) {
                        userNameAttr = attributes.get(userNameAttrValues[i]);
                        if (userNameAttr != null) {
                            userNameAttribute = userNameAttrValues[i];
                            break;
                        }
                    }
                    if (userNameAttr == null) {
                        logFile.print("WARN: Failed to find any of ( ");
                        for (int i = 0; i < userNameAttrValues.length; i++) {
                            logFile.print(userNameAttrValues[i] + " ");
                        }
                        logFile.println(") for entry " + userEntry.getNameInNamespace());
                        continue;
                    }
                } else {
                    userNameAttr = attributes.get(userNameAttribute);
                    if (userNameAttr == null) {
                        logFile.println("WARN: Failed to find " + userNameAttribute + " for entry " + userEntry.getNameInNamespace());
                        continue;
                    }
                }
                String userName = userNameAttr.get().toString();
                if (userName == null || userName.trim().isEmpty()) {
                    logFile.println("WARN: " + userNameAttribute + " empty for entry " + userEntry.getNameInNamespace());
                    continue;
                }
                userName = userName.toLowerCase();
                Set<String> groups = new HashSet<>();
                groupMemberAttr = attributes.get(userGroupMemberName);
                if (groupMemberAttr != null) {
                    NamingEnumeration<?> groupEnum = groupMemberAttr.getAll();
                    while (groupEnum.hasMore()) {
                        String groupRes = groupEnum.next().toString();
                        groups.add(groupRes);
                        if (groupName == null || groupName.isEmpty()) {
                            groupName = groupRes;
                        }
                    }
                }
                if (noOfUsers < 20) {
                    logFile.println("Username: " + userName + ", Groups: " + groups);
                }
                noOfUsers++;
            }
            // 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];
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                logFile.println("WARN: No controls were sent from the server");
            }
            // Re-activate paged results
            if (config.isPagedResultsEnabled()) {
                ldapContext.setRequestControls(new Control[] { new PagedResultsControl(config.getPagedResultsSize(), cookie, Control.CRITICAL) });
            }
        } while (cookie != null);
        logFile.println("\nINFO: Total no. of users = " + noOfUsers);
    } catch (NamingException ne) {
        String msg = "Exception occured while retreiving users\n";
        if ((config.getUserNameAttribute() != null && !config.getUserNameAttribute().isEmpty()) || (config.getUserObjectClass() != null && !config.getUserObjectClass().isEmpty()) || (config.getGroupNameAttribute() != null && !config.getGroupNameAttribute().isEmpty()) || (config.getUserSearchBase() != null && !config.getUserSearchBase().isEmpty()) || (config.getUserSearchFilter() != null && !config.getUserSearchFilter().isEmpty())) {
            throw new Exception("Please verify values for:\n ranger.usersync.ldap.user.nameattribute\n " + "ranger.usersync.ldap.user.objectclass\n" + "ranger.usersync.ldap.user.groupnameattribute\n" + "ranger.usersync.ldap.user.searchbase\n" + "ranger.usersync.ldap.user.searchfilter\n");
        } else {
            throw new Exception(msg + ne);
        }
    } finally {
        if (userSearchResultEnum != null) {
            userSearchResultEnum.close();
        }
    }
}
Also used : Attribute(javax.naming.directory.Attribute) PagedResultsResponseControl(javax.naming.ldap.PagedResultsResponseControl) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) Control(javax.naming.ldap.Control) PagedResultsControl(javax.naming.ldap.PagedResultsControl) PagedResultsResponseControl(javax.naming.ldap.PagedResultsResponseControl) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException) HashSet(java.util.HashSet) PagedResultsControl(javax.naming.ldap.PagedResultsControl)

Example 30 with SearchResult

use of javax.naming.directory.SearchResult in project ranger by apache.

the class LdapDeltaUserGroupBuilder method getGroups.

private void getGroups(UserGroupSink sink) throws Throwable {
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
    long highestdeltaSyncGroupTime = deltaSyncGroupTime;
    try {
        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++;
                        noOfGroups++;
                        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);
                        // 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);
                                noOfUsers++;
                            }
                            // 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));
    }
}
Also used : Attribute(javax.naming.directory.Attribute) PagedResultsResponseControl(javax.naming.ldap.PagedResultsResponseControl) SearchResult(javax.naming.directory.SearchResult) Date(java.util.Date) InvalidNameException(javax.naming.InvalidNameException) Control(javax.naming.ldap.Control) PagedResultsControl(javax.naming.ldap.PagedResultsControl) PagedResultsResponseControl(javax.naming.ldap.PagedResultsResponseControl) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat) PagedResultsControl(javax.naming.ldap.PagedResultsControl)

Aggregations

SearchResult (javax.naming.directory.SearchResult)248 SearchControls (javax.naming.directory.SearchControls)146 NamingException (javax.naming.NamingException)113 Attributes (javax.naming.directory.Attributes)96 Attribute (javax.naming.directory.Attribute)86 ArrayList (java.util.ArrayList)75 LdapContext (javax.naming.ldap.LdapContext)39 NamingEnumeration (javax.naming.NamingEnumeration)36 DirContext (javax.naming.directory.DirContext)35 Test (org.junit.Test)32 BasicAttributes (javax.naming.directory.BasicAttributes)30 HashSet (java.util.HashSet)28 InitialDirContext (javax.naming.directory.InitialDirContext)27 InitialLdapContext (javax.naming.ldap.InitialLdapContext)23 PagedResultsControl (javax.naming.ldap.PagedResultsControl)22 HashMap (java.util.HashMap)20 IOException (java.io.IOException)19 BasicAttribute (javax.naming.directory.BasicAttribute)19 Control (javax.naming.ldap.Control)16 PagedResultsResponseControl (javax.naming.ldap.PagedResultsResponseControl)15