Java Code Examples for javax.naming.directory.DirContext#search()

The following examples show how to use javax.naming.directory.DirContext#search() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LDAPAuthenticationService.java    From proxylive with MIT License 6 votes vote down vote up
public String findGroupBySID(DirContext ctx, String ldapSearchBase, String sid) throws NamingException {

        String searchFilter = "(&(objectClass=group)(objectSid=" + sid + "))";

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

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

        if (results.hasMoreElements()) {
            SearchResult searchResult = (SearchResult) results.nextElement();

            //make sure there is not another item available, there should be only 1 match
            if (results.hasMoreElements()) {
                logger.warn("Matched multiple groups for the group with SID: " + sid);
                return null;
            } else {
                return (String) searchResult.getAttributes().get("sAMAccountName").get();
            }
        }
        return null;
    }
 
Example 2
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public void search(final Name base, final String filter, final SearchControls controls,
		NameClassPairCallbackHandler handler, DirContextProcessor processor) {

	// Create a SearchExecutor to perform the search.
	SearchExecutor se = new SearchExecutor() {
		public NamingEnumeration executeSearch(DirContext ctx) throws javax.naming.NamingException {
			return ctx.search(base, filter, controls);
		}
	};
	if (handler instanceof ContextMapperCallbackHandler) {
		assureReturnObjFlagSet(controls);
	}
	search(se, handler, processor);
}
 
Example 3
Source File: LdapTemplateSortedSearchITest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
public void testSearch_SortControl() {
    SearchExecutor searchExecutor = new SearchExecutor() {
        public NamingEnumeration executeSearch(DirContext ctx)
                throws NamingException {
            return ctx.search(BASE, FILTER_STRING, searchControls);
        }
    };
    SortControlDirContextProcessor requestControl;

    // Prepare for first search
    requestControl = new SortControlDirContextProcessor("cn");
    tested.search(searchExecutor, callbackHandler, requestControl);
    int resultCode = requestControl.getResultCode();
    boolean sorted = requestControl.isSorted();
    assertThat("Search result should have been sorted: " + resultCode, sorted).isTrue();
    List list = callbackHandler.getList();
    assertSortedList(list);
}
 
Example 4
Source File: LdapDao.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public List<T> findAll(final DirContext ctx, final String organizationalUnit) throws NamingException
{
  final LinkedList<T> list = new LinkedList<T>();
  NamingEnumeration< ? > results = null;
  final SearchControls controls = new SearchControls();
  controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  final String searchBase = getSearchBase(organizationalUnit);
  results = ctx.search(searchBase, "(objectclass=" + getObjectClass() + ")", controls);
  while (results.hasMore()) {
    final SearchResult searchResult = (SearchResult) results.next();
    final String dn = searchResult.getName();
    final Attributes attributes = searchResult.getAttributes();
    list.add(mapToObject(dn, searchBase, attributes));
  }
  return list;
}
 
Example 5
Source File: BasicAuthLDAPTest.java    From apiman with Apache License 2.0 6 votes vote down vote up
@Test @Ignore
public void testLdap() throws Exception {
    DirContext ctx = createContext();
    Assert.assertNotNull(ctx);

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<SearchResult> result = ctx.search("o=apiman", "(ObjectClass=*)", controls);

    System.out.println(" ==== Search Results ====");
    while (result.hasMore()) {
        SearchResult entry = result.next();
        System.out.println(" ===> " + entry.getName());
    }

}
 
Example 6
Source File: LDAPUtil.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * @param ctx
 * @param ldapSearchBase
 * @param sid
 * @return
 * @throws NamingException
 */
public static String findGroupBySID(DirContext ctx, String ldapSearchBase, String sid,
                                    String userAttribute) throws NamingException {

    String searchFilter = "(&(objectClass=group)(objectSid=" + sid + "))";

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

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

    if (results.hasMoreElements()) {
        SearchResult searchResult = (SearchResult) results.nextElement();

        // make sure there is not another item available, there should be only 1 match
        if (results.hasMoreElements()) {
            log.error("Matched multiple groups for the group with SID: " + sid);
            return null;
        } else {
            return (String) searchResult.getAttributes().get(userAttribute).get();
        }
    }
    return null;
}
 
