类javax.naming.directory.DirContext源码实例Demo

下面列出了怎么用javax.naming.directory.DirContext的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: jdk8u_jdk   文件: ldapURLContextFactory.java
static ResolveResult getUsingURLIgnoreRootDN(String url, Hashtable<?,?> env)
        throws NamingException {
    LdapURL ldapUrl = new LdapURL(url);
    DirContext ctx = new LdapCtx("", ldapUrl.getHost(), ldapUrl.getPort(),
        env, ldapUrl.useSsl());
    String dn = (ldapUrl.getDN() != null ? ldapUrl.getDN() : "");

    // Represent DN as empty or single-component composite name.
    CompositeName remaining = new CompositeName();
    if (!"".equals(dn)) {
        // if nonempty, add component
        remaining.add(dn);
    }

    return new ResolveResult(ctx, remaining);
}
 
源代码2 项目: spring-ldap   文件: DirContextAdapterTest.java
@Test
public void testChangeMultiAttribute_RemoveValue() throws Exception {
	final Attributes fixtureAttrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("abc");
	multi.add("123");
	multi.add("qwe");
	fixtureAttrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(fixtureAttrs, null);
			setUpdateMode(true);
		}
	}
	tested = new TestableDirContextAdapter();
	assertThat(tested.isUpdateMode()).isTrue();
	tested.setAttributeValues("abc", new String[] { "123" });

	ModificationItem[] modificationItems = tested.getModificationItems();
	assertThat(modificationItems.length).isEqualTo(1);
    assertThat(modificationItems[0].getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
	assertThat(modificationItems[0].getAttribute().get()).isEqualTo("qwe");
}
 
源代码3 项目: olat   文件: SecureWebdavServlet.java
/**
 * MOVE Method.
 */
protected void doMove(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    if (readOnly) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    // Check if operation allowed by OLAT VFS security callback
    DirContext resources = getResources(req);
    VFSDirContext vfsContext = (VFSDirContext) resources;
    String path = getRelativePath(req);
    if (!vfsContext.canRename(path)) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(req)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return;
    }

    if (copyResource(req, resp)) {
        deleteResource(path, req, resp);
    }
}
 
源代码4 项目: tomcatsrc   文件: JNDIRealm.java
/**
 * Check whether the credentials presented by the user match those
 * retrieved from the directory.
 *
 * @param context The directory context
 * @param info The User to be authenticated
 * @param credentials Authentication credentials
 *
 * @exception NamingException if a directory server error occurs
 */
protected boolean compareCredentials(DirContext context,
                                     User info,
                                     String credentials)
    throws NamingException {

    // Validate the credentials specified by the user
    if (containerLog.isTraceEnabled())
        containerLog.trace("  validating credentials");

    if (info == null || credentials == null)
        return (false);

    String password = info.getPassword();

    return compareCredentials(credentials, password);
}
 
源代码5 项目: micro-integrator   文件: LDAPUtil.java
/**
 * @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;
}
 
源代码6 项目: spring-ldap   文件: LdapTemplate.java
/**
    * {@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);
}
 
源代码7 项目: iaf   文件: LdapSender.java
private String performOperationChallenge(String principal, IPipeLineSession session, Map paramValueMap) throws SenderException, ParameterException {
	DirContext dirContext = null;
	try{
		// Use loopkupDirContext instead of getDirContext to prevent
		// NamingException (with error code 49) being converted to
		// SenderException.
		dirContext = loopkupDirContext(paramValueMap);
		attributesToXml(dirContext.getAttributes(principal, getAttributesReturnedParameter())).toXML();
		return DEFAULT_RESULT_CHALLENGE_OK;
	} catch(NamingException e) {
		// https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
		//   49 LDAP_INVALID_CREDENTIALS Indicates that during a bind operation one of the following occurred: The client passed either an incorrect DN or password, or the password is incorrect because it has expired, intruder detection has locked the account, or another similar reason. This is equivalent to AD error code 52e.
		if(e.getMessage().startsWith("[LDAP: error code 49 - ") ) {
			if (log.isDebugEnabled()) log.debug("Operation [" + getOperation()+ "] invalid credentials for: " + principal);
			return DEFAULT_RESULT_CHALLENGE_NOK;	
		} else {
			storeLdapException(e, session);
			throw new SenderException("Exception in operation [" + getOperation()+ "] principal=["+principal+"]", e);	
		}
	} finally {
		closeDirContext(dirContext);
	}
}
 
源代码8 项目: spring-ldap   文件: LdapTemplate.java
/**
    * {@inheritDoc}
    */
   @Override
