Example usage for javax.naming.directory SearchControls setReturningAttributes

List of usage examples for javax.naming.directory SearchControls setReturningAttributes

Introduction

In this page you can find the example usage for javax.naming.directory SearchControls setReturningAttributes.

Prototype

public void setReturningAttributes(String[] attrs) 

Source Link

Document

Specifies the attributes that will be returned as part of the search.

Usage

From source file:org.apache.zeppelin.rest.GetUserList.java

/**
 * function to extract users from LDAP//from  w  ww .j av a2  s .c  o  m
 */
public List<String> getUserList(JndiLdapRealm r, String searchText) {
    List<String> userList = new ArrayList<>();
    String userDnTemplate = r.getUserDnTemplate();
    String userDn[] = userDnTemplate.split(",", 2);
    String userDnPrefix = userDn[0].split("=")[0];
    String userDnSuffix = userDn[1];
    JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
    try {
        LdapContext ctx = CF.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userDnPrefix };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userDnPrefix) != null) {
                String currentUser = attrs.get(userDnPrefix).toString();
                userList.add(currentUser.split(":")[1].trim());
            }
        }
    } catch (Exception e) {
        LOG.error("Error retrieving User list from Ldap Realm", e);
    }
    LOG.info("UserList: " + userList);
    return userList;
}

From source file:org.apache.zeppelin.rest.GetUserList.java

/**
 * function to extract users from Zeppelin LdapRealm
 *///from  w  ww. ja va 2  s. c o m
public List<String> getUserList(LdapRealm r, String searchText) {
    List<String> userList = new ArrayList<>();
    if (LOG.isDebugEnabled()) {
        LOG.debug("SearchText: " + searchText);
    }
    String userAttribute = r.getUserSearchAttributeName();
    String userSearchRealm = r.getUserSearchBase();
    String userObjectClass = r.getUserObjectClass();
    JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
    try {
        LdapContext ctx = CF.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userAttribute };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userSearchRealm,
                "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=" + searchText + "))",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userAttribute) != null) {
                String currentUser;
                if (r.getUserLowerCase()) {
                    LOG.debug("userLowerCase true");
                    currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
                } else {
                    LOG.debug("userLowerCase false");
                    currentUser = (String) attrs.get(userAttribute).get();
                }
                if (LOG.isDebugEnabled()) {
                    LOG.debug("CurrentUser: " + currentUser);
                }
                userList.add(currentUser.trim());
            }
        }
    } catch (Exception e) {
        LOG.error("Error retrieving User list from Ldap Realm", e);
    }
    return userList;
}

From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java

/** Function to extract users from LDAP. */
private List<String> getUserList(JndiLdapRealm r, String searchText, int numUsersToFetch) {
    List<String> userList = new ArrayList<>();
    String userDnTemplate = r.getUserDnTemplate();
    String userDn[] = userDnTemplate.split(",", 2);
    String userDnPrefix = userDn[0].split("=")[0];
    String userDnSuffix = userDn[1];
    JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
    try {//from w  ww . ja v a 2 s  . c om
        LdapContext ctx = cf.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setCountLimit(numUsersToFetch);
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userDnPrefix };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userDnPrefix) != null) {
                String currentUser = attrs.get(userDnPrefix).toString();
                userList.add(currentUser.split(":")[1].trim());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error retrieving User list from Ldap Realm", e);
    }
    LOGGER.info("UserList: " + userList);
    return userList;
}

From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java

/** Function to extract users from Zeppelin LdapRealm. */
private List<String> getUserList(LdapRealm r, String searchText, int numUsersToFetch) {
    List<String> userList = new ArrayList<>();
    LOGGER.debug("SearchText: " + searchText);
    String userAttribute = r.getUserSearchAttributeName();
    String userSearchRealm = r.getUserSearchBase();
    String userObjectClass = r.getUserObjectClass();
    JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
    try {//from w ww. j a  v a  2  s.  com
        LdapContext ctx = cf.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        constraints.setCountLimit(numUsersToFetch);
        String[] attrIDs = { userAttribute };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userSearchRealm,
                "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=*" + searchText + "*))",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userAttribute) != null) {
                String currentUser;
                if (r.getUserLowerCase()) {
                    LOGGER.debug("userLowerCase true");
                    currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
                } else {
                    LOGGER.debug("userLowerCase false");
                    currentUser = (String) attrs.get(userAttribute).get();
                }
                LOGGER.debug("CurrentUser: " + currentUser);
                userList.add(currentUser.trim());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error retrieving User list from Ldap Realm", e);
    }
    return userList;
}