Example 7
Source File: LdapDao.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public T findById(final DirContext ctx, final Object id, final String... organizationalUnits) throws NamingException
{
  NamingEnumeration< ? > results = null;
  final SearchControls controls = new SearchControls();
  controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  final String searchBase = getSearchBase(organizationalUnits);
  final String args = "(&(objectClass=" + getObjectClass() + ")(" + getIdAttrId() + "=" + buildId(id) + "))";
  results = ctx.search(searchBase, args, controls);
  if (results.hasMore() == false) {
    return null;
  }
  final SearchResult searchResult = (SearchResult) results.next();
  final String dn = searchResult.getName();
  final Attributes attributes = searchResult.getAttributes();
  if (results.hasMore() == true) {
    log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + id);
  }
  return mapToObject(dn, searchBase, attributes);
}
 
Example 8
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public void search(final Name base, final String filter, final SearchControls controls,
		NameClassPairCallbackHandler handler) {

	// Create a SearchExecutor to perform the search.
	SearchExecutor se = new SearchExecutor() {
		public NamingEnumeration executeSearch(DirContext ctx) throws javax.naming.NamingException {
			return ctx.search(base, filter, controls);
		}
	};
	if (handler instanceof ContextMapperCallbackHandler) {
		assureReturnObjFlagSet(controls);
	}
	search(se, handler);
}
 
Example 9
Source File: LdapAuthenticator.java    From presto with Apache License 2.0 5 votes vote down vote up
private NamingEnumeration<SearchResult> searchGroupMembership(String user, DirContext context)
        throws NamingException
{
    String userBase = userBaseDistinguishedName.get();
    String searchFilter = replaceUser(groupAuthorizationSearchPattern.get(), user);
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    return context.search(userBase, searchFilter, searchControls);
}
 
Example 10
Source File: ApacheDSRootDseServlet.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException {
    try {
        resp.setContentType("text/plain");
        PrintWriter out = resp.getWriter();

        out.println("*** ApacheDS RootDSE ***\n");

        DirContext ctx = new InitialDirContext(this.createEnv());

        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(new String[] { "*", "+" });
        ctls.setSearchScope(SearchControls.OBJECT_SCOPE);

        NamingEnumeration<SearchResult> result = ctx.search("", "(objectClass=*)", ctls);
        if (result.hasMore()) {
            SearchResult entry = result.next();
            Attributes as = entry.getAttributes();

            NamingEnumeration<String> ids = as.getIDs();
            while (ids.hasMore()) {
                String id = ids.next();
                Attribute attr = as.get(id);
                for (int i = 0; i < attr.size(); ++i) {
                    out.println(id + ": " + attr.get(i));
                }
            }
        }
        ctx.close();

        out.flush();
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
 
Example 11
Source File: LdapUtil.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
/**
     * list ldap entries
     *
     * @throws NamingException
     */
//TODO split list Entries with get Max uidNumber
public static int listEntries() throws NamingException {
    DirContext context = getLdapContext(User.getLdapAdminUser());
    int maxUidNumber = 10009;

    String searchFilter = "(objectClass=inetOrgPerson)";
    String[] requiredAttributes = {"uid", "cn", "sn", "uidNumber"};

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

    NamingEnumeration users;
    try {
        users = context.search(BASE_DN, searchFilter, controls);
        while (users.hasMore()) {
            SearchResult searchResult = (SearchResult) users.next();
            Attributes attr = searchResult.getAttributes();
            String commonName = attr.get("cn").get(0).toString();
            String uniqueName = attr.get("uid").get(0).toString();
            String sn = attr.get("sn").get(0).toString();
            int uidNumber = Integer.parseInt(attr.get("uidNumber").get(0).toString());
            maxUidNumber = maxUidNumber > uidNumber ? maxUidNumber : uidNumber;
            LOGGER.info("Name = " + commonName);
            LOGGER.info("Uid = " + uniqueName);
            LOGGER.info("sn = " + sn);
            LOGGER.info("uidNumber = " + uidNumber);
        }
    }
    catch (NamingException e) {
        LOGGER.error(e.getMessage());
    }
    return maxUidNumber;
}
 
Example 12
Source File: LDAPLoginManagerImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Find the user dn with its uid
 * 
 * @param uid
 * @param ctx
 * @return user's dn
 */
private String searchUserDN(final String uid, final DirContext ctx) {
    if (ctx == null) {
        return null;
    }

    final List<String> ldapBases = LDAPLoginModule.getLdapBases();
    final String objctClass = LDAPLoginModule.getLdapUserObjectClass();
    final String[] serachAttr = { "dn" };

    final String ldapUserIDAttribute = LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
    final String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))";
    final SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(serachAttr);

    String userDN = null;
    for (final String ldapBase : ldapBases) {
        try {
            final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls);
            while (enm.hasMore()) {
                final SearchResult result = enm.next();
                userDN = result.getNameInNamespace();
            }
            if (userDN != null) {
                break;
            }
        } catch (final NamingException e) {
            log.error("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e);
        }
    }

    return userDN;
}
 