public void search(final Name base, final String filter, final SearchControls controls,
		NameClassPairCallbackHandler handler, DirContextProcessor processor) {

	// 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, processor);
}
 
源代码9 项目: projectforge-webapp   文件: LdapDao.java
public List<T> findAll(final DirContext ctx, final String organizationalUnit) throws NamingException
{
  final LinkedList<T> list = new LinkedList<T>();
  NamingEnumeration< ? > results = null;
  final SearchControls controls = new SearchControls();
  controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  final String searchBase = getSearchBase(organizationalUnit);
  results = ctx.search(searchBase, "(objectclass=" + getObjectClass() + ")", controls);
  while (results.hasMore()) {
    final SearchResult searchResult = (SearchResult) results.next();
    final String dn = searchResult.getName();
    final Attributes attributes = searchResult.getAttributes();
    list.add(mapToObject(dn, searchBase, attributes));
  }
  return list;
}
 
源代码10 项目: JDKSourceCode1.8   文件: DirectoryManager.java
/**
  * Creates a context in which to continue a <tt>DirContext</tt> operation.
  * Operates just like <tt>NamingManager.getContinuationContext()</tt>,
  * only the continuation context returned is a <tt>DirContext</tt>.
  *
  * @param cpe
  *         The non-null exception that triggered this continuation.
  * @return A non-null <tt>DirContext</tt> object for continuing the operation.
  * @exception NamingException If a naming exception occurred.
  *
  * @see NamingManager#getContinuationContext(CannotProceedException)
  */
@SuppressWarnings("unchecked")
public static DirContext getContinuationDirContext(
        CannotProceedException cpe) throws NamingException {

    Hashtable<Object,Object> env = (Hashtable<Object,Object>)cpe.getEnvironment();
    if (env == null) {
        env = new Hashtable<>(7);
    } else {
        // Make a (shallow) copy of the environment.
        env = (Hashtable<Object,Object>) env.clone();
    }
    env.put(CPE, cpe);

    return (new ContinuationDirContext(cpe, env));
}
 
源代码11 项目: spring-ldap   文件: DirContextAdapterTest.java
@Test
public void testRemoveMultiAttribute() throws Exception {
	final Attributes fixtureAttrs = new BasicAttributes();
	Attribute abc = new BasicAttribute("abc");
	abc.add("123");
	abc.add("456");
	fixtureAttrs.put(abc);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(fixtureAttrs, null);
			setUpdateMode(true);
		}
	}
	tested = new TestableDirContextAdapter();

	tested.setUpdateMode(true);
	tested.setAttributeValues("abc", new String[] {});

	ModificationItem[] mods = tested.getModificationItems();
	assertThat(mods.length).isEqualTo(1);
	assertThat(mods[0].getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
	Attribute attr = mods[0].getAttribute();
	assertThat((String) attr.getID()).isEqualTo("abc");
	assertThat(attr.size()).isEqualTo(0);
}
 
源代码12 项目: jdk8u-jdk   文件: ldapURLContextFactory.java
static ResolveResult getUsingURLIgnoreRootDN(String url, Hashtable<?,?> env)
        throws NamingException {
    LdapURL ldapUrl = new LdapURL(url);
    DirContext ctx = new LdapCtx("", ldapUrl.getHost(), ldapUrl.getPort(),
        env, ldapUrl.useSsl());
    String dn = (ldapUrl.getDN() != null ? ldapUrl.getDN() : "");

    // Represent DN as empty or single-component composite name.
    CompositeName remaining = new CompositeName();
    if (!"".equals(dn)) {
        // if nonempty, add component
        remaining.add(dn);
    }

    return new ResolveResult(ctx, remaining);
}
 
private List<String> discoverNodes(String serviceName) throws NamingException {
	List<String> locations = new ArrayList<>();

	Hashtable<String, String> env = new Hashtable<String, String>();
	env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
	env.put("java.naming.provider.url", "dns:");

	DirContext context = new InitialDirContext(env);
	Attributes attributes = context.getAttributes(serviceName, new String[] { "SRV" });
	for (NamingEnumeration<? extends Attribute> records = attributes.getAll(); records.hasMore();) {
		Attribute record = records.next();
		NamingEnumeration<String> values = (NamingEnumeration<String>) record.getAll();
		while (values.hasMore()) {
			String dns = values.next();
			String[] split = dns.split(" ");
			String host = split[3];
			if (host.endsWith(".")) {
				host = host.substring(0, host.length() - 1);
			}

			String location = "http://" + host + ":2379";
			locations.add(location);
		}
	}
	return locations;
}
 
