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.archone.ad.domain.UserHelper.java

public List<String> lookupMembershipGroups(DirContext dirContext, String userDn)
        throws javax.naming.NamingException {

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

    NamingEnumeration<SearchResult> searchResults = dirContext.search("",
            adConfiguration.getMembershipSearchFilter(), new String[] { userDn }, controls);

    List<String> roles = new LinkedList<String>();
    while (searchResults.hasMore()) {
        GroupDn groupDn = new GroupDn(searchResults.next().getNameInNamespace(),
                adConfiguration.getGroupsRdn());
        roles.add(groupDn.getAsGroupId());
    }/*from w  w  w.ja  va  2  s . c o m*/

    return roles;
}

From source file:org.hyperic.hq.plugin.netservices.LDAPCollector.java

/**
 * Construct default SearchControls/*from  w  ww  .  j a v  a 2  s.c o  m*/
 */
private SearchControls getSearchControls() {
    // Set the scope to subtree, default is one-level
    int scope = SearchControls.SUBTREE_SCOPE;

    // Use 'socket timeout' for search timeout.
    int timeLimit = getTimeoutMillis();

    // No limit on the number of entries returned
    long countLimit = 0;

    // Attributes to return.
    String returnedAttributes[] = null;

    // Don't return the object
    boolean returnObject = false;

    // No dereferencing during the search
    boolean deference = false;

    SearchControls constraints = new SearchControls(scope, countLimit, timeLimit, returnedAttributes,
            returnObject, deference);
    return constraints;
}

From source file:org.jasig.cas.adaptors.ldap.services.LdapServiceRegistryDao.java

public LdapServiceRegistryDao() {
    this.cachedSearchControls = new SearchControls();
    this.cachedSearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
}

From source file:org.archone.ad.authentication.ShoadRealm.java

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }/*from  w w  w .j a  v  a 2  s  . com*/

    String username = (String) getAvailablePrincipal(principals);

    Set<String> roleNames = null;
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContextAdapter context = (DirContextAdapter) contextSource.getReadOnlyContext();
    try {
        String userDn = (String) getUserDn(username);

        DirContextAdapter superuserGroup = (DirContextAdapter) new LdapTemplate(contextSource)
                .lookup("cn=administrator,cn=shoad");
        Set<String> superusers = superuserGroup.getAttributeSortedStringSet("uniqueMember");

        Logger.getLogger("AUTH").log(Level.INFO, "THE SIZE IS {0}", new Integer(superusers.size()).toString());

        if (superusers.contains(userDn)) {
            Logger.getLogger("AUTH").log(Level.INFO, "SUPERUSER LOGGED IN");
            roleNames.add("SUPERUSER");
        }

        NamingEnumeration<SearchResult> searchResults = context.search("",
                adConfiguration.getMembershipSearchFilter(), new String[] { userDn }, controls);
        while (searchResults.hasMore()) {
            GroupDn groupDn = new GroupDn(searchResults.next().getNameInNamespace(),
                    adConfiguration.getGroupsRdn());
            roleNames.add(groupDn.getAsGroupId());
        }

    } catch (javax.naming.NamingException ex) {
        Logger.getLogger(ShoadRealm.class.getName()).log(Level.SEVERE, null, ex);
        throw new AuthorizationException(ex);
    }

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);

    return info;
}

From source file:org.apache.cxf.sts.claims.LdapUtils.java

public static Map<String, Attribute> getAttributesOfEntry(LdapTemplate ldapTemplate, String baseDN,
        String objectClass, String filterAttributeName, String filterAttributeValue,
        String[] searchAttributes) {

    Map<String, Attribute> ldapAttributes = null;

    AttributesMapper mapper = new AttributesMapper() {
        public Object mapFromAttributes(Attributes attrs) throws NamingException {
            Map<String, Attribute> map = new HashMap<String, Attribute>();
            NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
            while (attrEnum.hasMore()) {
                Attribute att = attrEnum.next();
                map.put(att.getID(), att);
            }//from  w w w .  j  a v  a 2s .  c  o  m
            return map;
        }
    };

    List<?> result = null;
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", objectClass))
            .and(new EqualsFilter(filterAttributeName, filterAttributeValue));

    result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
            SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && result.size() > 0) {
        ldapAttributes = CastUtils.cast((Map<?, ?>) result.get(0));
    }

    return ldapAttributes;
}

