下面列出了怎么用javax.naming.directory.SearchResult的API类实例代码及写法,或者点击链接到github查看源代码。
private NamingEnumeration<SearchResult> mockSearchResults(String password)
throws NamingException {
@SuppressWarnings("unchecked")
NamingEnumeration<SearchResult> searchResults =
EasyMock.createNiceMock(NamingEnumeration.class);
EasyMock.expect(Boolean.valueOf(searchResults.hasMore()))
.andReturn(Boolean.TRUE)
.andReturn(Boolean.FALSE)
.andReturn(Boolean.TRUE)
.andReturn(Boolean.FALSE);
EasyMock.expect(searchResults.next())
.andReturn(new SearchResult("ANY RESULT", "",
new BasicAttributes(USER_PASSWORD_ATTR, password)))
.times(2);
EasyMock.replay(searchResults);
return searchResults;
}
@Instrumentation.TraceEntry(message = "get ldap user DN for username: {{1}}", timer = "ldap")
private static @Nullable String getUserDn(LdapContext ldapContext, String username,
LdapConfig ldapConfig) throws NamingException {
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<?> namingEnum = ldapContext.search(ldapConfig.userBaseDn(),
ldapConfig.userSearchFilter(), new String[] {username}, searchCtls);
try {
if (!namingEnum.hasMore()) {
return null;
}
SearchResult result = (SearchResult) checkNotNull(namingEnum.next());
String userDn = result.getNameInNamespace();
if (namingEnum.hasMore()) {
throw new IllegalStateException("More than matching user: " + username);
}
return userDn;
} finally {
namingEnum.close();
}
}
@Override
public void process(SearchResult result) throws NamingException, ParseException
{
try
{
doProcess(result);
}
finally
{
Object obj = result.getObject();
if (obj != null && obj instanceof Context)
{
try
{
((Context)obj).close();
}
catch (NamingException e)
{
logger.debug("error when closing result block context", e);
}
obj = null;
}
result = null;
}
}
@SuppressWarnings("unchecked")
@Before
public void setup() throws Exception {
bean = spy(new LdapAccessServiceBean());
dcMock = mock(DirContext.class);
neMock = mock(NamingEnumeration.class);
srMock = mock(SearchResult.class);
aMock = mock(Attributes.class);
doReturn(new Integer(5)).when(bean).getSearchLimit();
doReturn(dcMock).when(bean).getDirContext(any(Properties.class));
when(dcMock.search(anyString(), anyString(), any(SearchControls.class)))
.thenReturn(neMock);
when(Boolean.valueOf(neMock.hasMore())).thenReturn(Boolean.TRUE,
Boolean.FALSE);
when(neMock.next()).thenReturn(srMock);
when(srMock.getAttributes()).thenReturn(aMock);
}
@Test
public void testSearch_String_SearchControls_ContextMapper_DirContextProcessor() throws Exception {
expectGetReadOnlyContext();
SearchControls controls = searchControlsRecursive();
Object expectedObject = new Object();
SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes());
singleSearchResultWithStringBase(controls, searchResult);
Object expectedResult = expectedObject;
when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult);
List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock,
dirContextProcessorMock);
verify(dirContextProcessorMock).preProcess(dirContextMock);
verify(dirContextProcessorMock).postProcess(dirContextMock);
verify(namingEnumerationMock).close();
verify(dirContextMock).close();
assertThat(list).isNotNull();
assertThat(list).hasSize(1);
assertThat(list.get(0)).isSameAs(expectedResult);
}
@Test
public void testSearch_CallbackHandler_DirContextProcessor() throws Exception {
expectGetReadOnlyContext();
SearchControls controls = searchControlsRecursive();
controls.setReturningObjFlag(false);
SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes());
singleSearchResult(controls, searchResult);
tested.search(nameMock, "(ou=somevalue)", controls, handlerMock, dirContextProcessorMock);
verify(dirContextProcessorMock).preProcess(dirContextMock);
verify(dirContextProcessorMock).postProcess(dirContextMock);
verify(namingEnumerationMock).close();
verify(handlerMock).handleNameClassPair(searchResult);
verify(dirContextMock).close();
}
/**
* @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;
}
@Test
public void verifyThatFindOneThrowsIncorrectResultSizeDataAccessExceptionWhenMoreResults() throws Exception {
Class<Object> expectedClass = Object.class;
when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock);
when(odmMock.filterFor(expectedClass,
new EqualsFilter("ou", "somevalue"))).thenReturn(new EqualsFilter("ou", "somevalue"));
DirContextAdapter expectedObject = new DirContextAdapter();
SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes());
setupSearchResults(searchControlsRecursive(), new SearchResult[]{searchResult, searchResult});
Object expectedResult = expectedObject;
when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult, expectedResult);
try {
tested.findOne(query().where("ou").is("somevalue"), expectedClass);
fail("EmptyResultDataAccessException expected");
} catch (IncorrectResultSizeDataAccessException expected) {
assertThat(true).isTrue();
}
verify(namingEnumerationMock).close();
verify(dirContextMock).close();
}
/**
* Retrieves a list of all groups the user is a member of.
* @param dirContext a DirContext
* @param ldapUser the LdapUser to retrieve group membership for
* @return A list of Strings representing the fully qualified DN of each group
* @throws NamingException if an exception is thrown
* @since 1.4.0
*/
public List<String> getGroups(final DirContext dirContext, final LdapUser ldapUser) throws NamingException {
LOGGER.debug("Retrieving groups for: " + ldapUser.getDN());
final List<String> groupDns = new ArrayList<>();
final String searchFilter = variableSubstitution(USER_GROUPS_FILTER, ldapUser);
final SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
final NamingEnumeration<SearchResult> ne = dirContext.search(BASE_DN, searchFilter, sc);
while (hasMoreEnum(ne)) {
final SearchResult result = ne.next();
groupDns.add(result.getNameInNamespace());
LOGGER.debug("Found group: " + result.getNameInNamespace() + " for user: " + ldapUser.getDN());
}
closeQuietly(ne);
return groupDns;
}
@Test
public void testSearch_String_AttributesMapper() throws Exception {
expectGetReadOnlyContext();
SearchControls controls = searchControlsOneLevel();
controls.setReturningObjFlag(false);
BasicAttributes expectedAttributes = new BasicAttributes();
SearchResult searchResult = new SearchResult("", null, expectedAttributes);
singleSearchResultWithStringBase(controls, searchResult);
Object expectedResult = new Object();
when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult);
List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, attributesMapperMock);
verify(namingEnumerationMock).close();
verify(dirContextMock).close();
assertThat(list).isNotNull();
assertThat(list).hasSize(1);
assertThat(list.get(0)).isSameAs(expectedResult);
}
@Test
public void testSearch_String_AttributesMapper_Default() throws Exception {
expectGetReadOnlyContext();
SearchControls controls = searchControlsRecursive();
controls.setReturningObjFlag(false);
BasicAttributes expectedAttributes = new BasicAttributes();
SearchResult searchResult = new SearchResult("", null, expectedAttributes);
singleSearchResultWithStringBase(controls, searchResult);
Object expectedResult = new Object();
when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult);
List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", attributesMapperMock);
verify(namingEnumerationMock).close();
verify(dirContextMock).close();
assertThat(list).isNotNull();
assertThat(list).hasSize(1);
assertThat(list.get(0)).isSameAs(expectedResult);
}
@Test
public void retrieveName_notRelative() {
// given
SearchResult searchResult = new SearchResult(null, null, null, false);
searchResult.setNameInNamespace("cn=ldap01");
searchResult
.setName("ldap://estdevmail1.dev.est.fujitsu.com:389/cn=ldap01");
ldapProps.put(Context.PROVIDER_URL, "");
// when
String name = realmImpl.retrieveName(ldapProps, searchResult);
// then
assertEquals("cn=ldap01", name);
assertEquals("ldap://estdevmail1.dev.est.fujitsu.com:389",
ldapProps.getProperty(Context.PROVIDER_URL));
}
@Test
public void testSearch_String_SearchControls_ContextMapper_ReturningObjFlagNotSet() throws Exception {
expectGetReadOnlyContext();
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
SearchControls expectedControls = new SearchControls();
expectedControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
expectedControls.setReturningObjFlag(true);
Object expectedObject = new Object();
SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes());
singleSearchResultWithStringBase(expectedControls, searchResult);
Object expectedResult = expectedObject;
when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult);
List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock);
verify(namingEnumerationMock).close();
verify(dirContextMock).close();
assertThat(list).isNotNull();
assertThat(list).hasSize(1);
assertThat(list.get(0)).isSameAs(expectedResult);
}
private String getGroupName(SearchResult resultedGroup) throws NamingException {
Attribute attribute = resultedGroup.getAttributes()
.get(realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE));
if (attribute == null) {
return resultedGroup.getName();
} else {
String groupNameAttributeValue = (String) attribute.get();
return realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE) +
"=" + groupNameAttributeValue;
}
}
private LdapUser getUserForDn(String userdn, LdapContext context, Long domainId) throws NamingException {
final SearchControls controls = new SearchControls();
controls.setSearchScope(_ldapConfiguration.getScope());
controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes(domainId));
NamingEnumeration<SearchResult> result = context.search(userdn, "(objectClass=" + _ldapConfiguration.getUserObject(domainId) + ")", controls);
if (result.hasMoreElements()) {
return createUser(result.nextElement(), domainId);
} else {
throw new NamingException("No user found for dn " + userdn);
}
}
/**
* Finds a distinguished name(DN) of a user by querying the active directory LDAP context for the
* specified username.
*
* @return the DN of the user, or {@code null} if there's no such user
*/
@Nullable
protected String findUserDn(LdapContextFactory ldapContextFactory, String username) throws NamingException {
LdapContext ctx = null;
try {
// Binds using the system username and password.
ctx = ldapContextFactory.getSystemLdapContext();
final SearchControls ctrl = new SearchControls();
ctrl.setCountLimit(1);
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctrl.setTimeLimit(searchTimeoutMillis);
final String filter =
searchFilter != null ? USERNAME_PLACEHOLDER.matcher(searchFilter)
.replaceAll(username)
: username;
final NamingEnumeration<SearchResult> result = ctx.search(searchBase, filter, ctrl);
try {
if (!result.hasMore()) {
return null;
}
return result.next().getNameInNamespace();
} finally {
result.close();
}
} finally {
LdapUtils.closeContext(ctx);
}
}
List<String> doGetGroups(String user) throws NamingException {
List<String> groups = new ArrayList<String>();
DirContext ctx = getDirContext();
// Search for the user. We'll only ever need to look at the first result
NamingEnumeration<SearchResult> results = ctx.search(baseDN,
userSearchFilter,
new Object[]{user},
SEARCH_CONTROLS);
if (results.hasMoreElements()) {
SearchResult result = results.nextElement();
String userDn = result.getNameInNamespace();
NamingEnumeration<SearchResult> groupResults =
ctx.search(baseDN,
"(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))",
new Object[]{userDn},
SEARCH_CONTROLS);
while (groupResults.hasMoreElements()) {
SearchResult groupResult = groupResults.nextElement();
Attribute groupName = groupResult.getAttributes().get(groupNameAttr);
groups.add(groupName.get().toString());
}
}
return groups;
}
public void testOSXICalSearch() throws NamingException {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
searchControls.setReturningAttributes(new String[]{"uid", "mail", "sn", "cn", "description", "apple-generateduid", "givenname", "apple-serviceslocator", "uidnumber"});
NamingEnumeration<SearchResult> searchResults = ldapContext.search("cn=users, o=od",
"(&(objectclass=inetOrgPerson)(objectclass=extensibleObject)(objectclass=apple-user)(|(|(uid=fair*)(cn=fair*))(givenname=fair*)(sn=fair*)(cn=fair*)(mail=fair*))(objectclass=posixAccount)(objectclass=shadowAccount))", searchControls);
searchResults.close();
}
@Override
public boolean authenticate(String username, String password) {
String queryFilter = "("+filterAttribute+"="+username+")";
_logger.info(" filter : " + queryFilter);
String dn="";
SearchControls constraints = new SearchControls();
constraints.setSearchScope(ldapUtils.getSearchScope());
try {
NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
.search(ldapUtils.getBaseDN(), queryFilter, constraints);
if (results == null || !results.hasMore()) {
_logger.error("Ldap user "+username +" not found . ");
return false;
}else{
while (results != null && results.hasMore()) {
SearchResult sr = (SearchResult) results.next();
//String rdn = sr.getName();
dn = sr.getNameInNamespace();
_logger.debug("Directory user dn is "+dn+" .");
}
}
} catch (NamingException e) {
_logger.error("query throw NamingException:" + e.getMessage());
} finally {
ldapUtils.close();
}
LdapUtils ldapPassWordValid=new LdapUtils(ldapUtils.getProviderUrl(),dn,password);
ldapPassWordValid.openConnection();
if(ldapPassWordValid.getCtx()!=null){
_logger.debug("Directory user " + username + " is validate .");
ldapPassWordValid.close();
return true;
}
return false;
}
private boolean isPagedResultControlSupported(final LdapContext ctx) {
try {
final SearchControls ctl = new SearchControls();
ctl.setReturningAttributes(new String[] { "supportedControl" });
ctl.setSearchScope(SearchControls.OBJECT_SCOPE);
/* search for the rootDSE object */
final NamingEnumeration<SearchResult> results = ctx.search("", "(objectClass=*)", ctl);
while (results.hasMore()) {
final SearchResult entry = results.next();
final NamingEnumeration<? extends Attribute> attrs = entry.getAttributes().getAll();
while (attrs.hasMore()) {
final Attribute attr = attrs.next();
final NamingEnumeration<?> vals = attr.getAll();
while (vals.hasMore()) {
final String value = (String) vals.next();
if (value.equals(PAGED_RESULT_CONTROL_OID)) {
return true;
}
}
}
}
return false;
} catch (final Exception e) {
log.error("Exception when trying to know if the server support paged results.", e);
return false;
}
}
public NamingEnumeration<SearchResult> search(String name,
Attributes matchingAttributes)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().search(res.getString(),
matchingAttributes);
}
public NamingEnumeration<SearchResult> search(String name,
Attributes matchingAttributes)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().search(res.getString(),
matchingAttributes);
}
@Override
public boolean update(Groups group) throws Exception{
logger.info("update");
try {
SearchControls constraints = new SearchControls();
constraints.setSearchScope(ldapUtils.getSearchScope());
NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
.search(ldapUtils.getBaseDN(), "(cn="+group.getName()+")", constraints);
String oldDn="";
String rdn="";
if (results == null || !results.hasMore()) {
return create(group);
}else{
SearchResult sr = (SearchResult) results.next();
oldDn =sr.getNameInNamespace();
String[] dnSplit=oldDn.split(",");
rdn=oldDn.substring(oldDn.indexOf(","), oldDn.length());
String groupName=dnSplit[0].split("=")[1];
if(group.getName()!=groupName){
String newDn="cn="+group.getName()+","+rdn;
ldapUtils.getCtx().rename(oldDn, newDn);
ModificationItem[] modificationItems = new ModificationItem[1];
modificationItems[0]=new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute("cn",groupName));
ldapUtils.getCtx().modifyAttributes(newDn, modificationItems);
}
}
ldapUtils.close();
} catch (NamingException e) {
e.printStackTrace();
}
return true;
}
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 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);
}
/**
* Verifies that org.jivesoftware.openfire.ldap.LdapManager#getRelativeDNFromResult(javax.naming.directory.SearchResult)
* can handle a result that contains a quoted RDN values.
*
* Openldap has been observed returning the type of quoted values that are tested here.
*/
@Test
public void testGetRelativeDNFromResultQuoted() throws Exception
{
// Setup test fixture.
final SearchResult input = new SearchResult( "\"cn=ship crew/cooks\"", null, new BasicAttributes(), true );
// Execute system under test.
final Rdn[] result = LdapManager.getRelativeDNFromResult( input );
// Verify result.
assertEquals( 1, result.length );
assertEquals( "cn", result[0].getType() );
assertEquals( "ship crew/cooks", result[0].getValue() );
}
public void testMozillaSearchAttributes() throws NamingException {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
searchControls.setReturningAttributes(new String[]{"custom1", "mozillausehtmlmail", "postalcode", "custom2", "custom3", "custom4", "street", "surname", "telephonenumber", "mozillahomelocalityname", "orgunit", "mozillaworkstreet2", "xmozillanickname", "mozillahomestreet", "description", "cellphone", "homeurl", "mozillahomepostalcode", "departmentnumber", "postofficebox", "st", "objectclass", "sn", "ou", "fax", "mozillahomeurl", "mozillahomecountryname", "streetaddress", "cn", "company", "mozillaworkurl", "mobile", "region", "birthmonth", "birthday", "labeleduri", "carphone", "department", "xmozillausehtmlmail", "givenname", "nsaimid", "workurl", "facsimiletelephonenumber", "mozillanickname", "title", "nscpaimscreenname", "xmozillasecondemail", "mozillacustom3", "countryname", "mozillacustom4", "mozillacustom1", "mozillacustom2", "homephone", "mozillasecondemail", "pager", "zip", "mail", "c", "mozillahomestate", "o", "l", "birthyear", "modifytimestamp", "locality", "commonname", "notes", "pagerphone", "mozillahomestreet2"});
NamingEnumeration<SearchResult> searchResults = ldapContext.search("ou=people", "(objectclass=*)", searchControls);
searchResults.close();
}
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);
}
@Override
public List<LdapUser> getUsersInGroup(final String groupName, final LdapContext context) throws NamingException {
final String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
final SearchControls controls = new SearchControls();
controls.setSearchScope(_ldapConfiguration.getScope());
controls.setReturningAttributes(new String[]{attributeName});
final NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(), generateGroupSearchFilter(groupName), controls);
final List<LdapUser> users = new ArrayList<>();
//Expecting only one result which has all the users
if (result.hasMoreElements()) {
final Attribute attribute = result.nextElement().getAttributes().get(attributeName);
final NamingEnumeration<?> values = attribute.getAll();
while (values.hasMoreElements()) {
final String userdn = String.valueOf(values.nextElement());
try {
users.add(getUserForDn(userdn, context));
} catch (final NamingException e) {
s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
}
}
}
Collections.sort(users);
return users;
}
private void addRoleAttribute(SearchResult searchResult, List<String> roles) throws NamingException {
if (isRoleAttributeSet) {
Attribute roleAttribute = searchResult.getAttributes().get(roleAttributeName);
if (roleAttribute != null) {
roles.add((String) roleAttribute.get());
}
} else {
roles.add(searchResult.getNameInNamespace());
}
}