源代码14 项目: iaf   文件: LdapSender.java
private String performOperationRead(String entryName, IPipeLineSession session, Map paramValueMap) throws SenderException, ParameterException {
	DirContext dirContext = null;
	try{
		dirContext = getDirContext(paramValueMap);
		return attributesToXml(dirContext.getAttributes(entryName, getAttributesReturnedParameter())).toXML();
	} catch(NamingException e) {
		// https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
		//   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
		// Sun:
		//   [LDAP: error code 32 - No Such Object...
		if(e.getMessage().startsWith("[LDAP: error code 32 - ") ) {
			if (log.isDebugEnabled()) log.debug("Operation [" + getOperation()+ "] found nothing - no such entryName: " + entryName);
			return DEFAULT_RESULT_READ;	
		} else {
			storeLdapException(e, session);
			throw new SenderException("Exception in operation [" + getOperation()+ "] entryName=["+entryName+"]", e);	
		}
	} finally {
		closeDirContext(dirContext);
	}
}
 
源代码15 项目: ripple-lib-java   文件: X509LDAPCertStoreSpi.java
private DirContext connectLDAP() throws NamingException
{
    Properties props = new Properties();
    props.setProperty(Context.INITIAL_CONTEXT_FACTORY, LDAP_PROVIDER);
    props.setProperty(Context.BATCHSIZE, "0");

    props.setProperty(Context.PROVIDER_URL, params.getLdapURL());
    props.setProperty(Context.URL_PKG_PREFIXES, URL_CONTEXT_PREFIX);
    props.setProperty(Context.REFERRAL, REFERRALS_IGNORE);
    props.setProperty(Context.SECURITY_AUTHENTICATION,
        SEARCH_SECURITY_LEVEL);

    DirContext ctx = new InitialDirContext(props);
    return ctx;
}
 
protected CompensatingTransactionHolderSupport getNewHolder() {
    DirContext newCtx = getContextSource().getReadWriteContext();
    return new DirContextHolder(
            new DefaultCompensatingTransactionOperationManager(
                    new LdapCompensatingTransactionOperationFactory(
                            renamingStrategy)), newCtx);
}
 
源代码17 项目: Tomcat8-Source-Read   文件: JNDIRealm.java
/**
 * Check credentials by binding to the directory as the user
 *
 * @param context The directory context
 * @param user The User to be authenticated
 * @param credentials Authentication credentials
 * @return <code>true</code> if the credentials are validated
 * @exception NamingException if a directory server error occurs
 */
 protected boolean bindAsUser(DirContext context,
                              User user,
                              String credentials)
     throws NamingException {

     if (credentials == null || user == null)
         return false;

     String dn = user.getDN();
     if (dn == null)
         return false;

     // Validate the credentials specified by the user
     if (containerLog.isTraceEnabled()) {
         containerLog.trace("  validating credentials by binding as the user");
    }

    userCredentialsAdd(context, dn, credentials);

    // Elicit an LDAP bind operation
    boolean validated = false;
    try {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  binding as "  + dn);
        }
        context.getAttributes("", null);
        validated = true;
    }
    catch (AuthenticationException e) {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  bind attempt failed");
        }
    }

    userCredentialsRemove(context);

    return validated;
}
 
@Test
public void testMakeObjectReadOnly() throws Exception {
    final DirContextPooledObjectFactory objectFactory = new DirContextPooledObjectFactory();

    DirContext readOnlyContextMock = mock(DirContext.class);

    when(contextSourceMock.getReadOnlyContext()).thenReturn(readOnlyContextMock);
    objectFactory.setContextSource(contextSourceMock);

    final PooledObject createdDirContext = objectFactory.makeObject(DirContextType.READ_ONLY);
    InvocationHandler invocationHandler = Proxy.getInvocationHandler(createdDirContext.getObject());
    assertThat(readOnlyContextMock).isEqualTo(Whitebox.getInternalState(invocationHandler, "target"));
}
 
源代码19 项目: embedded-ldap-junit   文件: ContextProxyFactory.java
public static DirContext asDelegatingDirContext(final InitialDirContext initialDirContext) {
    try {
        final DirContext dirContext = DIR_CONTEXT_PROXY_TYPE.newInstance();
        ((DirContextProxy) dirContext).setDelegatedDirContext(initialDirContext);
        return dirContext;
    } catch (InstantiationException | IllegalAccessException e) {
        throw new IllegalStateException("Could not wrap DirContext", e);
    }
}
 
