Example usage for javax.naming.ldap LdapContext search

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

Introduction

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

Prototype

public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes,
        String[] attributesToReturn) throws NamingException;

Source Link

Document

Searches in a single context for objects that contain a specified set of attributes, and retrieves selected attributes.

Usage

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java

@Override
public User importUser(long ldapServerId, long companyId, String emailAddress, String screenName)
        throws Exception {

    LdapContext ldapContext = null;

    NamingEnumeration<SearchResult> enu = null;

    try {/* w  w w .j  a v  a2s  .  c  om*/
        LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider
                .getConfiguration(companyId, ldapServerId);

        String baseDN = ldapServerConfiguration.baseDN();

        ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

        if (ldapContext == null) {
            _log.error("Unable to bind to the LDAP server");

            return null;
        }

        String filter = ldapServerConfiguration.authSearchFilter();

        if (_log.isDebugEnabled()) {
            _log.debug("Search filter before transformation " + filter);
        }

        filter = StringUtil.replace(filter, new String[] { "@company_id@", "@email_address@", "@screen_name@" },
                new String[] { String.valueOf(companyId), emailAddress, screenName });

        LDAPUtil.validateFilter(filter);

        if (_log.isDebugEnabled()) {
            _log.debug("Search filter after transformation " + filter);
        }

        Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);

        String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName"));

        userMappingsScreenName = StringUtil.toLowerCase(userMappingsScreenName);

        SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0,
                new String[] { userMappingsScreenName }, false, false);

        enu = ldapContext.search(baseDN, filter, searchControls);

        if (enu.hasMoreElements()) {
            if (_log.isDebugEnabled()) {
                _log.debug("Search filter returned at least one result");
            }

            Binding binding = enu.nextElement();

            Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext,
                    binding.getNameInNamespace());

            return importUser(ldapServerId, companyId, ldapContext, attributes, null);
        } else {
            return null;
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn("Problem accessing LDAP server " + e.getMessage());
        }

        if (_log.isDebugEnabled()) {
            _log.debug(e, e);
        }

        throw new SystemException("Problem accessing LDAP server " + e.getMessage());
    } finally {
        if (enu != null) {
            enu.close();
        }

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

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

@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException {
    if (StringUtils.isBlank(groupName)) {
        throw new IllegalArgumentException("ldap group name cannot be blank");
    }//from   w w w . j a v a2  s.c om

    String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }

    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    NamingEnumeration<SearchResult> results = context.search(basedn, generateADGroupSearchFilter(groupName),
            searchControls);
    final List<LdapUser> users = new ArrayList<LdapUser>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));
    }
    return users;
}

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

public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException {
    String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(new String[] { attributeName });

    NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(),
            generateGroupSearchFilter(groupName), controls);

    final List<LdapUser> users = new ArrayList<LdapUser>();
    //Expecting only one result which has all the users
    if (result.hasMoreElements()) {
        Attribute attribute = result.nextElement().getAttributes().get(attributeName);
        NamingEnumeration<?> values = attribute.getAll();

        while (values.hasMoreElements()) {
            String userdn = String.valueOf(values.nextElement());
            try {
                users.add(getUserForDn(userdn, context));
            } catch (NamingException e) {
                s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
            }//from w  ww . j ava2s.  c  o m
        }
    }

    Collections.sort(users);

    return users;
}

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

private LdapUser getUserForDn(String userdn, LdapContext context) throws NamingException {
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    NamingEnumeration<SearchResult> result = context.search(userdn,
            "(objectClass=" + _ldapConfiguration.getUserObject() + ")", controls);
    if (result.hasMoreElements()) {
        return createUser(result.nextElement());
    } else {//w  w w. j a v a2 s.  c o  m
        throw new NamingException("No user found for dn " + userdn);
    }
}

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");
    }/*from   w  ww .  j  a va  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();
            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> getUsersInGroup(String groupName, LdapContext context) throws NamingException {
    String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(new String[] { attributeName });

    NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(),
            generateGroupSearchFilter(groupName), controls);

    final List<LdapUser> users = new ArrayList<LdapUser>();
    //Expecting only one result which has all the users
    if (result.hasMoreElements()) {
        Attribute attribute = result.nextElement().getAttributes().get(attributeName);
        NamingEnumeration<?> values = attribute.getAll();

        while (values.hasMoreElements()) {
            String userdn = String.valueOf(values.nextElement());
            try {
                users.add(getUserForDn(userdn, context));
            } catch (NamingException e) {
                s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
            }/*ww  w .java2  s. c  o  m*/
        }
    }

    Collections.sort(users);

    return users;
}

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

