javax.naming.directory.SearchResult Java Examples

The following examples show how to use javax.naming.directory.SearchResult. 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: TestJNDIRealm.java    From Tomcat8-Source-Read with MIT License 7 votes vote down vote up
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;
}
 
Example #2
Source File: LdapConnectionWrapper.java    From Alpine with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #4
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 #5
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #6
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: ADMRealmImplTest.java    From development with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #8
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: LdapAccessServiceBeanTest.java    From development with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: LDAPUserRegistry.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
    }
}
 
Example #11
Source File: LdapAuthentication.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example #12
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #13
Source File: ContinuationDirContext.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            Attributes matchingAttributes)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(),
                                     matchingAttributes);
}
 
Example #14
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(String name,
                            String filterExpr,
                            Object[] args,
                            SearchControls cons)
throws NamingException {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(), filterExpr, args,
                                     cons);
}
 
Example #15
Source File: ContinuationDirContext.java    From openjdk-jdk9 with GNU General Public License v2.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 #16
Source File: ContinuationDirContext.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(Name name,
                            Attributes matchingAttributes,
                            String[] attributesToReturn)
throws NamingException  {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), matchingAttributes,
                                     attributesToReturn);
}
 
Example #17
Source File: LDAPTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * 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() );
}
 
Example #18
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 #19
Source File: OpenLdapUserManagerImpl.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #20
Source File: LDAPLoginModule.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
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());
   }
}
 
Example #21
Source File: ContinuationDirContext.java    From TencentKona-8 with GNU General Public License v2.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 #22
Source File: LdapAccessServiceBean.java    From development with Apache License 2.0 5 votes vote down vote up
private boolean hasMoreEnum(NamingEnumeration<SearchResult> namingEnum)
        throws NamingException {
    boolean hasMore = true;
    try {
        if (!namingEnum.hasMore()) {
            hasMore = false;
        }
    } catch (PartialResultException e) {
        hasMore = false;
        logger.logWarn(Log4jLogger.SYSTEM_LOG, e,
                LogMessageIdentifier.WARN_LDAP_PARTIAL_EXCEPTION);
    }
    return hasMore;
}
 
Example #23
Source File: TestLdap.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
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();
}
 
Example #24
Source File: ContinuationDirContext.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            Attributes matchingAttributes)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(),
                                     matchingAttributes);
}
 
Example #25
Source File: ADLdapUserManagerImpl.java    From cosmic with Apache License 2.0 5 votes vote down vote up
protected boolean isUserDisabled(final SearchResult result) throws NamingException {
    boolean isDisabledUser = false;
    final String userAccountControl = LdapUtils.getAttributeValue(result.getAttributes(), _ldapConfiguration.getUserAccountControlAttribute());
    if (userAccountControl != null) {
        final int control = Integer.parseInt(userAccountControl);
        // second bit represents disabled user flag in AD
        if ((control & 2) > 0) {
            isDisabledUser = true;
        }
    }
    return isDisabledUser;
}
 
Example #26
Source File: Group2Ldap.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #27
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(Name name,
                            String filterExpr,
                            Object[] args,
                            SearchControls cons)
throws NamingException {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), filterExpr, args,
                                     cons);
}
 
Example #28
Source File: JDKUtil.java    From learnjavabug with MIT License 5 votes vote down vote up
@SuppressWarnings ( "unchecked" )
public static Enumeration<?> makeLazySearchEnumeration ( String codebase, String clazz ) throws Exception {
    DirContext ctx = makeContinuationContext(codebase, clazz);
    NamingEnumeration<?> inner = Reflections.createWithoutConstructor(LazySearchEnumerationImpl.class);
    Reflections.setFieldValue(inner, "nextMatch", new SearchResult("foo", ctx, null));
    return new LazySearchEnumerationImpl((NamingEnumeration<Binding>) inner, null, null);
}
 
Example #29
Source File: ContinuationDirContext.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            Attributes matchingAttributes)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(),
                                     matchingAttributes);
}
 
Example #30
Source File: Group2Activedirectory.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@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;
}