Example usage for javax.naming.directory SearchControls SearchControls

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

Introduction

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

Prototype

public SearchControls() 

Source Link

Document

Constructs a search constraints using defaults.

Usage

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:com.surevine.chat.auth.GroupAuthorisationFilter.java

/**
 * Get a list of the members of a group, searching for the group using an
 * LDAP filter expression and scope./*from   w  ww. ja  v a 2 s. c  o  m*/
 * 
 * @param filter
 *            LDAP search filter (see RFC2254)
 * @param scope
 *            One of SearchControls.OBJECT_SCOPE,
 *            SearchControls.ONELEVEL_SCOPE, or SearchControls.SUBTREE_SCOPE
 *            (see javax.naming.directory.SearchControls)
 * @return List of usernames
 * @throws NamingException
 * @throws LdapException
 *             On any LDAP error
 */
private Collection<String> getGroupMembers(final String groupName) throws NamingException {
    _logger.debug("Looking for members of " + groupName);
    String filter = "cn=" + groupName;
    Collection<String> memberList = new HashSet<String>(20);

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

    NamingEnumeration<SearchResult> objects;
    DirContext ctx = getLdapConnection();

    objects = ctx.search("ou=groups", filter, controls);

    while (objects.hasMore()) {
        SearchResult sr = (SearchResult) objects.next();
        Attributes attributes = sr.getAttributes();
        Attribute attribute = attributes.get("member");

        if (attribute != null) {
            NamingEnumeration<?> valueEnum = attribute.getAll();

            while (valueEnum.hasMore()) {
                String value = valueEnum.next().toString();

                final String searchFor = "cn=";
                int start = value.indexOf(searchFor);
                int end = value.indexOf(',', start);

                if (start >= 0 && end >= 0) {
                    String name = value.substring(start + searchFor.length(), end);
                    _logger.debug(name + " is a chatter");
                    memberList.add(name);
                }
            }
        }
    }
    _logger.debug("Returning a total of " + memberList.size() + " chatters");
    return memberList;
}

From source file:eu.uqasar.util.ldap.LdapManager.java

private SearchControls getDefaultSearchControls() {
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SUBTREE_SCOPE);
    controls.setReturningAttributes(null);
    controls.setReturningObjFlag(true);//  w ww.ja v  a  2  s . co m
    return controls;
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static boolean isCNregistered(String cn) {
    boolean registered = false;
    NamingEnumeration results = null;
    DirContext ctx = null;//w ww . j a v a2  s  . c o m
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls);
        if (results.hasMore()) {
            registered = true;
        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        registered = true;
    } 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 registered;
}

From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java

protected NamingEnumeration<SearchResult> searchUsers(DirContext context, String[] returnAttributes,
        LdapUserQuery query) throws NamingException {
    if (query == null) {
        query = new LdapUserQuery();
    }/*from  w w w  .  j  a v  a  2 s.  co m*/
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(mapper.getReturningAttributes());
    ctls.setCountLimit(((LdapUserMapper) mapper).getMaxResultCount());

    String finalFilter = new StringBuilder("(&(objectClass=" + mapper.getUserObjectClass() + ")")
            .append((mapper.getUserFilter() != null ? mapper.getUserFilter() : ""))
            .append(query.getLdapFilter(mapper) + ")").toString();

    log.debug("Searching for users with filter: '{}' from base dn: {}", finalFilter, mapper.getUserBaseDn());

    return context.search(mapper.getUserBaseDn(), finalFilter, ctls);
}

From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java

/**
 * Check if organizational unit is created in tenant.
 *
 * @param orgName           Organization name.
 * @param initialDirContext The directory connection.
 * @throws UserStoreException If an error occurred while searching.
 *///from w  ww  .j  av  a  2s. com