From source file:com.adito.activedirectory.PagedResultTemplate.java

boolean searchForResult(InitialLdapContext context, String searchBase, String filter) throws NamingException {
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<SearchResult> results = context.search(searchBase, filter, constraints);
    return results.hasMore();
}

From source file:de.tuttas.util.LDAPUtil.java

/**
 * Benutzer aus der LDAP Abfragen/*from   w  w w  .j a  v  a 2  s.c om*/
 *
 * @param username Benutzername
 * @param password Kennwort
 * @return der Benutzer
 * @throws Exception Wenn etwas schief ging
 */
public LDAPUser authenticateJndi(String username, String password) throws Exception {
    // Anbindung ans LDAP
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost);
    props.put(Context.SECURITY_PRINCIPAL, Config.getInstance().bindUser);//adminuser - User with special priviledge, dn user
    props.put(Context.SECURITY_CREDENTIALS, Config.getInstance().bindPassword);//dn user password
    try {
        context = new InitialDirContext(props);
        ctrls = new SearchControls();
        ctrls.setReturningAttributes(new String[] { "description", "mail", "sn", "initials", "givenName",
                "memberOf", "userPrincipalName", "distinguishedName" });
        ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    } catch (NamingException ex) {
        Logger.getLogger(LDAPUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
    NamingEnumeration<javax.naming.directory.SearchResult> answers = context
            .search(Config.getInstance().userContext, "(cn=" + username + ")", ctrls);
    Log.d("answers=" + answers);
    Log.d("answers=" + answers.hasMore());

    if (!answers.hasMore()) {
        return null;
    }

    javax.naming.directory.SearchResult result = answers.nextElement();

    try {
        for (NamingEnumeration ae = result.getAttributes().getAll(); ae.hasMore();) {
            Attribute attr = (Attribute) ae.next();
            Log.d("attribute: " + attr.getID());

            /* print each value */
            for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next()))
                ;
        }
    } catch (NamingException e) {
        e.printStackTrace();
    }

    String inititials = "";
    if (result.getAttributes().get("initials") != null) {
        inititials = result.getAttributes().get("initials").getAll().next().toString();
    }
    LDAPUser u;
    if (result.getAttributes().get("mail") == null) {
        u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(),
                result.getAttributes().get("givenName").getAll().next().toString(), "", inititials);
    } else {
        u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(),
                result.getAttributes().get("givenName").getAll().next().toString(),
                result.getAttributes().get("mail").getAll().next().toString(), inititials);
    }

    String dName = result.getAttributes().get("distinguishedName").getAll().next().toString();
    Log.d("dName=" + dName);
    if (dName.contains("OU=Lehrer")) {
        Log.d("Ich bin ein Lehrer");
        u.setRole(Roles.toString(Roles.LEHRER));
    } else {
        Log.d("Ich bin ein Schler");
        u.setRole(Roles.toString(Roles.SCHUELER));
        if (result.getAttributes().get("memberOf") != null) {
            String memberOf = result.getAttributes().get("memberOf").getAll().next().toString();
            String courseName = memberOf.split(",")[0];
            courseName = courseName.substring(courseName.indexOf("=") + 1);
            Log.d("Name der Klasse ist " + courseName);
            u.setCourse(courseName);
        }
    }

    String user = result.getNameInNamespace();

    try {

        props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost);
        props.put(Context.SECURITY_PRINCIPAL, user);
        props.put(Context.SECURITY_CREDENTIALS, password);

        context = new InitialDirContext(props);
    } catch (Exception e) {
        return null;
    }
    return u;
}