Example 13
Source File: LDAPManager.java    From Benchmark with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Search LDAPPerson by name
 * 
 * @param person
 *            to search
 * @return true if record found
 */
@SuppressWarnings("unused")
private boolean search(LDAPPerson person) {
	try {

		DirContext ctx = getDirContext();
		String base = "ou=users,ou=system";

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

		String filter = "(&(objectclass=person)(uid=" + ESAPI_Encoder.encodeForLDAP(person.getName()) + "))";

		NamingEnumeration<SearchResult> results = ctx.search(base, filter, sc);

		while (results.hasMore()) {
			SearchResult sr = (SearchResult) results.next();
			Attributes attrs = sr.getAttributes();

			Attribute attr = attrs.get("uid");
			if (attr != null) {
				// logger.debug("record found " + attr.get());
				// System.out.println("record found " + attr.get());
			}
		}
		ctx.close();

		return true;
	} catch (Exception e) {
		System.out.println("LDAP error search: ");
		// logger.error(e, e);
		e.printStackTrace();
		return false;
	}
}
 
Example 14
Source File: LdapUtil.java    From jeecg with Apache License 2.0 5 votes vote down vote up
/**
 * @param base
 *            :根节点(在这里是"dc=example,dc=com")
 * @param scope
 *            :搜索范围,分为"base"(本节点),"one"(单层),""(遍历)
 * @param filter
 *            :指定子节点(格式为"(objectclass=*)",*是指全部,你也可以指定某一特定类型的树节点)
 */
public static String getDN(String base, String scope, String filter,
		DirContext dc) {
	String dn = null;
	SearchControls sc = new SearchControls();
	if (scope.equals("base")) {
		sc.setSearchScope(SearchControls.OBJECT_SCOPE);
	} else if (scope.equals("one")) {
		sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
	} else {
		sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
	}
	NamingEnumeration<?> ne = null;
	try {
		ne = dc.search(base, filter, sc);
		while (ne.hasMore()) {
			//System.out.println();
			SearchResult sr = (SearchResult) ne.next();
			String name = sr.getName();
			if (base != null && !base.equals("")) {
				LogUtil.info("entry: " + name + "," + base);
			} else {
				LogUtil.info("entry: " + name);
			}
			dn = name + "," + base;
			break;
		}
	} catch (Exception nex) {
		System.err.println("Error: " + nex.getMessage());
		nex.printStackTrace();
	}
	return dn;
}
 
