Example usage for javax.naming.ldap Control NONCRITICAL

List of usage examples for javax.naming.ldap Control NONCRITICAL

Introduction

In this page you can find the example usage for javax.naming.ldap Control NONCRITICAL.

Prototype

boolean NONCRITICAL

To view the source code for javax.naming.ldap Control NONCRITICAL.

Click Source Link

Document

Indicates a non-critical control.

Usage

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

private void goUpGroupHierarchyLdap(Set<String> groupDNs, int groupHierarchyLevels) throws Throwable {
    if (groupHierarchyLevels <= 0 || groupDNs.isEmpty()) {
        return;/* w w w. ja v a  2  s . c  o  m*/
    }
    Set<String> nextLevelGroups = new HashSet<String>();

    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    try {
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        String groupFilter = "(&(objectclass=" + groupObjectClass + ")";
        if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) {
            String customFilter = groupSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }
            groupFilter += customFilter + "(|";
        }
        StringBuilder filter = new StringBuilder();

        for (String groupDN : groupDNs) {
            filter.append("(").append(groupMemberAttributeName).append("=").append(groupDN).append(")");
        }
        filter.append("))");
        groupFilter += filter;

        LOG.info("extendedAllGroupsSearchFilter = " + groupFilter);
        for (int ou = 0; ou < groupSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                do {
                    groupSearchResultEnum = ldapContext.search(groupSearchBase[ou], groupFilter,
                            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;
                        }
                        nextLevelGroups.add(groupEntry.getNameInNamespace());
                        String gName = (String) groupNameAttr.get();

                        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++;
                            originalUserFullName = originalUserFullName.toLowerCase();
                            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) {
                        ldapContext.setRequestControls(new Control[] {
                                new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() completed with group count: "
                        + counter);
            } catch (RuntimeException re) {
                LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with runtime exception: ",
                        re);
                throw re;
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", t);
                LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() group count: " + counter);
            }
        }

    } catch (RuntimeException re) {
        LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", re);
        throw re;
    } finally {
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
        closeLdapContext();
    }
    goUpGroupHierarchyLdap(nextLevelGroups, groupHierarchyLevels - 1);
}

From source file:org.apache.zeppelin.realm.LdapRealm.java