From source file:org.wso2.carbon.connector.ldap.SearchEntry.java

@Override
public void connect(MessageContext messageContext) throws ConnectException {
    String objectClass = (String) getParameter(messageContext, LDAPConstants.OBJECT_CLASS);
    String filter = (String) getParameter(messageContext, LDAPConstants.FILTERS);
    String dn = (String) getParameter(messageContext, LDAPConstants.DN);
    String returnAttributes[] = ((String) getParameter(messageContext, LDAPConstants.ATTRIBUTES)).split(",");
    boolean onlyOneReference = Boolean
            .valueOf((String) getParameter(messageContext, LDAPConstants.ONLY_ONE_REFERENCE));

    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace(LDAPConstants.CONNECTOR_NAMESPACE, LDAPConstants.NAMESPACE);
    OMElement result = factory.createOMElement(LDAPConstants.RESULT, ns);

    try {/*w  w w  .ja  va  2  s  .co m*/
        DirContext context = LDAPUtils.getDirectoryContext(messageContext);

        String attrFilter = generateAttrFilter(filter);
        String searchFilter = generateSearchFilter(objectClass, attrFilter);
        NamingEnumeration<SearchResult> results = null;
        try {
            results = searchInUserBase(dn, searchFilter, returnAttributes, SearchControls.SUBTREE_SCOPE,
                    context);
            SearchResult entityResult = null;

            if (!onlyOneReference) {
                if (results != null && results.hasMore()) {
                    while (results.hasMore()) {
                        entityResult = results.next();
                        result.addChild(prepareNode(entityResult, factory, ns, returnAttributes));
                    }
                }
            } else {
                entityResult = makeSureOnlyOneMatch(results);
                if (entityResult == null)
                    throw new NamingException(
                            "Multiple objects for the searched target have been found. Try to "
                                    + "change onlyOneReference option");
                result.addChild(prepareNode(entityResult, factory, ns, returnAttributes));
            }

            LDAPUtils.preparePayload(messageContext, result);

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

        } catch (NamingException e) { //LDAP Errors are catched
            LDAPUtils.handleErrorResponse(messageContext, LDAPConstants.ErrorConstants.SEARCH_ERROR, e);
            throw new SynapseException(e);
        }

    } catch (NamingException e) { //Authentication failures are catched
        LDAPUtils.handleErrorResponse(messageContext, LDAPConstants.ErrorConstants.INVALID_LDAP_CREDENTIALS, e);
        throw new SynapseException(e);
    }
}

From source file:org.pepstock.jem.gwt.server.security.ExtendedJndiLdapRealm.java

/**
 * Creates the search controls and authorization of JEM 
 *///from   w  w  w.java2 s.  com
public ExtendedJndiLdapRealm() {
    super();
    ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    authorizator = new Authorizator();
}

From source file:se.vgregion.service.innovationsslussen.ldap.LdapService.java

/**
 * Finds data from the ldap server. Provide a structure (class instance) with the data to use as search criteria
 * and gets the answer as a list with the same format (class type) as the criteria.
 * @param sample holds properties that (could) match fields in the db by the operator '=' or 'like' (in conjunction
 *               with having a '*' character in a String value).
 *
 * @param <T> type of the param and type of the answers inside the resulting list.
 * @return a list of search hits./*from   w w w.ja  va  2s.c om*/
 */
public <T> List<T> find(T sample) {
    final AttributesMapper mapper = newAttributesMapper(sample.getClass());
    final Filter searchFilter = toAndCondition(sample);
    final SearchControls searchControls = new SearchControls();
    searchControls.setReturningAttributes(new String[] { "*" });
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    @SuppressWarnings("unchecked")
    List<T> result = ldapTemplate.search(StringUtils.EMPTY, searchFilter.encode(), searchControls, mapper);

    return result;
}