Example usage for javax.naming.ldap LdapContext setRequestControls

List of usage examples for javax.naming.ldap LdapContext setRequestControls

Introduction

In this page you can find the example usage for javax.naming.ldap LdapContext setRequestControls.

Prototype

public void setRequestControls(Control[] requestControls) throws NamingException;

Source Link

Document

Sets the request controls for methods subsequently invoked on this context.

Usage

From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java

public boolean hasNextPage(DirContext ctx, int pageSize) {
    if (pageSize > 0) {
        try {//from ww  w.  j  a v a2s . c o  m
            LdapContext ldapContext = (LdapContext) ctx;
            Control[] controls = ldapContext.getResponseControls();

            // Retrieve the paged result cookie if there is one
            if (controls != null) {
                for (Control control : controls) {
                    if (control instanceof PagedResultsResponseControl) {
                        byte[] cookie = ((PagedResultsResponseControl) control).getCookie();
                        if (cookie != null) {
                            // Prepare for next page
                            ldapContext.setRequestControls(new Control[] {
                                    new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
                            return true;
                        }
                    }
                }
            }
        } catch (NamingException nx) {
            throw new AuthenticationException("Unable to connect to LDAP Server; check LDAP configuration", nx);
        } catch (IOException e) {
            throw new AuthenticationException(
                    "Unable to encode LDAP v3 request controls; check LDAP configuration", e);
        }

    }
    return false;
}

From source file:org.apache.cloudstack.ldap.LdapUserManager.java

public List<LdapUser> searchUsers(final String username, final LdapContext context)
        throws NamingException, IOException {

    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }// w w  w  .  j  a  v  a  2 s  . c  om
    byte[] cookie = null;
    int pageSize = _ldapConfiguration.getLdapPageSize();
    context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
    final List<LdapUser> users = new ArrayList<LdapUser>();
    NamingEnumeration<SearchResult> results;
    do {
        results = context.search(basedn, generateSearchFilter(username), searchControls);
        while (results.hasMoreElements()) {
            final SearchResult result = results.nextElement();
            users.add(createUser(result));
        }
        Control[] contextControls = context.getResponseControls();
        if (contextControls != null) {
            for (Control control : contextControls) {
                if (control instanceof PagedResultsResponseControl) {
                    PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                    cookie = prrc.getCookie();
                }
            }
        } else {
            s_logger.info("No controls were sent from the ldap server");
        }
        context.setRequestControls(
                new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
    } while (cookie != null);

    return users;
}

From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java

@Override
public List<LdapUser> searchUsers(final String username, final LdapContext context)
        throws NamingException, IOException {

    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }/*from w  w w .  ja  v a  2s.c  o  m*/
    byte[] cookie = null;
    int pageSize = _ldapConfiguration.getLdapPageSize();
    context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
    final List<LdapUser> users = new ArrayList<LdapUser>();
    NamingEnumeration<SearchResult> results;
    do {
        results = context.search(basedn, generateSearchFilter(username), searchControls);
        while (results.hasMoreElements()) {
            final SearchResult result = results.nextElement();
            if (!isUserDisabled(result)) {
                users.add(createUser(result));
            }
        }
        Control[] contextControls = context.getResponseControls();
        if (contextControls != null) {
            for (Control control : contextControls) {
                if (control instanceof PagedResultsResponseControl) {
                    PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                    cookie = prrc.getCookie();
                }
            }
        } else {
            s_logger.info("No controls were sent from the ldap server");
        }
        context.setRequestControls(
                new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
    } while (cookie != null);

    return users;
}

From source file:org.apache.ranger.ldapconfigcheck.LdapConfigCheckMain.java

public static void main(String[] args) {

    CommandLineOptions cli = new CommandLineOptions(args);
    cli.parse();/*from ww  w  .  j ava2 s.com*/
    String inFileName = cli.getInput();
    String outputDir = cli.getOutput();
    if (!outputDir.endsWith("/")) {
        outputDir = outputDir.concat("/");
    }

    LdapConfig config = new LdapConfig(inFileName, cli.getBindPassword());
    if (cli.getLdapUrl() != null && !cli.getLdapUrl().isEmpty()) {
        config.updateInputPropFile(cli.getLdapUrl(), cli.getBindDn(), cli.getBindPassword(),
                cli.getUserSearchBase(), cli.getUserSearchFilter(), cli.getAuthUser(), cli.getAuthPass());
    }

    PrintStream logFile = null;
    PrintStream ambariProps = null;
    PrintStream installProps = null;
    LdapContext ldapContext = null;

    try {
        logFile = new PrintStream(new File(outputDir + LOG_FILE));
        ambariProps = new PrintStream(new File(outputDir + AMBARI_PROPERTIES));
        installProps = new PrintStream(new File(outputDir + INSTALL_PROPERTIES));

        UserSync userSyncObj = new UserSync(config, logFile, ambariProps, installProps);

        String bindDn = config.getLdapBindDn();

        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, config.getLdapUrl());
        env.put(Context.SECURITY_PRINCIPAL, bindDn);
        env.put(Context.SECURITY_CREDENTIALS, cli.getBindPassword());
        env.put(Context.SECURITY_AUTHENTICATION, config.getLdapAuthenticationMechanism());
        env.put(Context.REFERRAL, "follow");

        ldapContext = new InitialLdapContext(env, null);

        if (config.isPagedResultsEnabled()) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(config.getPagedResultsSize(), Control.CRITICAL) });
        }

        String retrieveValues = "all";

        if (cli.getDiscoverProperties() != null) {
            retrieveValues = cli.getDiscoverProperties();
            if (cli.getDiscoverProperties().equalsIgnoreCase("users")) {
                userSyncObj.findUserProperties(ldapContext);
            } else if (cli.getDiscoverProperties().equalsIgnoreCase("groups")) {
                userSyncObj.findGroupProperties(ldapContext);
            } else {
                findAllUserSyncProperties(ldapContext, userSyncObj);
            }
        } else if (cli.getRetrieveValues() != null) {
            retrieveValues = cli.getRetrieveValues();

        } else {
            cli.help();
        }

        if (cli.isAuthEnabled()) {
            authenticate(userSyncObj, config, logFile, ambariProps, installProps);
        }

        retrieveUsersGroups(ldapContext, userSyncObj, retrieveValues);

        if (ldapContext != null) {
            ldapContext.close();
        }

    } catch (FileNotFoundException fe) {
        System.out.println(fe.getMessage());
    } catch (IOException ioe) {
        logFile.println("ERROR: Failed while setting the paged results controls\n" + ioe);
    } catch (NamingException ne) {
        System.out.println("ERROR: Failed to perfom ldap bind. Please verify values for "
                + "ranger.usersync.ldap.binddn and ranger.usersync.ldap.ldapbindpassword\n" + ne);
    } catch (Throwable t) {
        if (logFile != null) {
            logFile.println("ERROR: Connection failed: " + t.getMessage());
        } else {
            System.out.println("ERROR: Connection failed: " + t.getMessage());
        }
    } finally {
        if (logFile != null) {
            logFile.close();
        }
        if (ambariProps != null) {
            ambariProps.close();
        }
        if (installProps != null) {
            installProps.close();
        }
        try {
            if (ldapContext != null) {
                ldapContext.close();
            }
        } catch (NamingException ne) {
            System.out.println("Failed to close LdapContext!");
        }
    }
}

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 {/*from  www .j  a v  a 2s  .  c  om*/
        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 {/* ww w. ja v a2s  .c  o 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);
        }
    }
}

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();
            }//from ww  w.j a v a2  s . c om
        }
    }
    // Re-activate paged results
    ctx.setRequestControls(new Control[] { new PagedResultsControl(PAGE_SIZE, cookie, Control.CRITICAL) });
    return cookie;
}

From source file:org.springframework.ldap.control.AbstractRequestControlDirContextProcessor.java

/**
 * Get the existing RequestControls from the LdapContext, call
 * {@link #createRequestControl()} to get a new instance, build a new array
 * of Controls and set it on the LdapContext.
 * <p>/*from   ww w. j  a  v  a 2s. c  o m*/
 * The {@link Control} feature is specific for LDAP v3 and thus applies only
 * to {@link LdapContext}. However, the generic DirContextProcessor
 * mechanism used for calling <code>preProcess</code> and
 * <code>postProcess</code> uses DirContext, since it also works for LDAP
 * v2. This is the reason that DirContext has to be cast to a LdapContext.
 * 
 * @param ctx an LdapContext instance.
 * @throws NamingException
 * @throws IllegalArgumentException if the supplied DirContext is not an
 * LdapContext.
 */
public void preProcess(DirContext ctx) throws NamingException {
    LdapContext ldapContext;
    if (ctx instanceof LdapContext) {
        ldapContext = (LdapContext) ctx;
    } else {
        throw new IllegalArgumentException(
                "Request Control operations require LDAPv3 - " + "Context must be of type LdapContext");
    }

    Control[] requestControls = ldapContext.getRequestControls();
    if (requestControls == null) {
        requestControls = new Control[0];
    }
    Control newControl = createRequestControl();

    Control[] newControls = new Control[requestControls.length + 1];
    for (int i = 0; i < requestControls.length; i++) {
        if (replaceSameControlEnabled && requestControls[i].getClass() == newControl.getClass()) {
            log.debug("Replacing already existing control in context: " + newControl);
            requestControls[i] = newControl;
            ldapContext.setRequestControls(requestControls);
            return;
        }
        newControls[i] = requestControls[i];
    }

    // Add the new Control at the end of the array.
    newControls[newControls.length - 1] = newControl;

    ldapContext.setRequestControls(newControls);
}