public LdapUser searchUser(final String basedn, final String searchString, final LdapContext context)
        throws NamingException, IOException {
    final SearchControls searchControls = new SearchControls();

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

    NamingEnumeration<SearchResult> results = context.search(basedn, searchString, searchControls);
    final List<LdapUser> users = new ArrayList<LdapUser>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));/* w  w w  . ja v a 2 s  . com*/
    }

    if (users.size() == 1) {
        return users.get(0);
    } else {
        throw new NamingException("No user found for basedn " + basedn + " and searchString " + searchString);
    }
}

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  www  .j ava  2  s .com*/
    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.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

/**
 * Search./* w w w .  ja  va  2s.  c om*/
 * 
 * @param searchBase the search base
 * @param filter the filter
 * @param searchControls the controls
 * @param aliasesDereferencingMethod the aliases dereferencing method
 * @param referralsHandlingMethod the referrals handling method
 * @param controls the LDAP controls
 * @param monitor the progress monitor
 * @param referralsInfo the referrals info
 * 
 * @return the naming enumeration or null if an exception occurs.
 */
public JndiStudioNamingEnumeration search(final String searchBase, final String filter,
        final SearchControls searchControls, final AliasDereferencingMethod aliasesDereferencingMethod,
        final ReferralHandlingMethod referralsHandlingMethod, final Control[] controls,
        final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) {
    final long requestNum = searchRequestNum++;

    // start
    InnerRunnable runnable = new InnerRunnable() {
        public void run() {
            LdapContext searchCtx = context;
            try {
                // create the search context
                searchCtx = context.newInstance(controls);

                // translate alias dereferencing method
                searchCtx.addToEnvironment(JAVA_NAMING_LDAP_DEREF_ALIASES,
                        translateDerefAliasMethod(aliasesDereferencingMethod));

                // use "throw" as we handle referrals manually
                searchCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW);

                // perform the search
                NamingEnumeration<SearchResult> result = searchCtx
                        .search(JNDIConnectionWrapper.getSaveJndiName(searchBase), filter, searchControls);
                namingEnumeration = new JndiStudioNamingEnumeration(connection, searchCtx, result, null,
                        searchBase, filter, searchControls, aliasesDereferencingMethod, referralsHandlingMethod,
                        controls, requestNum, monitor, referralsInfo);
            } catch (PartialResultException | ReferralException e) {
                namingEnumeration = new JndiStudioNamingEnumeration(connection, searchCtx, null, e, searchBase,
                        filter, searchControls, aliasesDereferencingMethod, referralsHandlingMethod, controls,
                        requestNum, monitor, referralsInfo);
            } catch (NamingException e) {
                namingException = e;
            }

            for (IJndiLogger logger : getJndiLoggers()) {
                if (namingEnumeration != null) {
                    logger.logSearchRequest(connection, searchBase, filter, searchControls,
                            aliasesDereferencingMethod, controls, requestNum, namingException);
                } else {
                    logger.logSearchRequest(connection, searchBase, filter, searchControls,
                            aliasesDereferencingMethod, controls, requestNum, namingException);
                    logger.logSearchResultDone(connection, 0, requestNum, namingException);
                }
            }
        }
    };

    try {
        checkConnectionAndRunAndMonitor(runnable, monitor);
    } catch (NamingException ne) {
        monitor.reportError(ne);
        return null;
    }

    if (runnable.isCanceled()) {
        monitor.setCanceled(true);
    }
    if (runnable.getException() != null) {
        monitor.reportError(runnable.getException());
        return null;
    } else {
        return runnable.getResult();
    }
}

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 {/* ww  w.  ja v a 2 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;
}