Example usage for javax.naming.directory SearchControls setSearchScope

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

Introduction

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

Prototype

public void setSearchScope(int scope) 

Source Link

Document

Sets the search scope to one of: OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.

Usage

From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java

/**
 * @return true  = monitoring is enabled
 * @return false = monitoring is not enabled
 * @exception NamingException no conection
 *///from ww  w  . j a va2  s. c o  m
private boolean hasMonitoringEnabled(Metric metric) throws NamingException {
    NamingEnumeration enumer = null, enumerx = null, enumery = null;

    boolean res = false;
    try {
        String[] a = { "monitorContext" };
        SearchControls cons = new SearchControls();
        cons.setSearchScope(SearchControls.OBJECT_SCOPE);
        cons.setReturningAttributes(a);
        enumer = getDirContext(metric.getProperties()).search("", "(&(objectClass=*))", cons);
        while (enumer.hasMore() && !res) {
            SearchResult searchresult = (SearchResult) enumer.next();
            Attributes attrs = searchresult.getAttributes();
            enumerx = attrs.getIDs();
            while (enumerx.hasMore()) {
                String id = (String) enumerx.next();
                Attribute attr = attrs.get(id);
                res = true;
            }
        }
    } finally {
        if (enumer != null) {
            enumer.close();
        }
        if (enumerx != null) {
            enumerx.close();
        }
        if (enumery != null) {
            enumery.close();
        }
    }

    log.debug("[hasMonitoringEnabled] res=" + res + " metric:" + metric);
    return res;
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

public IAccount getUser(String uid) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration searchResultEnum;
    Map filters = new HashMap();

    String uidAttrName = "uid";
    if (this.propAttrMap.containsKey("user_id")) {
        try {/*from w ww .j a v a  2s  .  com*/
            uidAttrName = (String) this.propAttrMap.get("user_id");
        } catch (Exception ex) {
            //ignore
        }
    }
    if (uid != null && !"".equals(uid))
        filters.put(uidAttrName, uid);

    DirContext context = null;
    try {
        context = this.initContext();
        searchResultEnum = context.search(userBase, buildFilterByUid(filters), searchControls);
        //roop of retrieval result

        while (searchResultEnum.hasMore()) {
            SearchResult searchResult = (SearchResult) searchResultEnum.next();

            String dn = searchResult.getName() + "," + userBase;
            LDAPAccount user = createLDAPUser(dn, searchResult.getAttributes());
            setGroup(context, user);

            return user;
        }

        return null;
    } finally {
        if (context != null)
            context.close();
    }
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private void setGroup(DirContext context, LDAPAccount user) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    //create the filter of group
    Map filters = new HashMap();
    String uniqueMemberAttrName = "uniquemember";
    if (this.propAttrMap.containsKey("org_member"))
        uniqueMemberAttrName = (String) this.propAttrMap.get("org_member");

    filters.put(uniqueMemberAttrName, user.getDn());
    String grpFilter = buildGroupFilterByDN(filters);

    NamingEnumeration grpRes = context.search(groupBase, grpFilter, searchControls);

    List grpList = new ArrayList();

    while (grpRes.hasMoreElements()) {
        SearchResult findGrpEntry = (SearchResult) grpRes.next();
        if (log.isDebugEnabled())
            log.debug("Found Groups: " + findGrpEntry.getAttributes().toString());
        String grpdn = findGrpEntry.getName() + "," + groupBase;

        grpList.add(createLDAPGroup(grpdn, findGrpEntry.getAttributes()));
    }//from  w  ww . jav a 2s.c o  m

    IGroup[] igroup = new IGroup[grpList.size()];

    for (int i = 0; i < igroup.length; i++) {
        igroup[i] = (IGroup) grpList.get(i);
    }
    user.setGroups(igroup);

}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private List searchFromUsers(DirContext context, Map filters) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration searchResultEnum;

    String filter = buildFilter(filters);
    if (log.isInfoEnabled())
        log.info("Search User from " + userBase + " by " + filter);
    searchResultEnum = context.search(userBase, filter, searchControls);
    //roop of retrieval result

    List users = new ArrayList();
    while (searchResultEnum.hasMore()) {
        SearchResult searchResult = (SearchResult) searchResultEnum.next();
        String dn = searchResult.getName() + "," + userBase;
        LDAPAccount user = createLDAPUser(dn, searchResult.getAttributes());
        users.add(user);/*from   w  ww.j  av a2s  .  c o  m*/
    }
    return users;
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private List searchGroupMember(DirContext context, Map filters) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    Set userList = new HashSet();
    String filter = buildFilter(filters);
    if (log.isInfoEnabled())
        log.info("Search User from " + userBase + " by " + filter);
    NamingEnumeration searchResultEnum = context.search(this.groupBase, filter, searchControls);

    while (searchResultEnum.hasMore()) {
        SearchResult searchResult = (SearchResult) searchResultEnum.next();
        Attributes attrs = searchResult.getAttributes();
        String dn = searchResult.getName() + "," + groupBase;
        String uniquememberAttrName = "uniqueMember";
        if (this.propAttrMap.containsKey("org_member")) {
            try {
                uniquememberAttrName = (String) this.propAttrMap.get("org_member");
            } catch (Exception ex) {
                //ignore
            }/* ww w.  j  av a  2s  .c om*/
        }
        Attribute uniquememberAttr = attrs.get(uniquememberAttrName);
        if (uniquememberAttr == null)
            continue;
        NamingEnumeration memberDNs = uniquememberAttr.getAll();
        while (memberDNs.hasMoreElements()) {
            //System.out.println(memberDNs[j]);
            userList.add(memberDNs.next());//DN of user
        }
    }

    List members = new ArrayList();

    for (Iterator userDns = userList.iterator(); userDns.hasNext();) {

        /* Next directory entry */
        String userDn = (String) userDns.next();
        Attributes userEntry = null;
        try {
            userEntry = context.getAttributes(userDn);//DN of user
        } catch (Exception e) {
            log.error(userDn + ": " + e.getMessage());
        }
        if (userEntry == null)
            continue;

        LDAPAccount user = createLDAPUser(userDn, userEntry);
        if (user.getUid() == null)
            continue;

        members.add(user);

    }

    return members;

}