From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java

public EntityIdentifier[] searchForEntities(String query, int method, Class type) throws GroupsException {
    if (type != group && type != iperson)
        return new EntityIdentifier[0];
    // Guarantee that LDAP injection is prevented by replacing LDAP special characters
    // with escaped versions of the character
    query = LdapEncoder.filterEncode(query);
    ArrayList ids = new ArrayList();
    switch (method) {
    case STARTS_WITH:
        query = query + "*";
        break;/*from www .j  a  v  a  2  s.c o m*/
    case ENDS_WITH:
        query = "*" + query;
        break;
    case CONTAINS:
        query = "*" + query + "*";
        break;
    }
    query = namefield + "=" + query;
    DirContext context = getConnection();
    NamingEnumeration userlist = null;
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { keyfield });
    try {
        userlist = context.search(usercontext, query, sc);
        ArrayList keys = new ArrayList();
        processLdapResults(userlist, keys);
        String[] k = (String[]) keys.toArray(new String[0]);
        for (int i = 0; i < k.length; i++) {
            ids.add(new EntityIdentifier(k[i], iperson));
        }
        return (EntityIdentifier[]) ids.toArray(new EntityIdentifier[0]);
    } catch (NamingException nex) {
        throw new GroupsException("LDAPGroupStore: Unable to perform filter " + query, nex);
    }
}

From source file:org.ballerinalang.auth.ldap.nativeimpl.GetLdapScopesOfUser.java

private String[] getLDAPGroupsListOfUser(String userName, List<String> searchBase,
        CommonLdapConfiguration ldapAuthConfig) throws UserStoreException, NamingException {
    if (userName == null) {
        throw new BallerinaException("userName value is null.");
    }//from w  w  w.j a  v a  2 s .  c o  m

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    // Load normal roles with the user
    String searchFilter = ldapAuthConfig.getGroupNameListFilter();
    String roleNameProperty = ldapAuthConfig.getGroupNameAttribute();
    String membershipProperty = ldapAuthConfig.getMembershipAttribute();
    String nameInSpace = this.getNameInSpaceForUserName(userName, ldapConfiguration);

    if (membershipProperty == null || membershipProperty.length() < 1) {
        throw new BallerinaException("membershipAttribute not set in configuration");
    }

    String membershipValue;
    if (nameInSpace != null) {
        LdapName ldn = new LdapName(nameInSpace);
        if (LdapConstants.MEMBER_UID.equals(ldapAuthConfig.getMembershipAttribute())) {
            // membership value of posixGroup is not DN of the user
            List rdns = ldn.getRdns();
            membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString();
        } else {
            membershipValue = escapeLdapNameForFilter(ldn);
        }
    } else {
        return new String[0];
    }

    searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))";
    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Reading roles with the membershipProperty Property: " + membershipProperty);
    }

    List<String> list = this.getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty, false);
    return list.toArray(new String[list.size()]);
}

From source file:org.ballerinalang.stdlib.ldap.nativeimpl.GetLdapScopesOfUser.java

private static String[] getLDAPGroupsListOfUser(String userName, List<String> searchBase,
        CommonLdapConfiguration ldapAuthConfig, DirContext ldapConnectionContext)
        throws UserStoreException, NamingException {
    if (userName == null) {
        throw new BallerinaException("userName value is null.");
    }//  w  w  w. j  a v  a2  s.  c o m

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    // Load normal roles with the user
    String searchFilter = ldapAuthConfig.getGroupNameListFilter();
    String roleNameProperty = ldapAuthConfig.getGroupNameAttribute();
    String membershipProperty = ldapAuthConfig.getMembershipAttribute();
    String nameInSpace = getNameInSpaceForUserName(userName, ldapAuthConfig, ldapConnectionContext);

    if (membershipProperty == null || membershipProperty.length() < 1) {
        throw new BallerinaException("membershipAttribute not set in configuration");
    }

    String membershipValue;
    if (nameInSpace != null) {
        LdapName ldn = new LdapName(nameInSpace);
        if (LdapConstants.MEMBER_UID.equals(ldapAuthConfig.getMembershipAttribute())) {
            // membership value of posixGroup is not DN of the user
            List rdns = ldn.getRdns();
            membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString();
        } else {
            membershipValue = escapeLdapNameForFilter(ldn);
        }
    } else {
        return new String[0];
    }

    searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))";
    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Reading roles with the membershipProperty Property: " + membershipProperty);
    }

    List<String> list = getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty,
            ldapConnectionContext);
    return list.toArray(new String[list.size()]);
}