Example 15
Source File: LdapClient.java    From iaf with Apache License 2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(DirContext context, String searchDN, String filter, String[] returnedAttributes, int scope) throws NamingException {
  	if (log.isDebugEnabled()) log.debug("searchDN ["+searchDN+"] filter ["+filter+"] no params returnedAttributes ["+arrayToString(returnedAttributes,",")+"]");
SearchControls sc = new SearchControls();
sc.setSearchScope(scope);
if (returnedAttributes!=null) {
	sc.setReturningAttributes(returnedAttributes);
}
return context.search(searchDN, filter, sc);			
  }
 
Example 16
Source File: LdapUnboundidZapdotConnectionTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Test
public void testDirContext() throws Exception {

    // Test using the good ol' JDNI-LDAP integration
    final DirContext dirContext = embeddedLdapRule.dirContext();
    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final NamingEnumeration<javax.naming.directory.SearchResult> resultNamingEnumeration =
            dirContext.search(DOMAIN_DSN, "(objectClass=person)", searchControls);
    assertEquals(24, Iterators.size(Iterators.forEnumeration(resultNamingEnumeration)));
}
 
Example 17
Source File: ReadOnlyLDAPUserStoreManager.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
protected List<String> getAttributeListOfOneElement(String searchBases, String searchFilter,
                                                    SearchControls searchCtls)
        throws UserStoreException {
    List<String> list = new ArrayList<String>();
    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    try {
        dirContext = connectionSource.getContext();
        // handle multiple search bases
        String[] searchBaseArray = searchBases.split("#");
        for (String searchBase : searchBaseArray) {
            try {
                answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);
                int count = 0;
                if (answer.hasMore()) {
                    while (answer.hasMore()) {
                        if (count > 0) {
                            log.error("More than element user exist with name");
                            throw new UserStoreException("More than element user exist with name");
                        }
                        SearchResult sr = (SearchResult) answer.next();
                        count++;
                        list = parseSearchResult(sr, null);
                    }
                    break;
                }
            } catch (NamingException e) {
                //ignore
                if (log.isDebugEnabled()) {
                    log.debug(e);
                }
            }
        }
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return list;
}
 
Example 18
Source File: LdapAuthenticator.java    From onedev with MIT License 4 votes vote down vote up
private Collection<String> retrieveGroupsByFilter(DirContext ctx, DirContext referralCtx, String userDN) {
	Collection<String> groupNames = new HashSet<>();
	try {
    	SearchGroupsUsingFilter groupRetrieval = (SearchGroupsUsingFilter) getGroupRetrieval();
    	String groupNameAttribute = groupRetrieval.getGroupNameAttribute();
        Name groupSearchBase = new CompositeName().add(groupRetrieval.getGroupSearchBase());
        String groupSearchFilter = StringUtils.replace(groupRetrieval.getGroupSearchFilter(), "{0}", userDN);
        groupSearchFilter = StringUtils.replace(groupSearchFilter, "\\", "\\\\");

        logger.debug("Evaluated group search filter: " + groupSearchFilter);
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchControls.setReturningAttributes(new String[]{groupNameAttribute});
        searchControls.setReturningObjFlag(true);

    	NamingEnumeration<SearchResult> results;
        if (referralCtx != null)
            results = referralCtx.search(groupSearchBase, groupSearchFilter, searchControls);
        else
            results = ctx.search(groupSearchBase, groupSearchFilter, searchControls);
        if (results != null) {
            while (results.hasMore()) {
            	SearchResult searchResult = (SearchResult) results.next();
                Attributes searchResultAttributes = searchResult.getAttributes();
                if (searchResultAttributes == null 
                		|| searchResultAttributes.get(groupNameAttribute) == null
                        || searchResultAttributes.get(groupNameAttribute).get() == null) {
                    throw new RuntimeException("Can not find attribute '" 
                    		+ groupNameAttribute + "' in the returned group object.");
                }
                groupNames.add((String) searchResultAttributes.get(groupNameAttribute).get());
            }
        }
       } catch (PartialResultException pre) {
           logger.warn("Partial exception detected. You may try to set property " +
           		"'follow referrals' to true to avoid this exception.", pre);
	} catch (NamingException e) {
		logger.error("Error retrieving groups by filter", e);
	}
	return groupNames;
}
 
