javax.naming.directory.SearchControls Java Examples

The following examples show how to use javax.naming.directory.SearchControls. 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: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testAuthenticateQueryPasswordWhenNoUserWasFoundShouldThrowEmptyResult() throws Exception {

	when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock);

	 when(dirContextMock.search(
				any(Name.class),
				any(String.class),
				any(SearchControls.class))).thenReturn(namingEnumerationMock);

		when(namingEnumerationMock.hasMore()).thenReturn(false);

	try {
		tested.authenticate(query, "");
		fail("Expected Exception");
	}catch(EmptyResultDataAccessException success) {}
	verify(dirContextMock).close();
}
 
Example #2
Source File: EventSupport.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds <tt>l</tt> to list of listeners interested in <tt>nm</tt>
 * and filter.
 */
synchronized void addNamingListener(String nm, String filter,
    SearchControls ctls, NamingListener l) throws NamingException {

    if (l instanceof ObjectChangeListener ||
        l instanceof NamespaceChangeListener) {
        NotifierArgs args = new NotifierArgs(nm, filter, ctls, l);

        NamingEventNotifier notifier = notifiers.get(args);
        if (notifier == null) {
            notifier = new NamingEventNotifier(this, ctx, args, l);
            notifiers.put(args, notifier);
        } else {
            notifier.addNamingListener(l);
        }
    }
    if (l instanceof UnsolicitedNotificationListener) {
        // Add listener to this's list of unsolicited notifiers
        if (unsolicited == null) {
            unsolicited = new Vector<>(3);
        }
        unsolicited.addElement((UnsolicitedNotificationListener)l);
    }
}
 
Example #3
Source File: LdapAuthenticator.java    From dropwizard-auth-ldap with Apache License 2.0 6 votes vote down vote up
private boolean filterByGroup(AutoclosingLdapContext context, String sanitizedUsername) throws NamingException {
    final Set<String> restrictedToGroups = configuration.getRestrictToGroups();
    if (restrictedToGroups.isEmpty()) {
        return true;
    }

    final StringBuilder groupFilter = new StringBuilder();
    for (String group : restrictedToGroups) {
        final String sanitizedGroup = sanitizeEntity(group);
        groupFilter.append(String.format("(%s=%s)", configuration.getGroupNameAttribute(), sanitizedGroup));
    }

    final String filter = String.format("(&(%s=%s)(|%s))", configuration.getGroupMembershipAttribute(),
        userNameBaseOnGroupClass(sanitizedUsername), groupFilter.toString());

    final NamingEnumeration<SearchResult> result = context.search(configuration.getGroupFilter(), filter, new SearchControls());
    try {
        return result.hasMore();
    } finally {
        result.close();
    }
}
 
Example #4
Source File: ContextEnumerator.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
protected ContextEnumerator(Context context, int scope, String contextName,
                         boolean returnSelf)
    throws NamingException {
    if(context == null) {
        throw new IllegalArgumentException("null context passed");
    }

    root = context;

    // No need to list children if we're only searching object
    if (scope != SearchControls.OBJECT_SCOPE) {
        children = getImmediateChildren(context);
    }
    this.scope = scope;
    this.contextName = contextName;
    // pretend root is processed, if we're not supposed to return ourself
    rootProcessed = !returnSelf;
    prepNextChild();
}
 
Example #5
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 #6
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testSearch_NameNotFoundException() throws Exception {
	expectGetReadOnlyContext();

	final SearchControls controls = searchControlsRecursive();
	controls.setReturningObjFlag(false);

	javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException("some text");
	when(dirContextMock.search(
               eq(nameMock),
               eq("(ou=somevalue)"),
               argThat(new SearchControlsMatcher(controls)))).thenThrow(ne);

	try {
		tested.search(nameMock, "(ou=somevalue)", handlerMock);
		fail("NameNotFoundException expected");
	}
	catch (NameNotFoundException expected) {
		assertThat(true).isTrue();
	}
	verify(dirContextMock).close();
}
 
Example #7
Source File: Organization2Activedirectory.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public boolean delete(Organizations organization) throws Exception {
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(&(objectClass=organizationalUnit)(description="+organization.getId()+"))", constraints);
		String dn="";
		if (results == null || !results.hasMore()) {
			
		}else{
			SearchResult sr = (SearchResult) results.next();
			dn =sr.getNameInNamespace();
			ldapUtils.getCtx().destroySubcontext(dn);
		}
		
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return super.delete(organization);
}
 
Example #8
Source File: Organization2Ldap.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public boolean delete(Organizations organization)  throws Exception{
	logger.info("delete");
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(&(objectClass=organizationalUnit)(description="+organization.getId()+"))", constraints);
		String dn="";
		if (results == null || !results.hasMore()) {
			
		}else{
			SearchResult sr = (SearchResult) results.next();
			dn =sr.getNameInNamespace();
			ldapUtils.getCtx().destroySubcontext(dn);
		}
		
		ldapUtils.close();
	
	return super.delete(organization);
}
 