protected Set<String> rolesFor(PrincipalCollection principals, String userNameIn, final LdapContext ldapCtx,
        final LdapContextFactory ldapContextFactory, Session session) throws NamingException {
    final Set<String> roleNames = new HashSet<>();
    final Set<String> groupNames = new HashSet<>();
    final String userName;
    if (getUserLowerCase()) {
        log.debug("userLowerCase true");
        userName = userNameIn.toLowerCase();
    } else {/* w  w w .ja v a2s.  co  m*/
        userName = userNameIn;
    }

    String userDn = getUserDnForSearch(userName);

    // Activate paged results
    int pageSize = getPagingSize();
    if (log.isDebugEnabled()) {
        log.debug("Ldap PagingSize: " + pageSize);
    }
    int numResults = 0;
    byte[] cookie = null;
    try {
        ldapCtx.addToEnvironment(Context.REFERRAL, "ignore");

        ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });

        do {
            // ldapsearch -h localhost -p 33389 -D
            // uid=guest,ou=people,dc=hadoop,dc=apache,dc=org -w guest-password
            // -b dc=hadoop,dc=apache,dc=org -s sub '(objectclass=*)'
            NamingEnumeration<SearchResult> searchResultEnum = null;
            SearchControls searchControls = getGroupSearchControls();
            try {
                if (groupSearchEnableMatchingRuleInChain) {
                    searchResultEnum = ldapCtx.search(getGroupSearchBase(), String
                            .format(MATCHING_RULE_IN_CHAIN_FORMAT, groupObjectClass, memberAttribute, userDn),
                            searchControls);
                    while (searchResultEnum != null && searchResultEnum.hasMore()) {
                        // searchResults contains all the groups in search scope
                        numResults++;
                        final SearchResult group = searchResultEnum.next();

                        Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
                        String groupName = attribute.get().toString();

                        String roleName = roleNameFor(groupName);
                        if (roleName != null) {
                            roleNames.add(roleName);
                        } else {
                            roleNames.add(groupName);
                        }
                    }
                } else {
                    // Default group search filter
                    String searchFilter = String.format("(objectclass=%1$s)", groupObjectClass);

                    // If group search filter is defined in Shiro config, then use it
                    if (groupSearchFilter != null) {
                        searchFilter = expandTemplate(groupSearchFilter, userName);
                        //searchFilter = String.format("%1$s", groupSearchFilter);
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Group SearchBase|SearchFilter|GroupSearchScope: " + getGroupSearchBase()
                                + "|" + searchFilter + "|" + groupSearchScope);
                    }
                    searchResultEnum = ldapCtx.search(getGroupSearchBase(), searchFilter, searchControls);
                    while (searchResultEnum != null && searchResultEnum.hasMore()) {
                        // searchResults contains all the groups in search scope
                        numResults++;
                        final SearchResult group = searchResultEnum.next();
                        addRoleIfMember(userDn, group, roleNames, groupNames, ldapContextFactory);
                    }
                }
            } catch (PartialResultException e) {
                log.debug("Ignoring PartitalResultException");
            } finally {
                if (searchResultEnum != null) {
                    searchResultEnum.close();
                }
            }
            // Re-activate paged results
            ldapCtx.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
        } while (cookie != null);
    } catch (SizeLimitExceededException e) {
        log.info("Only retrieved first " + numResults + " groups due to SizeLimitExceededException.");
    } catch (IOException e) {
        log.error("Unabled to setup paged results");
    }
    // save role names and group names in session so that they can be
    // easily looked up outside of this object
    session.setAttribute(SUBJECT_USER_ROLES, roleNames);
    session.setAttribute(SUBJECT_USER_GROUPS, groupNames);
    if (!groupNames.isEmpty() && (principals instanceof MutablePrincipalCollection)) {
        ((MutablePrincipalCollection) principals).addAll(groupNames, getName());
    }
    if (log.isDebugEnabled()) {
        log.debug("User RoleNames: " + userName + "::" + roleNames);
    }
    return roleNames;
}

From source file:org.olat.ldap.LDAPLoginManagerImpl.java

private void searchInLdap(final LdapVisitor visitor, final String filter, final String[] returningAttrs,
        final LdapContext ctx) {
    final SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(returningAttrs);
    ctls.setCountLimit(0); // set no limits

    final boolean paging = isPagedResultControlSupported(ctx);
    for (final String ldapBase : LDAPLoginModule.getLdapBases()) {
        int counter = 0;
        try {/*from  ww w  . j  a  v a 2s  .co  m*/
            if (paging) {
                byte[] cookie = null;
                ctx.setRequestControls(
                        new Control[] { new PagedResultsControl(PAGE_SIZE, Control.NONCRITICAL) });
                do {
                    final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls);
                    while (enm.hasMore()) {
                        visitor.visit(enm.next());
                    }
                    cookie = getCookie(ctx);
                } while (cookie != null);
            } else {
                final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls);
                while (enm.hasMore()) {
                    visitor.visit(enm.next());
                }
                counter++;
            }
        } catch (final SizeLimitExceededException e) {
            logError("SizeLimitExceededException after " + counter
                    + " records when getting all users from LDAP, reconfigure your LDAP server, hints: http://www.ldapbrowser.com/forum/viewtopic.php?t=14",
                    null);
        } catch (final NamingException e) {
            logError("NamingException when trying to fetch deleted users from LDAP using ldapBase::" + ldapBase
                    + " on row::" + counter, e);
        } catch (final Exception e) {
            logError("Exception when trying to fetch deleted users from LDAP using ldapBase::" + ldapBase
                    + " on row::" + counter, e);
        }
    }
}