Example usage for javax.naming.directory SearchControls SUBTREE_SCOPE

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

Introduction

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

Prototype

int SUBTREE_SCOPE

To view the source code for javax.naming.directory SearchControls SUBTREE_SCOPE.

Click Source Link

Document

Search the entire subtree rooted at the named object.

Usage

From source file:org.wso2.carbon.identity.account.suspension.notification.task.ldap.LDAPNotificationReceiversRetrieval.java

@Override
public List<NotificationReceiver> getNotificationReceivers(long lookupMin, long lookupMax,
        long delayForSuspension, String tenantDomain) throws AccountSuspensionNotificationException {

    List<NotificationReceiver> users = new ArrayList<NotificationReceiver>();

    if (realmConfiguration != null) {
        String ldapSearchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
        RealmService realmService = NotificationTaskDataHolder.getInstance().getRealmService();

        try {/*  w w  w.  j  a v  a2  s.  com*/
            ClaimManager claimManager = (ClaimManager) realmService
                    .getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain)).getClaimManager();
            String userStoreDomain = realmConfiguration
                    .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
            if (StringUtils.isBlank(userStoreDomain)) {
                userStoreDomain = IdentityUtil.getPrimaryDomainName();
            }

            String usernameMapAttribute = claimManager.getAttributeName(userStoreDomain,
                    NotificationConstants.USERNAME_CLAIM);
            String firstNameMapAttribute = claimManager.getAttributeName(userStoreDomain,
                    NotificationConstants.FIRST_NAME_CLAIM);
            String emailMapAttribute = claimManager.getAttributeName(userStoreDomain,
                    NotificationConstants.EMAIL_CLAIM);
            String lastLoginTimeAttribute = claimManager.getAttributeName(userStoreDomain,
                    NotificationConstants.LAST_LOGIN_TIME);

            if (log.isDebugEnabled()) {
                log.debug(
                        "Retrieving ldap user list for lookupMin: " + lookupMin + " - lookupMax: " + lookupMax);
            }

            LDAPConnectionContext ldapConnectionContext = new LDAPConnectionContext(realmConfiguration);
            DirContext ctx = ldapConnectionContext.getContext();

            //carLicense is the mapped LDAP attribute for LastLoginTime claim
            String searchFilter = "(&(" + lastLoginTimeAttribute + ">=" + lookupMin + ")("
                    + lastLoginTimeAttribute + "<=" + lookupMax + "))";

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

            NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls);

            if (log.isDebugEnabled()) {
                log.debug("LDAP user list retrieved.");
            }

            while (results.hasMoreElements()) {
                SearchResult result = results.nextElement();

                NotificationReceiver receiver = new NotificationReceiver();
                receiver.setEmail((String) result.getAttributes().get(emailMapAttribute).get());
                receiver.setUsername((String) result.getAttributes().get(usernameMapAttribute).get());
                receiver.setFirstName((String) result.getAttributes().get(firstNameMapAttribute).get());
                receiver.setUserStoreDomain(userStoreDomain);

                long lastLoginTime = Long
                        .parseLong(result.getAttributes().get(lastLoginTimeAttribute).get().toString());
                long expireDate = lastLoginTime + TimeUnit.DAYS.toMillis(delayForSuspension);
                receiver.setExpireDate(new SimpleDateFormat("dd-MM-yyyy").format(new Date(expireDate)));

                if (log.isDebugEnabled()) {
                    log.debug("Expire date was set to: " + receiver.getExpireDate());
                }
                users.add(receiver);
            }
        } catch (NamingException e) {
            throw new AccountSuspensionNotificationException("Failed to filter users from LDAP user store.", e);
        } catch (UserStoreException e) {
            throw new AccountSuspensionNotificationException("Failed to load LDAP connection context.", e);
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            throw new AccountSuspensionNotificationException(
                    "Error occurred while getting tenant user realm for " + "tenant:" + tenantDomain, e);
        }
    }
    return users;
}

From source file:fr.iphc.grid.jobmonitor.CeList.java