Example #9
Source File: EventSupport.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds <tt>l</tt> to list of listeners interested in <tt>nm</tt>
 * and filter.
 */
synchronized void addNamingListener(String nm, String filter,
    SearchControls ctls, NamingListener l) throws NamingException {

    if (l instanceof ObjectChangeListener ||
        l instanceof NamespaceChangeListener) {
        NotifierArgs args = new NotifierArgs(nm, filter, ctls, l);

        NamingEventNotifier notifier = notifiers.get(args);
        if (notifier == null) {
            notifier = new NamingEventNotifier(this, ctx, args, l);
            notifiers.put(args, notifier);
        } else {
            notifier.addNamingListener(l);
        }
    }
    if (l instanceof UnsolicitedNotificationListener) {
        // Add listener to this's list of unsolicited notifiers
        if (unsolicited == null) {
            unsolicited = new Vector<>(3);
        }
        unsolicited.addElement((UnsolicitedNotificationListener)l);
    }
}
 
Example #10
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
private SearchControls searchControlsForQuery(LdapQuery query, boolean returnObjFlag) {
    SearchControls searchControls = getDefaultSearchControls(
            defaultSearchScope,
            returnObjFlag,
            query.attributes());

    if(query.searchScope() != null) {
        searchControls.setSearchScope(query.searchScope().getId());
    }

    if(query.countLimit() != null) {
        searchControls.setCountLimit(query.countLimit());
    }

    if(query.timeLimit() != null) {
        searchControls.setTimeLimit(query.timeLimit());
    }
    return searchControls;
}
 
Example #11
Source File: LdapTemplateSearchResultITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testSearch_SearchScope_LimitedAttrs_ContextMapper_Name() {
	contextMapper.setExpectedAttributes(CN_SN_ATTRS);
	contextMapper.setExpectedValues(CN_SN_VALUES);
	contextMapper.setAbsentAttributes(ABSENT_ATTRIBUTES);
	List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, contextMapper);
	assertThat(list).hasSize(1);
}
 
Example #12
Source File: ContinuationDirContext.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            String filter,
                            SearchControls cons)
throws NamingException {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(), filter, cons);
}
 
Example #13
Source File: LdapTemplateSearchResultNamespaceConfigITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testSearch_SearchScope_LimitedAttrs_ContextMapper() {
	contextMapper.setExpectedAttributes(CN_SN_ATTRS);
	contextMapper.setExpectedValues(CN_SN_VALUES);
	contextMapper.setAbsentAttributes(ABSENT_ATTRIBUTES);
	List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, contextMapper);
	assertThat(list).hasSize(1);
}
 
Example #14
Source File: ContextEnumerator.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public Binding next() throws NamingException {
    if (!rootProcessed) {
        rootProcessed = true;
        return new Binding("", root.getClass().getName(),
                           root, true);
    }

    if (scope != SearchControls.OBJECT_SCOPE && hasMoreDescendants()) {
        return getNextDescendant();
    }

    throw new NoSuchElementException();
}
 
Example #15
Source File: JNDIProviderImpl.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
private SearchControls makeSearchControls()
{
    final SearchControls searchControls = new SearchControls();
    searchControls.setReturningObjFlag( false );
    searchControls.setReturningAttributes( new String[0] );
    searchControls.setSearchScope( searchHelper.getSearchScope().getJndiScopeInt() );
    final String[] returnAttributes = searchHelper.getAttributes() == null
            ? null
            : searchHelper.getAttributes().toArray( new String[searchHelper.getAttributes().size()] );

    searchControls.setReturningAttributes( returnAttributes );
    searchControls.setTimeLimit( searchHelper.getTimeLimit() );
    searchControls.setCountLimit( searchHelper.getMaxResults() );
    return searchControls;
}
 
Example #16
Source File: NotifierArgs.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
NotifierArgs(String name, int scope, NamingListener l) {
    this(name, "(objectclass=*)", null, l);

    // if scope is not default, create search ctl and set it
    if (scope != EventContext.ONELEVEL_SCOPE) {
        controls = new SearchControls();
        controls.setSearchScope(scope);
    }
}
 
Example #17
Source File: NotifierArgs.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private boolean checkControls(SearchControls ctls) {
    if ((controls == null || ctls == null)) {
        return ctls == controls;
    }
    // ctls are nonempty

    return (controls.getSearchScope() == ctls.getSearchScope()) &&
        (controls.getTimeLimit() == ctls.getTimeLimit()) &&
        (controls.getDerefLinkFlag() == ctls.getDerefLinkFlag()) &&
        (controls.getReturningObjFlag() == ctls.getReturningObjFlag()) &&
        (controls.getCountLimit() == ctls.getCountLimit()) &&
        checkStringArrays(controls.getReturningAttributes(),
            ctls.getReturningAttributes());
}
 
