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.ballerinalang.auth.ldap.nativeimpl.GetLdapScopesOfUser.java

private String[] getLDAPGroupsListOfUser(String userName, List<String> searchBase,
        CommonLdapConfiguration ldapAuthConfig) throws UserStoreException, NamingException {
    if (userName == null) {
        throw new BallerinaException("userName value is null.");
    }/*from  w w  w.j av  a  2  s.c  o  m*/

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    // Load normal roles with the user
    String searchFilter = ldapAuthConfig.getGroupNameListFilter();
    String roleNameProperty = ldapAuthConfig.getGroupNameAttribute();
    String membershipProperty = ldapAuthConfig.getMembershipAttribute();
    String nameInSpace = this.getNameInSpaceForUserName(userName, ldapConfiguration);

    if (membershipProperty == null || membershipProperty.length() < 1) {
        throw new BallerinaException("membershipAttribute not set in configuration");
    }

    String membershipValue;
    if (nameInSpace != null) {
        LdapName ldn = new LdapName(nameInSpace);
        if (LdapConstants.MEMBER_UID.equals(ldapAuthConfig.getMembershipAttribute())) {
            // membership value of posixGroup is not DN of the user
            List rdns = ldn.getRdns();
            membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString();
        } else {
            membershipValue = escapeLdapNameForFilter(ldn);
        }
    } else {
        return new String[0];
    }

    searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))";
    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Reading roles with the membershipProperty Property: " + membershipProperty);
    }

    List<String> list = this.getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty, false);
    return list.toArray(new String[list.size()]);
}

From source file:ldap.ActiveLoginImpl.java

/**
 * Returns whether this user is listed in the admin users role
 *
 * @param login/*from  w w  w  . j av a 2s . c o  m*/
 * @return
 * @throws Exception
 */
public boolean isAdmin(String login, DirContext context, String DN) throws Exception {
    NamingEnumeration result = null;

    String[] returnAttributes = new String[] { "uniqueMember" };

    /* specify search constraints to search subtree */
    SearchControls constraints = new SearchControls();

    constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
    constraints.setCountLimit(0);
    constraints.setTimeLimit(0);

    constraints.setReturningAttributes(returnAttributes);
    /*
            Entry user = null;
            try {
    user = searcher.getUser(LdapConstants.ldapAttrLogin, login, context);
            } catch (NamingException e) {
               throw new LdapException("getUser NamingException" + e.getMessage(), e);
            }
       String DN = null;
            if (user == null) {
               logger.info("USER DOES NOT EXIST");
               return false;
            } else {
          DN = user.getName().toString();
               if (DN != null) {
      logger.info("DN = " + DN);
               }
       }
    */

    //result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember="+getUserDN(login)+")", constraints);
    result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember=" + DN + ")", constraints);

    if (result.hasMore()) {
        if (debug) {
            SearchResult sResult = (SearchResult) result.next();
            logger.info("Read Admin Roles Object with members: " + sResult.getAttributes().toString());
        }
        return true;
    } else if (debug)
        logger.info("Failed to find admin object with member " + DN);

    return false;
}

From source file:org.wso2.carbon.appfactory.userstore.internal.OTLDAPUtil.java

public static NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts,
        DirContext dirContext, String userSearchBase) throws UserStoreException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    if (returnedAtts != null && returnedAtts.length > 0) {
        searchCtls.setReturningAttributes(returnedAtts);
    }/*from ww w.ja v  a  2  s . com*/
    try {
        return dirContext.search(userSearchBase, searchFilter, searchCtls);
    } catch (NamingException e) {
        log.error("Search failed.", e);
        throw new UserStoreException(e.getMessage());
    }
}

From source file:org.ow2.proactive.addons.ldap_query.LDAPClient.java