Example 19
Source File: LdapManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Check if the given DN matches the group search filter
 *
 * @param dn the absolute DN of the node to check
 * @return true if the given DN is matching the group filter. false oterwise.
 * @throws NamingException if the search for the dn fails.
 */
public boolean isGroupDN(LdapName dn) throws NamingException {
    Log.debug("LdapManager: Trying to check if DN is a group. DN: {}, Base DN: {} ...", dn, baseDN);

    // is it a sub DN of the base DN?
    if (!dn.startsWith(baseDN)
        && (alternateBaseDN == null || !dn.startsWith(alternateBaseDN))) {
        if (Log.isDebugEnabled()) {
            Log.debug("LdapManager: DN ({}) does not fit to baseDN ({},{})", dn, baseDN, alternateBaseDN);
        }
        return false;
    }

    DirContext ctx = null;
    try {
        Log.debug("LdapManager: Starting LDAP search to check group DN: {}", dn);
        // Search for the group in the node with the given DN.
        // should return the group object itself if is matches the group filter
        ctx = getContext(dn);
        // only search the object itself.
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
        constraints.setReturningAttributes(new String[]{});
        String filter = MessageFormat.format(getGroupSearchFilter(), "*");
        NamingEnumeration<SearchResult> answer = ctx.search("", filter, constraints);

        Log.debug("LdapManager: ... group check search finished for DN: {}", dn);

        boolean result = (answer != null && answer.hasMoreElements());

        if (answer != null) {
            answer.close();
        }
        Log.debug("LdapManager: DN is group: {}? {}!", dn, result);
        return result;
    }
    catch (final Exception e) {
        Log.debug("LdapManager: Exception thrown when checking if DN is a group {}", dn, e);
        throw e;
    }
    finally {
        try {
            if (ctx != null)
                ctx.close();
        }
        catch (Exception ex) {
            Log.debug("An exception occurred while trying to close a LDAP context after trying to verify that DN '{}' is a group.", dn, ex);
        }
    }
}
 
Example 20
Source File: LdapAccessServiceBean.java    From development with Apache License 2.0 4 votes vote down vote up
private <T> List<T> searchByLimit(Properties properties, String baseDN,
        String filter, ILdapResultMapper<T> mapper, boolean checkAttribute,
        int searchLimit) throws NamingException {
    List<T> list = new ArrayList<T>();
    NamingEnumeration<SearchResult> namingEnum = null;

    DirContext ctx = getDirContext(properties);

    SearchControls ctls = new SearchControls();
    String[] attrIds = mapper.getAttributes();
    ctls.setReturningAttributes(attrIds);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setCountLimit(searchLimit);

    try {
        namingEnum = ctx.search(baseDN, escapeLDAPSearchFilter(filter),
                ctls);
        int count = 0;
        while (count++ < searchLimit && hasMoreEnum(namingEnum)) {
            SearchResult res = namingEnum.next();
            Attributes ldapAttributes = res.getAttributes();
            String[] values = new String[attrIds.length];
            for (int i = 0; i < values.length; i++) {
                Attribute ldapAttr = ldapAttributes
                        .get(escapeLDAPSearchFilter(attrIds[i]));
                if (checkAttribute && ldapAttr == null) {
                    NamingException e = new NamingException(
                            "Unknown LDAP attribute " + attrIds[i]);
                    throw e;
                }
                if (ldapAttr != null && ldapAttr.get() != null) {
                    values[i] = ldapAttr.get().toString();
                }
            }
            T t = mapper.map(values);
            if (t != null) {
                list.add(t);
            }
        }
    } finally {
        if (namingEnum != null) {
            try {
                namingEnum.close();
            } finally {
                closeContext(ctx);
            }
        }
        closeContext(ctx);
    }
    return list;
}