From source file:org.jasig.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];
    ArrayList ids = new ArrayList();
    switch (method) {
    case STARTS_WITH:
        query = query + "*";
        break;//from  w w  w. j  av  a 2 s.co  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);
    } catch (NamingException nex) {
        log.error("LDAPGroupStore: Unable to perform filter " + query, nex);
    }
    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]);
}

From source file:org.jasig.portal.security.provider.SimpleLdapSecurityContext.java

/**
 * Authenticates the user.//from   ww w  .  j  a  v  a2s .  c om
 */
public synchronized void authenticate() throws PortalSecurityException {
    this.isauth = false;
    ILdapServer ldapConn;

    String propFile = ctxProperties.getProperty(LDAP_PROPERTIES_CONNECTION_NAME);
    if (propFile != null && propFile.length() > 0)
        ldapConn = LdapServices.getLdapServer(propFile);
    else
        ldapConn = LdapServices.getDefaultLdapServer();

    String creds = new String(this.myOpaqueCredentials.credentialstring);
    if (this.myPrincipal.UID != null && !this.myPrincipal.UID.trim().equals("")
            && this.myOpaqueCredentials.credentialstring != null && !creds.trim().equals("")) {
        DirContext conn = null;
        NamingEnumeration results = null;
        StringBuffer user = new StringBuffer("(");
        String first_name = null;
        String last_name = null;

        user.append(ldapConn.getUidAttribute()).append("=");
        user.append(this.myPrincipal.UID).append(")");
        if (log.isDebugEnabled())
            log.debug("SimpleLdapSecurityContext: Looking for " + user.toString());

        try {
            conn = ldapConn.getConnection();

            // set up search controls
            SearchControls searchCtls = new SearchControls();
            searchCtls.setReturningAttributes(attributes);
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            // do lookup
            if (conn != null) {
                try {
                    results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls);
                    if (results != null) {
                        if (!results.hasMore())
                            log.error("SimpleLdapSecurityContext: user not found , " + this.myPrincipal.UID);
                        while (results != null && results.hasMore()) {
                            SearchResult entry = (SearchResult) results.next();
                            StringBuffer dnBuffer = new StringBuffer();
                            dnBuffer.append(entry.getName()).append(", ");
                            dnBuffer.append(ldapConn.getBaseDN());
                            Attributes attrs = entry.getAttributes();
                            first_name = getAttributeValue(attrs, ATTR_FIRSTNAME);
                            last_name = getAttributeValue(attrs, ATTR_LASTNAME);
                            // re-bind as user
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL);
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_CREDENTIALS);
                            conn.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, dnBuffer.toString());
                            conn.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS,
                                    this.myOpaqueCredentials.credentialstring);
                            searchCtls = new SearchControls();
                            searchCtls.setReturningAttributes(new String[0]);
                            searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

                            String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)";
                            log.debug("SimpleLdapSecurityContext: Looking in " + dnBuffer.toString() + " for "
                                    + attrSearch);
                            conn.search(dnBuffer.toString(), attrSearch, searchCtls);

                            this.isauth = true;
                            this.myPrincipal.FullName = first_name + " " + last_name;
                            log.debug("SimpleLdapSecurityContext: User " + this.myPrincipal.UID + " ("
                                    + this.myPrincipal.FullName + ") is authenticated");

                            // Since LDAP is case-insensitive with respect to uid, force
                            // user name to lower case for use by the portal
                            this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase();
                        } // while (results != null && results.hasMore())
                    } else {
                        log.error("SimpleLdapSecurityContext: No such user: " + this.myPrincipal.UID);
                    }
                } catch (AuthenticationException ae) {
                    log.info("SimpleLdapSecurityContext: Password invalid for user: " + this.myPrincipal.UID);
                } catch (Exception e) {
                    log.error("SimpleLdapSecurityContext: LDAP Error with user: " + this.myPrincipal.UID + "; ",
                            e);
                    throw new PortalSecurityException("SimpleLdapSecurityContext: LDAP Error" + e
                            + " with user: " + this.myPrincipal.UID);
                } finally {
                    ldapConn.releaseConnection(conn);
                }
            } else {
                log.error("LDAP Server Connection unavalable");
            }
        } catch (final NamingException ne) {
            log.error("Error geting connection to LDAP server.", ne);
        }
    } else {
        log.error("Principal or OpaqueCredentials not initialized prior to authenticate");
    }
    // Ok...we are now ready to authenticate all of our subcontexts.
    super.authenticate();
    return;
}