public String searchQueryLDAP() {
    NamingEnumeration results = null;
    ObjectMapper mapper = new ObjectMapper();
    Response response;//from   ww  w  . ja v a 2 s  . com
    String resultOutput = new String();
    List<Map<String, String>> attributesList = new LinkedList<>();

    String[] attributesToReturn = splitAttributes(allLDAPClientParameters.get(ARG_SELECTED_ATTRIBUTES));
    try {
        ldapConnection = LDAPConnectionUtility.connect(allLDAPClientParameters.get(ARG_URL),
                allLDAPClientParameters.get(ARG_DN_BASE), allLDAPClientParameters.get(ARG_USERNAME),
                allLDAPClientParameters.get(ARG_PASSWORD));
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (attributesToReturn.length > 0) {
            controls.setReturningAttributes(attributesToReturn);
        }
        results = ldapConnection.search(
                getFullLdapSearchBase(allLDAPClientParameters.get(ARG_DN_BASE),
                        allLDAPClientParameters.get(ARG_SEARCH_BASE)),
                allLDAPClientParameters.get(ARG_SEARCH_FILTER), controls);

        // Iterate through all attributes in the result of search query
        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();

            if (attributes != null && attributes.size() > 0) {
                NamingEnumeration ae = attributes.getAll();
                Map<String, String> attributesMap = new HashMap<>();
                while (ae.hasMore()) {
                    Attribute attribute = (Attribute) ae.next();
                    attributesMap.put(attribute.getID(), attribute.get().toString());
                }
                attributesList.add(attributesMap);
            }
        }
        response = new LDAPResponse("Ok", attributesList);
    } catch (Exception e) {
        response = new ErrorResponse("Error", e.toString());
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (ldapConnection != null) {
            try {
                ldapConnection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    try {
        resultOutput = mapper.writeValueAsString(response);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return resultOutput;
}

From source file:org.gbif.portal.registration.LDAPUtils.java

/**
 * Gets the common, phone and email for the
 * @param uid To use for searching in LDAP  
 * @return An array containing the 3 strings
 * @throws NamingException On error/* w  w  w  . j a  va 2  s.c o m*/
 */
@SuppressWarnings("unchecked")
public List<UserLogin> getUsernamePasswordForEmail(String email) throws NamingException {
    DirContext ctx = getUserContext();
    NamingEnumeration searchResults = ctx.search("", "mail=" + email, null, new SearchControls());
    List<UserLogin> uls = new ArrayList<UserLogin>();
    while (searchResults.hasMore()) {
        SearchResult sr = (SearchResult) searchResults.next();
        Attributes attributes = sr.getAttributes();
        debugAttributes(attributes);
        UserLogin ul = new UserLogin();
        ul.setSurname((String) attributes.get("sn").get());
        ul.setFirstName((String) attributes.get("givenName").get());
        ul.setEmail((String) attributes.get("mail").get());
        ul.setUsername((String) attributes.get("uid").get());
        uls.add(ul);
    }
    return uls;
}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.LdapManagerImpl.java

public Schema getSchema(String subschemaSubentry, LdapConnectionParams params) {
    try {/*w ww .j av a 2  s .com*/
        SearchControls cons = new SearchControls();
        // only interested in the first result
        cons.setCountLimit(1);
        // set time limit for this search to 30 sec, should be sufficient even for large LDAPs
        cons.setTimeLimit(30000);

        SchemaMapper mapper = new SchemaMapper();
        cons.setReturningAttributes(mapper.getReturningAttributes());
        cons.setSearchScope(SearchControls.OBJECT_SCOPE);

        Schema schema = (Schema) m_templateFactory.getLdapTemplate(params).search(subschemaSubentry,
                LdapManager.FILTER_ALL_CLASSES, cons, new SchemaMapper(), LdapManager.NULL_PROCESSOR).get(0);

        return schema;
    } catch (DataIntegrityViolationException e) {
        LOG.debug("Retrieving schema failed.", e);
        throw new UserException("searchSchema.violation.error");
    } catch (UncategorizedLdapException e) {
        LOG.debug("Retrieving schema failed. Anonymous-binding may be disabled", e);
        throw new UserException("searchSchema.anonymousBinding.error");
    }
}

From source file:org.pegadi.server.user.LDAPUserServerImpl.java

/**
 * Find a user by ID.  This id may be a compound ID, like the
 * LDAP database's DN structure. Otherwise it might be an empoyeeNumber
 * like this implementation use.//from   w  w  w  .j ava  2  s. c  o  m
 * <p/>
 * Tries first to get the user by pegadiID, which is the old method.
 *
 * @param id
 * @return the Userobject if found, or null if not.
 */
public Person getUserById(String id) {
    if (id == null || id.equals(0))
        return null;
    Person user = null;
    String[] getThese = { "sn", "gn", "mail", "uid", "employeeNumber" };
    try {
        //int nr = Integer.parseInt(id); //only needed if we can get the dn.
        SearchControls sc = new SearchControls();
        sc.setReturningAttributes(getThese);
        NamingEnumeration e = ctx.search("ou=people", "employeeNumber=" + id, sc);
        if (e.hasMore()) {
            SearchResult sr = (SearchResult) e.next();
            user = this.createUser(sr.getAttributes());
        }
    } catch (NamingException e) {
        log.error("An error occured while trying to getUserById(" + id + ")", e);
        /*FIXME does not work.
         * try {
                
        Attributes attrs = ctx.getAttributes("dn=" + id,getThese);
        return createUser(attrs);
                
        } catch (NamingException e) {
        e.printStackTrace();
        }*/
    }
    return user;
}

From source file:org.ballerinalang.stdlib.ldap.nativeimpl.GetLdapScopesOfUser.java

private static String[] getLDAPGroupsListOfUser(String userName, List<String> searchBase,
        CommonLdapConfiguration ldapAuthConfig, DirContext ldapConnectionContext)
        throws UserStoreException, NamingException {
    if (userName == null) {
        throw new BallerinaException("userName value is null.");
    }//from  w w w.j ava2  s.c o  m

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    // Load normal roles with the user
    String searchFilter = ldapAuthConfig.getGroupNameListFilter();
    String roleNameProperty = ldapAuthConfig.getGroupNameAttribute();
    String membershipProperty = ldapAuthConfig.getMembershipAttribute();
    String nameInSpace = getNameInSpaceForUserName(userName, ldapAuthConfig, ldapConnectionContext);

    if (membershipProperty == null || membershipProperty.length() < 1) {
        throw new BallerinaException("membershipAttribute not set in configuration");
    }

    String membershipValue;
    if (nameInSpace != null) {
        LdapName ldn = new LdapName(nameInSpace);
        if (LdapConstants.MEMBER_UID.equals(ldapAuthConfig.getMembershipAttribute())) {
            // membership value of posixGroup is not DN of the user
            List rdns = ldn.getRdns();
            membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString();
        } else {
            membershipValue = escapeLdapNameForFilter(ldn);
        }
    } else {
        return new String[0];
    }

    searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))";
    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Reading roles with the membershipProperty Property: " + membershipProperty);
    }

    List<String> list = getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty,
            ldapConnectionContext);
    return list.toArray(new String[list.size()]);
}

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