Example #18
Source File: TestLdapGroupsMapping.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetGroupsWithConnectionClosed() throws IOException, NamingException {
  // The case mocks connection is closed/gc-ed, so the first search call throws CommunicationException,
  // then after reconnected return the user NamingEnumeration first, and then the group
  when(mockContext.search(anyString(), anyString(), any(Object[].class),
      any(SearchControls.class)))
      .thenThrow(new CommunicationException("Connection is closed"))
      .thenReturn(mockUserNamingEnum, mockGroupNamingEnum);
  
  // Although connection is down but after reconnected it still should retrieve the result groups
  doTestGetGroups(Arrays.asList(testGroups), 1 + 2); // 1 is the first failure call 
}
 
Example #19
Source File: ContextEnumerator.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public Binding next() throws NamingException {
    if (!rootProcessed) {
        rootProcessed = true;
        return new Binding("", root.getClass().getName(),
                           root, true);
    }

    if (scope != SearchControls.OBJECT_SCOPE && hasMoreDescendants()) {
        return getNextDescendant();
    }

    throw new NoSuchElementException();
}
 
Example #20
Source File: ContextEnumerator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public Binding next() throws NamingException {
    if (!rootProcessed) {
        rootProcessed = true;
        return new Binding("", root.getClass().getName(),
                           root, true);
    }

    if (scope != SearchControls.OBJECT_SCOPE && hasMoreDescendants()) {
        return getNextDescendant();
    }

    throw new NoSuchElementException();
}
 
Example #21
Source File: ActiveDirectoryUtils.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public ActiveDirectoryUtils(String providerUrl, String principal, String credentials, String baseDN,
        String domain) {
    this.providerUrl = providerUrl;
    this.principal = principal;
    this.credentials = credentials;
    this.searchScope = SearchControls.SUBTREE_SCOPE;
    this.baseDN = baseDN;
    this.domain = domain.toUpperCase();
}
 
Example #22
Source File: ActiveDirectoryUtils.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public ActiveDirectoryUtils(String providerUrl, String principal, String credentials, String domain) {
    this.providerUrl = providerUrl;
    this.principal = principal;
    this.credentials = credentials;
    this.searchScope = SearchControls.SUBTREE_SCOPE;
    this.domain = domain.toUpperCase();
}
 
Example #23
Source File: ActiveDirectoryGroupRealm.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public List<String> searchForUserName(String containString, LdapContext ldapContext,
    int numUsersToFetch)
        throws NamingException {
  List<String> userNameList = new ArrayList<>();

  SearchControls searchCtls = new SearchControls();
  searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  searchCtls.setCountLimit(numUsersToFetch);

  String searchFilter = String.format("(&(objectClass=*)(%s=*%s*))", this.getUserSearchAttributeName(), containString);

  Object[] searchArguments = new Object[]{containString};

  NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments,
      searchCtls);

  while (answer.hasMoreElements()) {
    SearchResult sr = (SearchResult) answer.next();

    if (log.isDebugEnabled()) {
      log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]");
    }

    Attributes attrs = sr.getAttributes();
    if (attrs != null) {
      NamingEnumeration ae = attrs.getAll();
      while (ae.hasMore()) {
        Attribute attr = (Attribute) ae.next();
        if (attr.getID().toLowerCase().equals(this.getUserSearchAttributeName().toLowerCase())) {
          userNameList.addAll(LdapUtils.getAllAttributeValues(attr));
        }
      }
    }
  }
  return userNameList;
}
 
Example #24
Source File: ContinuationDirContext.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            String filter,
                            SearchControls cons)
throws NamingException {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(), filter, cons);
}
 
Example #25
Source File: ContinuationDirContext.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(Name name,
                            String filter,
                            SearchControls cons)
throws NamingException {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), filter, cons);
}
 
Example #26
Source File: ContinuationDirContext.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            String filterExpr,
                            Object[] args,
                            SearchControls cons)
throws NamingException {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(), filterExpr, args,
                                     cons);
}
 
Example #27
Source File: ContinuationDirContext.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            String filterExpr,
                            Object[] args,
                            SearchControls cons)
throws NamingException {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(), filterExpr, args,
                                     cons);
}
 
Example #28
Source File: ContinuationDirContext.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(Name name,
                            String filter,
                            SearchControls cons)
throws NamingException {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), filter, cons);
}
 
Example #29
Source File: ContinuationDirContext.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(Name name,
                            String filter,
                            SearchControls cons)
throws NamingException {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), filter, cons);
}
 
Example #30
Source File: ContextEnumerator.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public Binding next() throws NamingException {
    if (!rootProcessed) {
        rootProcessed = true;
        return new Binding("", root.getClass().getName(),
                           root, true);
    }

    if (scope != SearchControls.OBJECT_SCOPE && hasMoreDescendants()) {
        return getNextDescendant();
    }

    throw new NoSuchElementException();
}