源代码20 项目: iaf   文件: LdapClient.java
public String searchObjectForSingleAttributeWithCache(String objectDN, String baseDn, String attribute) throws NamingException {
   	DirContext context=getContext();
   	try {
   		return searchObjectForSingleAttributeWithCache(context, objectDN, baseDn, attribute);
   	} finally {
   		context.close();
   	}
}
 
源代码21 项目: pentaho-kettle   文件: MailValidation.java
/**
 * verify if there is a mail server registered to the domain name. and return the email servers count
 */
public static int mailServersCount( String hostName ) throws NamingException {
  Hashtable<String, String> env = new Hashtable<String, String>();
  env.put( "java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory" );
  DirContext ictx = new InitialDirContext( env );
  Attributes attrs = ictx.getAttributes( hostName, new String[] { "MX" } );
  Attribute attr = attrs.get( "MX" );
  if ( attr == null ) {
    return ( 0 );
  }
  return ( attr.size() );
}
 
源代码22 项目: msf4j   文件: LDAPUserStoreManager.java
public void assignUser(String username, String groupName) throws NamingException {

        try {
            ModificationItem[] mods = new ModificationItem[1];
            Attribute mod = new BasicAttribute("member", getUserDN(username));
            mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, mod);
            context.modifyAttributes(getGroupDN(groupName), mods);
        } catch (AttributeInUseException e) {
            // If user is already added, ignore exception
        }
    }
 
@Test
public void testMakeObjectReadOnly() throws Exception {
    final DirContextPoolableObjectFactory objectFactory = new DirContextPoolableObjectFactory();

    DirContext readOnlyContextMock = mock(DirContext.class);

    when(contextSourceMock.getReadOnlyContext()).thenReturn(readOnlyContextMock);
    objectFactory.setContextSource(contextSourceMock);

    final Object createdDirContext = objectFactory.makeObject(DirContextType.READ_ONLY);
    InvocationHandler invocationHandler = Proxy.getInvocationHandler(createdDirContext);
    assertThat(readOnlyContextMock).isEqualTo(Whitebox.getInternalState(invocationHandler, "target"));
}
 
/**
 * Post processing the user list, when found membership group filter with claim filtering.
 *
 * @param expressionConditions
 * @param tempUserList
 * @return
 * @throws UserStoreException
 */
private List<String> getUserListFromClaimFiltering(List<ExpressionCondition> expressionConditions,
                                                   List<String> tempUserList) throws UserStoreException {

    List<String> claimSearchUserList = new ArrayList<>();
    List<ExpressionCondition> derivedConditionList = expressionConditions;
    Iterator<ExpressionCondition> iterator = derivedConditionList.iterator();

    while (iterator.hasNext()) {
        ExpressionCondition expressionCondition = iterator.next();
        if (ExpressionAttribute.ROLE.toString().equals(
                expressionCondition.getAttributeName())) {
            iterator.remove();
        }
    }

    LDAPSearchSpecification claimSearch = new LDAPSearchSpecification(realmConfig, derivedConditionList);
    SearchControls claimSearchControls = claimSearch.getSearchControls();
    DirContext claimSearchDirContext = this.connectionSource.getContext();
    NamingEnumeration<SearchResult> tempAnswer = null;

    try {
        tempAnswer = claimSearchDirContext.search(claimSearch.getSearchBases(),
                claimSearch.getSearchFilterQuery(), claimSearchControls);
        if (tempAnswer.hasMore()) {
            claimSearchUserList = getUserListFromNonGroupFilterResult(tempAnswer,
                    Arrays.asList(claimSearchControls.getReturningAttributes()));
        }
    } catch (NamingException e) {
        log.error(String.format("Error occurred while doing claim filtering for user(s) with filter: %s, %s",
                claimSearch.getSearchFilterQuery(), e.getMessage()));
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        JNDIUtil.closeContext(claimSearchDirContext);
        JNDIUtil.closeNamingEnumeration(tempAnswer);
    }
    tempUserList.retainAll(claimSearchUserList);
    return tempUserList;
}
 
源代码25 项目: spring-ldap   文件: LdapTemplate.java
/**
    * {@inheritDoc}
    */
   @Override
public void bind(final String dn, final Object obj, final Attributes attributes) {
	executeReadWrite(new ContextExecutor<Object>() {
		public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
			ctx.bind(dn, obj, attributes);
			return null;
		}
	});
}
 