protected boolean isOrganizationalUnitCreated(String orgName, DirContext initialDirContext)
        throws UserStoreException {

    //construct search filter,eg. (&(objectClass=organizationalUnit)(ou=wso2.com))
    String partitionDN = tenantMgtConfig.getTenantStoreProperties()
            .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ROOT_PARTITION);
    String organizationalObjectClass = tenantMgtConfig.getTenantStoreProperties()
            .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORGANIZATIONAL_OBJECT_CLASS);
    String organizationalAttribute = tenantMgtConfig.getTenantStoreProperties()
            .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORGANIZATIONAL_ATTRIBUTE);
    String searchFilter = "(&(objectClass=" + organizationalObjectClass + ")(" + organizationalAttribute + "="
            + orgName + "))";

    SearchControls userSearchControl = new SearchControls();
    userSearchControl.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    NamingEnumeration<SearchResult> userSearchResults = null;

    try {
        userSearchResults = initialDirContext.search(partitionDN, searchFilter, userSearchControl);
        return userSearchResults.hasMore();
    } catch (NamingException e) {
        String errorMessage = "Error occurred while searching in root partition for organization : " + orgName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
}

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

/**
 * The simple object getter according to its identifier.
 * /*w w w  .ja va 2 s.  c  om*/
 * @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;
}

From source file:ru.runa.wfe.security.logic.LdapLogic.java