private void doPagedSearch(InitialLdapContext context, String filter, String[] attributes,
        PagedResultMapper mapper) throws NamingException {
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    applyControls(context, pageSize);/* w  w  w.j av  a  2s  .co  m*/

    for (String searchBase : ouSearchBase) {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for items starting at " + searchBase + " (filter = " + filter + ")");
        }

        try {
            int currentPage = 1;
            int startPosition = 0;
            int endPosition = pageSize - 1;
            byte[] cookie = null;

            do {
                String range = startPosition + "-" + endPosition;

                if (logger.isDebugEnabled()) {
                    logger.debug("Starting search on page " + currentPage + " " + range);
                }

                constraints.setReturningAttributes(attributes);
                NamingEnumeration<SearchResult> results = context.search(searchBase, filter, constraints);

                try {
                    mapResults(mapper, results);
                } catch (PartialResultException pre) {
                    // We're paging so we dont care and don't log anymore
                }

                // Examine the paged results control response
                Control[] controls = context.getResponseControls();
                if (controls != null) {
                    for (int index = 0; index < controls.length; index++) {
                        if (controls[index] instanceof PagedResultsResponseControl) {
                            PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[index];
                            cookie = prrc.getCookie();
                        }
                    }
                }

                applyControls(context, pageSize, cookie);
                startPosition = startPosition + pageSize;
                endPosition = endPosition + pageSize;
                currentPage++;
            } while ((cookie != null) && (cookie.length != 0));
        } catch (NamingException e) {
            mapper.processException(e);
            logger.error("Possible configuration error! Did you enter your OUs correctly? [" + searchBase + "]",
                    e);
        }
    }
}