From source file:org.jsecurity.realm.activedirectory.ActiveDirectoryRealm.java

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames;
    roleNames = new LinkedHashSet<String>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String userPrincipalName = username;
    if (principalSuffix != null) {
        userPrincipalName += principalSuffix;
    }/*from   w  w  w. j av  a2s  .  com*/

    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving group names for user [" + sr.getName() + "]");
        }

        Attributes attrs = sr.getAttributes();

        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();

                if (attr.getID().equals("memberOf")) {

                    Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

                    if (log.isDebugEnabled()) {
                        log.debug("Groups found for user [" + username + "]: " + groupNames);
                    }

                    Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
                    roleNames.addAll(rolesForGroups);
                }
            }
        }
    }
    return roleNames;
}

From source file:org.kuali.rice.kim.dao.impl.LdapPrincipalDaoImpl.java

protected SearchControls getSearchControls() {
    SearchControls retval = new SearchControls();
    retval.setCountLimit(getSearchResultsLimit(PersonImpl.class).longValue());
    retval.setSearchScope(SearchControls.SUBTREE_SCOPE);
    return retval;
}

From source file:org.lsc.jndi.FullDNJndiDstService.java

/**
 * The simple object getter according to its identifier.
 * //w w w  . ja  v  a  2 s.c o  m
 * @param dn DN of the entry to be returned, which is the name returned by {@link #getListPivots()}
 * @param pivotAttributes Unused.
 * @param fromSameService are the pivot attributes provided by the same service
 * @return The bean, or null if not found
 * @throws LscServiceException May throw a {@link NamingException} if the object is not found in the
 *             directory, or if more than one object would be returned. 
 */
public IBean getBean(String dn, LscDatasets pivotAttributes, boolean fromSameService)
        throws LscServiceException {

    try {
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);
        List<String> attrs = getAttrs();
        if (attrs != null) {
            sc.setReturningAttributes(attrs.toArray(new String[attrs.size()]));
        }
        SearchResult srObject = getJndiServices().readEntry(dn, getFilterId(), true, sc);
        Method method = beanClass.getMethod("getInstance",
                new Class[] { SearchResult.class, String.class, Class.class });
        return (IBean) method.invoke(null, new Object[] { srObject, jndiServices.completeDn(dn), beanClass });

    } catch (SecurityException e) {
        LOGGER.error(
                "Unable to get static method getInstance on {} ! This is probably a programmer's error ({})",
                beanClass.getName(), e);
        LOGGER.debug(e.toString(), e);
    } catch (NoSuchMethodException e) {
        LOGGER.error(
                "Unable to get static method getInstance on {} ! This is probably a programmer's error ({})",
                beanClass.getName(), e);
        LOGGER.debug(e.toString(), e);
    } catch (IllegalArgumentException e) {
        LOGGER.error(
                "Unable to get static method getInstance on {} ! This is probably a programmer's error ({})",
                beanClass.getName(), e);
        LOGGER.debug(e.toString(), e);
    } catch (IllegalAccessException e) {
        LOGGER.error(
                "Unable to get static method getInstance on {} ! This is probably a programmer's error ({})",
                beanClass.getName(), e);
        LOGGER.debug(e.toString(), e);
    } catch (InvocationTargetException e) {
        LOGGER.error(
                "Unable to get static method getInstance on {} ! This is probably a programmer's error ({})",
                beanClass.getName(), e);
        LOGGER.debug(e.toString(), e);
    } catch (NamingException e) {
        LOGGER.error("JNDI error while synchronizing {}: {} ", beanClass.getName(), e);
        LOGGER.debug(e.toString(), e);
        throw new LscServiceException(e.toString(), e);
    }
    return null;
}