下面列出了怎么用javax.naming.directory.SearchControls的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
}
/**
* 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);
}
}
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();
}
/**
* {@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);
}
@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();
}
@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);
}
@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);
}
/**
* 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);
}
}
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;
}
@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();
}
@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();
}
@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);
}
public NamingEnumeration<SearchResult> search(Name name,
String filter,
SearchControls cons)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), filter, cons);
}
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;
}
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;
}
}
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);
}
}
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);
}
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);
}
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");}
}
}
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);
}
@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);
}
}
public NamingEnumeration<SearchResult> search(Name name,
String filter,
SearchControls cons)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), filter, cons);
}
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;
}
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());
}
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();
}
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();
}
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();
}
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);
}
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);
}
public NamingEnumeration<SearchResult> search(Name name,
String filter,
SearchControls cons)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), filter, cons);
}