static public ArrayList<URL> AvailableLdapCe() throws Exception {
    ArrayList<URL> CeList = new ArrayList<URL>();
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://cclcgtopbdii01.in2p3.fr:2170");
    env.put("java.naming.ldap.attributes.binary", "objectSID");
    try {//from   ww  w . j av a  2s.c  om
        // Create initial context
        DirContext ctx = new InitialDirContext(env);
        SearchControls contraints = new SearchControls();
        contraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attributIDs = { "GlueCEUniqueID" };
        contraints.setReturningAttributes(attributIDs);
        String BASE_SEARCH = "Mds-Vo-name=local,o=grid";
        String filter = "(&(objectClass=GlueCE)(GlueCEImplementationName=CREAM)(GlueCEAccessControlBaseRule=VO:biomed))";
        NamingEnumeration<SearchResult> answer = ctx.search(BASE_SEARCH, filter, contraints);
        //         int index = 0;
        Random rand = new Random();
        while (answer.hasMore()) {
            //            index++;
            SearchResult result = answer.next();
            //            Attributes attrs = result.getAttributes();
            //            NamingEnumeration f = attrs.getAll();
            //            Attribute attr = (Attribute) f.next();
            String line = "cream://" + result.getAttributes().get("GlueCEUniqueID").get() + "?delegationId="
                    + rand.nextLong();
            URL serviceURL = URLFactory.createURL(line);
            CeList.add(serviceURL);
        }
        // Close the context when we're done
        ctx.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    ;
    return CeList;
}

From source file:com.photon.phresco.ldap.impl.LDAPManagerImpl.java

private User getUser(Credentials credentials, DirContext ctx) throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entering Method LDAPManagerImpl.getUserInfo(String userName, DirContext ctx)");
    }//from w  w  w  . jav a 2 s  .  com
    User user = new User();
    try {
        String userName = credentials.getUsername();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { "*" };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration<SearchResult> ne = ctx.search(ldapConfig.getLdapBaseDn(),
                ldapConfig.getLdapLoginAttribute() + Constants.STR_EQUALS + userName, constraints);
        if (ne.hasMore()) {
            Attributes attrs = ne.next().getAttributes();

            user.setName(userName);
            //      userInfo.setCredentials(credentials);
            user.setDisplayName(getDisplayName(attrs));
            user.setEmail(getMailId(attrs));
            user.setPhrescoEnabled(isPhrescoEnabled(attrs));
            //      userInfo.setCustomerNames(getCustomerNames(attrs));

        }

    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return user;
}

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

/**
 * function to extract users from Zeppelin LdapRealm
 *//* w  ww  .j a  v a  2s .  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.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl.java

public List findAll() {
    DirContext ctx = createAnonymousContext();

    LinkedList list = new LinkedList();
    NamingEnumeration results = null;
    try {//  ww w. j  a  v  a 2  s  .c  om
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        results = ctx.search("", "(objectclass=person)", controls);

        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            String dn = searchResult.getName();
            Attributes attributes = searchResult.getAttributes();
            list.add(mapToPerson(dn, attributes));
        }
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
    return list;
}

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

/**
 * Authenticates the user./*from   w  w  w  . j  a va  2s .com*/
 */
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.apache.lens.server.user.LDAPBackedDatabaseUserConfigLoader.java

/**
 * Find account by account name.//from   w ww. ja  v  a2s.co m
 *
 * @param accountName the account name
 * @return the search result
 * @throws NamingException the naming exception
 */
protected SearchResult findAccountByAccountName(String accountName) throws NamingException {
    String searchFilter = String.format(searchFilterPattern, accountName);
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    InitialLdapContext ctx = new InitialLdapContext(env, null);
    try {
        NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchControls);
        if (!results.hasMoreElements()) {
            throw new UserConfigLoaderException("LDAP Search returned no accounts");
        }
        SearchResult searchResult = results.nextElement();
        if (results.hasMoreElements()) {
            throw new UserConfigLoaderException("More than one account found in ldap search");
        }
        return searchResult;
    } finally {
        ctx.close();
    }
}

From source file:net.identio.server.service.authentication.ldap.LdapConnectionFactory.java

@Override
public boolean validateObject(PooledObject<InitialLdapContext> p) {

    LOG.debug("Validating connection to LDAP directory {}", ldapAuthMethod.getName());

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    controls.setCountLimit(1);/*from w w w  .ja v a  2 s .com*/
    controls.setTimeLimit(500);

    try {
        p.getObject().search("", ldapAuthMethod.getPoolConfig().getTestRequestFilter(), controls);
    } catch (NamingException e) {
        LOG.error("Validation of connection to LDAP directory {} failed", ldapAuthMethod.getName());
        return false;
    }

    return true;
}

From source file:org.apereo.services.persondir.support.ldap.LdapPersonAttributeDao.java

public LdapPersonAttributeDao() {
    this.searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    this.searchControls.setReturningObjFlag(false);
}

From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java

public List<Person> findAll() {
    DirContext ctx = createAnonymousContext();

    LinkedList<Person> list = new LinkedList<Person>();
    NamingEnumeration<?> results = null;
    try {/*from  w ww  .j  av  a  2s . co  m*/
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        results = ctx.search("", "(objectclass=person)", controls);

        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            String dn = searchResult.getName();
            Attributes attributes = searchResult.getAttributes();
            list.add(mapToPerson(dn, attributes));
        }
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
    return list;
}