源代码26 项目: olat   文件: LDAPLoginManagerImpl.java
/**
 * Find the user dn with its uid
 * 
 * @param uid
 * @param ctx
 * @return user's dn
 */
private String searchUserDN(final String uid, final DirContext ctx) {
    if (ctx == null) {
        return null;
    }

    final List<String> ldapBases = LDAPLoginModule.getLdapBases();
    final String objctClass = LDAPLoginModule.getLdapUserObjectClass();
    final String[] serachAttr = { "dn" };

    final String ldapUserIDAttribute = LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
    final String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))";
    final SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(serachAttr);

    String userDN = null;
    for (final String ldapBase : ldapBases) {
        try {
            final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls);
            while (enm.hasMore()) {
                final SearchResult result = enm.next();
                userDN = result.getNameInNamespace();
            }
            if (userDN != null) {
                break;
            }
        } catch (final NamingException e) {
            log.error("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e);
        }
    }

    return userDN;
}
 
源代码27 项目: tomcatsrc   文件: WebappClassLoaderBase.java
/**
 * Set associated resources.
 */
public void setResources(DirContext resources) {

    this.resources = resources;

    if (resources instanceof ProxyDirContext) {
        contextName = ((ProxyDirContext) resources).getContextName();
    }
}
 
源代码28 项目: james-project   文件: RetryingDirContext.java
@SuppressWarnings("unchecked")
@Override
public NamingEnumeration<SearchResult> search(final String name, final String filter,
        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, filter, cons);
        }
    }.perform();
}
 
源代码29 项目: spring-ldap   文件: DirContextAdapterTest.java
/**
 * Test case corresponding to LDAP-96 in Spring Jira.
 * https://jira.springframework.org/browse/LDAP-96
 */
   @Test
public void testChangeMultiAttributeOrderDoesMatterLDAP96()
		throws Exception {
	final Attributes fixtureAttrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("title");
	multi.add("Juergen");
	multi.add("George");
	fixtureAttrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(fixtureAttrs, null);
			setUpdateMode(true);
		}
	}
	tested = new TestableDirContextAdapter();
	assertThat(tested.isUpdateMode()).isTrue();
	tested.setAttributeValues("title", new String[] { "Jim", "George",
			"Juergen" }, true);

	// change
	ModificationItem[] mods = tested.getModificationItems();
	assertThat(mods.length).isEqualTo(1);
	assertThat(mods[0].getModificationOp()).isEqualTo(DirContext.REPLACE_ATTRIBUTE);
	Attribute attr = mods[0].getAttribute();
	assertThat(attr.get(0)).isEqualTo("Jim");
	assertThat(attr.get(1)).isEqualTo("George");
	assertThat(attr.get(2)).isEqualTo("Juergen");
}
 
源代码30 项目: hadoop   文件: TestLdapGroupsMapping.java
@Before
public void setupMocks() throws NamingException {
  mockContext = mock(DirContext.class);
  doReturn(mockContext).when(mappingSpy).getDirContext();
          
  SearchResult mockUserResult = mock(SearchResult.class);
  // We only ever call hasMoreElements once for the user NamingEnum, so 
  // we can just have one return value
  when(mockUserNamingEnum.hasMoreElements()).thenReturn(true);
  when(mockUserNamingEnum.nextElement()).thenReturn(mockUserResult);
  when(mockUserResult.getNameInNamespace()).thenReturn("CN=some_user,DC=test,DC=com");
  
  SearchResult mockGroupResult = mock(SearchResult.class);
  // We're going to have to define the loop here. We want two iterations,
  // to get both the groups
  when(mockGroupNamingEnum.hasMoreElements()).thenReturn(true, true, false);
  when(mockGroupNamingEnum.nextElement()).thenReturn(mockGroupResult);
  
  // Define the attribute for the name of the first group
  Attribute group1Attr = new BasicAttribute("cn");
  group1Attr.add(testGroups[0]);
  Attributes group1Attrs = new BasicAttributes();
  group1Attrs.put(group1Attr);
  
  // Define the attribute for the name of the second group
  Attribute group2Attr = new BasicAttribute("cn");
  group2Attr.add(testGroups[1]);
  Attributes group2Attrs = new BasicAttributes();
  group2Attrs.put(group2Attr);
  
  // This search result gets reused, so return group1, then group2
  when(mockGroupResult.getAttributes()).thenReturn(group1Attrs, group2Attrs);
}
 
 类所在包
 同包方法