Example usage for javax.naming.ldap Control CRITICAL

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

Introduction

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

Prototype

boolean CRITICAL

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

Click Source Link

Document

Indicates a 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;//from  w ww.j a  v  a2 s  .com
    }
    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  va2 s . c o 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.lsc.jndi.JndiServices.java

public Map<String, LscDatasets> doGetAttrsList(final String base, final String filter, final int scope,
        final List<String> attrsNames) throws NamingException {

    // sanity checks
    String searchBase = base == null ? "" : rewriteBase(base);
    String searchFilter = filter == null ? DEFAULT_FILTER : filter;

    Map<String, LscDatasets> res = new LinkedHashMap<String, LscDatasets>();

    if (attrsNames == null || attrsNames.size() == 0) {
        LOGGER.error("No attribute names to read! Check configuration.");
        return res;
    }//from  w w w . j  a  va2s  . c o  m

    String[] attributes = new String[attrsNames.size()];
    attributes = attrsNames.toArray(attributes);

    SearchControls constraints = new SearchControls();
    constraints.setDerefLinkFlag(false);
    constraints.setReturningAttributes(attributes);
    constraints.setSearchScope(scope);
    constraints.setReturningObjFlag(true);

    try {
        boolean requestPagedResults = false;

        List<Control> extControls = new ArrayList<Control>();

        if (pageSize > 0) {
            requestPagedResults = true;
            LOGGER.debug("Using pagedResults control for {} entries at a time", pageSize);
        }

        if (requestPagedResults) {
            extControls.add(new PagedResultsControl(pageSize, Control.CRITICAL));
        }

        if (sortedBy != null) {
            extControls.add(new SortControl(sortedBy, Control.CRITICAL));
        }

        if (extControls.size() > 0) {
            ctx.setRequestControls(extControls.toArray(new Control[extControls.size()]));
        }

        byte[] pagedResultsResponse = null;
        do {
            NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, constraints);

            if (results != null) {
                Map<String, Object> attrsValues = null;
                while (results.hasMoreElements()) {
                    attrsValues = new HashMap<String, Object>();

                    SearchResult ldapResult = (SearchResult) results.next();

                    // get the value for each attribute requested
                    for (String attributeName : attrsNames) {
                        Attribute attr = ldapResult.getAttributes().get(attributeName);
                        if (attr != null && attr.get() != null) {
                            attrsValues.put(attributeName, attr.get());
                        }
                    }

                    res.put(ldapResult.getNameInNamespace(), new LscDatasets(attrsValues));
                }
            }

            Control[] respCtls = ctx.getResponseControls();
            if (respCtls != null) {
                for (Control respCtl : respCtls) {
                    if (requestPagedResults && respCtl instanceof PagedResultsResponseControl) {
                        pagedResultsResponse = ((PagedResultsResponseControl) respCtl).getCookie();
                    }
                }
            }

            if (requestPagedResults && pagedResultsResponse != null) {
                ctx.setRequestControls(new Control[] {
                        new PagedResultsControl(pageSize, pagedResultsResponse, Control.CRITICAL) });
            }

        } while (pagedResultsResponse != null);

        // clear requestControls for future use of the JNDI context
        if (requestPagedResults) {
            ctx.setRequestControls(null);
        }
    } catch (CommunicationException e) {
        // Avoid handling the communication exception as a generic one
        throw e;
    } catch (ServiceUnavailableException e) {
        // Avoid handling the service unavailable exception as a generic one
        throw e;
    } catch (NamingException e) {
        // clear requestControls for future use of the JNDI context
        ctx.setRequestControls(null);
        LOGGER.error(e.toString());
        LOGGER.debug(e.toString(), e);

    } catch (IOException e) {
        // clear requestControls for future use of the JNDI context
        ctx.setRequestControls(null);
        LOGGER.error(e.toString());
        LOGGER.debug(e.toString(), e);
    }
    return res;
}

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

private byte[] getCookie(final LdapContext ctx) throws NamingException, IOException {
    byte[] cookie = null;
    // Examine the paged results control response
    final Control[] controls = ctx.getResponseControls();
    if (controls != null) {
        for (int i = 0; i < controls.length; i++) {
            if (controls[i] instanceof PagedResultsResponseControl) {
                final PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                cookie = prrc.getCookie();
            }// w  w w. j a v a 2s.  c om
        }
    }
    // Re-activate paged results
    ctx.setRequestControls(new Control[] { new PagedResultsControl(PAGE_SIZE, cookie, Control.CRITICAL) });
    return cookie;
}