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.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 .  j  a v  a  2 s  .  c o  m*/

    return roles;
}

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.apache.cloudstack.ldap.ADLdapUserManagerImpl.java

@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException {
    if (StringUtils.isBlank(groupName)) {
        throw new IllegalArgumentException("ldap group name cannot be blank");
    }/*  w  ww.j a  v a 2  s .com*/

    String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }

    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    NamingEnumeration<SearchResult> results = context.search(basedn, generateADGroupSearchFilter(groupName),
            searchControls);
    final List<LdapUser> users = new ArrayList<LdapUser>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));
    }
    return users;
}

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.");
    }/* w w  w  .ja v a2 s .c om*/

    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: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:org.beangle.security.ldap.connect.SimpleLdapUserStore.java

public String getUserDN(String uid) {
    DirContext ctx = getContext();
    if (ctx == null)
        return null;
    String result = null;//from   ww w  . ja va2  s.c o 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.jasig.cas.authentication.principal.AbstractLdapPersonDirectoryCredentialsToPrincipalResolver.java

protected final SearchControls getSearchControls() {
    final SearchControls constraints = new SearchControls();
    if (log.isDebugEnabled()) {
        log.debug("returning searchcontrols: scope=" + this.scope + "; search base=" + this.searchBase
                + "; attributes=" + Arrays.toString(this.attributeIds) + "; timeout=" + this.timeout);
    }/*from   www  .  j a  va  2 s . c om*/
    constraints.setSearchScope(this.scope);
    constraints.setReturningAttributes(this.attributeIds);
    constraints.setTimeLimit(this.timeout);
    constraints.setCountLimit(DEFAULT_MAX_NUMBER_OF_RESULTS);
    return constraints;
}

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

/**
 * Benutzer aus der LDAP Abfragen//from w  w w .  j  a va  2 s  .  c  o  m
 *
 * @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: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./* w  w w  . j  ava 2  s  . co  m*/
 */
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;
}

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

/**
 * Creates the search controls and authorization of JEM 
 *//* ww  w  .  j a v a  2  s  . c om*/
public ExtendedJndiLdapRealm() {
    super();
    ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    authorizator = new Authorizator();
}