private int synchronizeActors(DirContext dirContext, Map<String, Actor> actorsByDistinguishedName)
        throws Exception {
    int changesCount = 0;
    List<Actor> existingActorsList = executorDao.getAllActors(BatchPresentationFactory.ACTORS.createNonPaged());
    Map<String, Actor> existingActorsMap = Maps.newHashMap();
    for (Actor actor : existingActorsList) {
        existingActorsMap.put(actor.getName().toLowerCase(), actor);
    }//from  w  ww  .ja  v  a  2s .  c  o m
    Set<Actor> ldapActorsToDelete = Sets.newHashSet();
    if (LdapProperties.isSynchronizationDeleteExecutors()) {
        ldapActorsToDelete.addAll(executorDao.getGroupActors(importGroup));
    }
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    for (String ou : LdapProperties.getSynchronizationOrganizationUnits()) {
        List<SearchResult> resultList = Lists.newArrayList();
        try {
            NamingEnumeration<SearchResult> list = dirContext.search(ou, OBJECT_CLASS_USER_FILTER, controls);
            while (list.hasMore()) {
                SearchResult searchResult = list.next();
                resultList.add(searchResult);
            }
            list.close();
        } catch (SizeLimitExceededException e) {
            resultList.clear();
            for (String y : ALPHABETS) {
                NamingEnumeration<SearchResult> list = dirContext.search(ou,
                        MessageFormat.format(LOGIN_FIRST_LETTER_FILTER, ATTR_ACCOUNT_NAME, y, y.toLowerCase(),
                                OBJECT_CLASS_USER_FILTER),
                        controls);
                while (list.hasMore()) {
                    SearchResult searchResult = list.next();
                    resultList.add(searchResult);
                }
                list.close();
            }
        }
        for (SearchResult searchResult : resultList) {
            String name = getStringAttribute(searchResult, ATTR_ACCOUNT_NAME);
            String description = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserDescriptionAttribute());
            String fullName = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserFullNameAttribute());
            String email = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserEmailAttribute());
            String phone = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserPhoneAttribute());
            String title = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserTitleAttribute());
            String department = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserDepartmentAttribute());
            ToStringHelper toStringHelper = MoreObjects.toStringHelper("user info");
            toStringHelper.add("name", name).add("description", description).add("fullName", fullName)
                    .add("email", email);
            toStringHelper.add("phone", phone).add("title", title).add("department", department)
                    .omitNullValues();
            log.debug("Read " + toStringHelper.toString());
            Actor actor = existingActorsMap.get(name.toLowerCase());
            if (actor == null) {
                if (!LdapProperties.isSynchronizationCreateExecutors()) {
                    continue;
                }
                actor = new Actor(name, description, fullName, null, email, phone, title, department);
                log.info("Creating " + actor);
                executorDao.create(actor);
                executorDao.addExecutorsToGroup(Lists.newArrayList(actor), importGroup);
                permissionDao.setPermissions(importGroup, Lists.newArrayList(Permission.LIST), actor);
                changesCount++;
            } else {
                ldapActorsToDelete.remove(actor);
                if (LdapProperties.isSynchronizationUpdateExecutors()) {
                    List<IChange> changes = Lists.newArrayList();
                    if (isAttributeNeedsChange(description, actor.getDescription())) {
                        changes.add(new AttributeChange("description", actor.getDescription(), description));
                        actor.setDescription(description);
                    }
                    if (isAttributeNeedsChange(fullName, actor.getFullName())) {
                        changes.add(new AttributeChange("fullName", actor.getFullName(), fullName));
                        actor.setFullName(fullName);
                    }
                    if (isAttributeNeedsChange(email, actor.getEmail())) {
                        changes.add(new AttributeChange("email", actor.getEmail(), email));
                        actor.setEmail(email);
                    }
                    if (isAttributeNeedsChange(phone, actor.getPhone())) {
                        changes.add(new AttributeChange("phone", actor.getPhone(), phone));
                        actor.setPhone(phone);
                    }
                    if (isAttributeNeedsChange(title, actor.getTitle())) {
                        changes.add(new AttributeChange("title", actor.getTitle(), title));
                        actor.setTitle(title);
                    }
                    if (isAttributeNeedsChange(department, actor.getDepartment())) {
                        changes.add(new AttributeChange("department", actor.getDepartment(), department));
                        actor.setDepartment(department);
                    }
                    if (!actor.isActive()) {
                        if (LdapProperties.isSynchronizationUserStatusEnabled()) {
                            actor.setActive(true);
                            changes.add(new AttributeChange("active", "false", "true"));
                        }
                        if (executorDao.removeExecutorFromGroup(actor, wasteGroup)) {
                            changes.add(new Change("waste group removal"));
                        }
                        if (executorDao.addExecutorToGroup(actor, importGroup)) {
                            changes.add(new Change("import group addition"));
                        }
                    }
                    if (!changes.isEmpty()) {
                        executorDao.update(actor);
                        log.info("Updating " + actor + ": " + changes);
                        changesCount++;
                    }
                }
            }
            actorsByDistinguishedName.put(searchResult.getNameInNamespace(), actor);
        }
    }
    if (LdapProperties.isSynchronizationDeleteExecutors() && ldapActorsToDelete.size() > 0) {
        if (LdapProperties.isSynchronizationUserStatusEnabled()) {
            for (Actor actor : ldapActorsToDelete) {
                actor.setActive(false);
                executorDao.update(actor);
                log.info("Inactivating " + actor);
                changesCount++;
            }
        }
        executorDao.removeExecutorsFromGroup(ldapActorsToDelete, importGroup);
        executorDao.addExecutorsToGroup(ldapActorsToDelete, wasteGroup);
        changesCount += ldapActorsToDelete.size();
    }
    return changesCount;
}

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());
            }/*ww  w . ja  v  a 2  s  . co m*/
        }
    }

    Collections.sort(users);

    return users;
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Returns <code>true</code> if the supplied id is found in the JNDI storage.
 * @see IStorage#exists(java.lang.String)
 *//* w  w  w.  j  a  v a 2s .c  o  m*/
public boolean exists(String id) throws UserException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;

    boolean bReturn = false;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

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

        String searchFilter = resolveSearchQuery(id);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
            bReturn = oNamingEnumeration.hasMore();
        } catch (InvalidSearchFilterException e) {
            _logger.error("Wrong filter: " + searchFilter);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.debug("User unknown, naming exception. query: " + searchFilter, e);
            return false; //user unknown
        }
    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not verify if user exists: " + id, e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + id, e);
            }
        }
    }
    return bReturn;
}