Java Code Examples for javax.naming.directory.SearchControls

The following examples show how to use javax.naming.directory.SearchControls. These examples are extracted from open source projects. 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 Project: dropwizard-auth-ldap   Source File: LdapAuthenticator.java    License: 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 2
Source Project: jdk8u-jdk   Source File: EventSupport.java    License: 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 Project: jdk8u_jdk   Source File: ContextEnumerator.java    License: 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 4
Source Project: spring-ldap   Source File: LdapTemplate.java    License: 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 5
Source Project: spring-ldap   Source File: LdapTemplateTest.java    License: 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 6
Source Project: MaxKey   Source File: Organization2Activedirectory.java    License: 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 7
Source Project: MaxKey   Source File: Organization2Ldap.java    License: 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 8
Source Project: openjdk-jdk8u   Source File: EventSupport.java    License: 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 9
Source Project: spring-ldap   Source File: LdapTemplate.java    License: 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 10
Source Project: spring-ldap   Source File: LdapTemplateTest.java    License: 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 11
Source Project: james-project   Source File: RetryingDirContext.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public NamingEnumeration<SearchResult> search(final String name, final String filterExpr,
        final Object[] filterArgs, final SearchControls cons) throws NamingException {
    return (NamingEnumeration<SearchResult>) new LoggingRetryHandler(
            DEFAULT_EXCEPTION_CLASSES, this, getSchedule(), getMaxRetries()) {

        @Override
        public Object operation() throws NamingException {
            return ((DirContext) getDelegate()).search(name, filterExpr, filterArgs, cons);
        }
    }.perform();
}
 
Example 12
Source Project: spring-ldap   Source File: LdapTemplateSearchResultITest.java    License: 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 13
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 14
Source Project: griffin   Source File: LoginServiceLdapImpl.java    License: Apache License 2.0 5 votes vote down vote up
public LoginServiceLdapImpl(String url, String email, String searchBase,
                            String searchPattern, boolean sslSkipVerify,
                            String bindDN, String bindPassword) {
    this.url = url;
    this.email = email;
    this.searchBase = searchBase;
    this.searchPattern = searchPattern;
    this.sslSkipVerify = sslSkipVerify;
    this.bindDN = bindDN;
    this.bindPassword = bindPassword;
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    this.searchControls = searchControls;
}
 
Example 15
Source Project: jdk8u_jdk   Source File: NotifierArgs.java    License: GNU General Public License v2.0 5 votes vote down vote up
NotifierArgs(String name, String filter, SearchControls ctls,
    NamingListener l) {
    this.name = name;
    this.filter = filter;
    this.controls = ctls;

    if (l instanceof NamespaceChangeListener) {
        mask |= ADDED_MASK|REMOVED_MASK|RENAMED_MASK;
    }
    if (l instanceof ObjectChangeListener) {
        mask |= CHANGED_MASK;
    }
}
 
Example 16
Source Project: openjdk-jdk8u   Source File: NotifierArgs.java    License: 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
public NamingEnumeration<SearchResult> search(Name name,
                            String filterExpr,
                            Object[] args,
                            SearchControls cons)
throws NamingException {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), filterExpr, args,
                                     cons);
}
 
Example 18
Source Project: micro-integrator   Source File: CarbonContextDataHolder.java    License: Apache License 2.0 5 votes vote down vote up
public void addNamingListener(String s, String filter, Object[] objects,
                              SearchControls searchControls, NamingListener namingListener)
        throws NamingException {
    MicroIntegratorBaseUtils.checkSecurity();
    getEventDirContext(s).addNamingListener(s, filter, objects, searchControls,
                                            namingListener);
}
 
Example 19
Source Project: openjdk-8   Source File: ContextEnumerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void prepNextChild() throws NamingException {
    if(hasMoreChildren()) {
        try {
            currentChild = getNextChild();
            currentReturned = false;
        } catch (NamingException e){
            if (debug) System.out.println(e);
            if (debug) e.printStackTrace();
        }
    } else {
        currentChild = null;
        return;
    }

    if(scope == SearchControls.SUBTREE_SCOPE &&
       currentChild.getObject() instanceof Context) {
        currentChildEnum = newEnumerator(
                                      (Context)(currentChild.getObject()),
                                      scope, currentChild.getName(),
                                      false);
        currentChildExpanded = true;
        if(debug) {System.out.println("prepNextChild: expanded");}
    } else {
        currentChildExpanded = false;
        currentChildEnum = null;
        if(debug) {System.out.println("prepNextChild: normal");}
    }
}
 
Example 20
Source Project: Java8CN   Source File: ContinuationDirContext.java    License: Apache License 2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(Name name,
                            String filterExpr,
                            Object[] args,
                            SearchControls cons)
throws NamingException {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), filterExpr, args,
                                     cons);
}
 
Example 21
Source Project: keycloak   Source File: LDAPIdentityStore.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Set<LDAPCapabilityRepresentation> queryServerCapabilities() {
    Set<LDAPCapabilityRepresentation> result = new LinkedHashSet<>();
    try {
        List<String> attrs = new ArrayList<>();
        attrs.add("supportedControl");
        attrs.add("supportedExtension");
        attrs.add("supportedFeatures");
        List<SearchResult> searchResults = operationManager
            .search("", "(objectClass=*)", Collections.unmodifiableCollection(attrs), SearchControls.OBJECT_SCOPE);
        if (searchResults.size() != 1) {
            throw new ModelException("Could not query root DSE: unexpected result size");
        }
        SearchResult rootDse = searchResults.get(0);
        Attributes attributes = rootDse.getAttributes();
        for (String attr: attrs) {
            Attribute attribute = attributes.get(attr);
            if (null != attribute) {
                CapabilityType capabilityType = CapabilityType.fromRootDseAttributeName(attr);
                NamingEnumeration<?> values = attribute.getAll();
                while (values.hasMoreElements()) {
                    Object o = values.nextElement();
                    LDAPCapabilityRepresentation capability = new LDAPCapabilityRepresentation(o, capabilityType);
                    logger.info("rootDSE query: " + capability);
                    result.add(capability);
                }
            }
        }
        return result;
    } catch (NamingException e) {
        throw new ModelException("Failed to query root DSE: " + e.getMessage(), e);
    }
}
 
Example 22
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 23
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 24
Source Project: jdk8u-jdk   Source File: NotifierArgs.java    License: 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 25
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 26
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 27
Source Project: MaxKey   Source File: ActiveDirectoryUtils.java    License: 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 28
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 29
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 30
public NamingEnumeration<SearchResult> search(Name name,
                            String filter,
                            SearchControls cons)
throws NamingException {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), filter, cons);
}