From source file:org.beangle.security.ldap.connect.SimpleLdapUserStore.java

public String getUserDN(String uid) {
    DirContext ctx = getContext();
    if (ctx == null)
        return null;
    String result = null;//from  w  w w.  j  a v a2  s.co m
    String condition = StrUtils.concat(uidName, "=", uid);
    try {
        String attrList[] = { uidName };
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(2);
        constraints.setReturningAttributes(attrList);
        NamingEnumeration<SearchResult> results = ctx.search(base, condition, constraints);
        if (results.hasMore()) {
            SearchResult si = results.next();
            result = StrUtils.concat(si.getName(), ",", base);
        }
        results.close();
        results = null;
    } catch (Throwable e) {
        logger.error("Ldap search error,uid=" + uid, e);
    }
    return result;
}

From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java

/**
 * Performs an LDAP compare operation of the value of an attribute for a particular directory entry.
 *
 * @param dn the entry who's attribute is to be used
 * @param attributeName the attribute who's value we want to compare
 * @param value the value to be checked against the directory value
 *
 * @return true if the supplied value matches that in the directory
 *///from  w w w. j av a 2  s .c  o m
public boolean compare(final String dn, final String attributeName, final Object value) {
    final String comparisonFilter = "(" + attributeName + "={0})";

    class LdapCompareCallback implements ContextExecutor {

        public Object executeWithContext(DirContext ctx) throws NamingException {
            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(NO_ATTRS);
            ctls.setSearchScope(SearchControls.OBJECT_SCOPE);

            NamingEnumeration<SearchResult> results = ctx.search(dn, comparisonFilter, new Object[] { value },
                    ctls);

            Boolean match = Boolean.valueOf(results.hasMore());
            LdapUtils.closeEnumeration(results);

            return match;
        }
    }

    Boolean matches = (Boolean) executeReadOnly(new LdapCompareCallback());

    return matches.booleanValue();
}

From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java

/**
 * Performs a search using the supplied filter and returns the values of each named attribute
 * found in all entries matched by the search. Note that one directory entry may have several values for the
 * attribute. Intended for role searches and similar scenarios.
 *
 * @param base the DN to search in/* ww  w.jav  a 2  s .  c  o m*/
 * @param filter search filter to use
 * @param params the parameters to substitute in the search filter
 * @param attributeNames the attributes' values that are to be retrieved.
 *
 * @return the set of String values for each attribute found in all the matching entries.
 * The attribute name is the key for each set of values. In addition each map contains the DN as a String
 * with the key predefined key {@link #DN_KEY}.
 */
public Set<Map<String, String[]>> searchForMultipleAttributeValues(final String base, final String filter,
        final Object[] params, final String[] attributeNames) {
    // Escape the params acording to RFC2254
    Object[] encodedParams = new String[params.length];

    for (int i = 0; i < params.length; i++) {
        encodedParams[i] = LdapEncoder.filterEncode(params[i].toString());
    }

    String formattedFilter = MessageFormat.format(filter, encodedParams);
    logger.debug("Using filter: " + formattedFilter);

    final HashSet<Map<String, String[]>> set = new HashSet<Map<String, String[]>>();

    ContextMapper roleMapper = new ContextMapper() {
        public Object mapFromContext(Object ctx) {
            DirContextAdapter adapter = (DirContextAdapter) ctx;
            Map<String, String[]> record = new HashMap<String, String[]>();
            for (String attributeName : attributeNames) {
                String[] values = adapter.getStringAttributes(attributeName);
                if (values == null || values.length == 0) {
                    logger.debug("No attribute value found for '" + attributeName + "'");
                } else {
                    record.put(attributeName, values);
                }
            }
            record.put(DN_KEY, new String[] { adapter.getDn().toString() });
            set.add(record);
            return null;
        }
    };

    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(searchControls.getSearchScope());
    ctls.setReturningAttributes(attributeNames);

    search(base, formattedFilter, ctls, roleMapper);

    return set;
}