Java Code Examples for javax.naming.directory.DirContext

The following examples show how to use javax.naming.directory.DirContext. 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
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);
}
 
Example 2
Source Project: spring-ldap   Source File: DirContextAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example 3
Source Project: olat   Source File: SecureWebdavServlet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 4
Source Project: tomcatsrc   Source File: JNDIRealm.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 5
Source Project: micro-integrator   Source File: LDAPUtil.java    License: 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 6
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 7
Source Project: iaf   Source File: LdapSender.java    License: Apache License 2.0 6 votes vote down vote up
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);
	}
}
 
Example 8
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, 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);
}
 
Example 9
Source Project: projectforge-webapp   Source File: LdapDao.java    License: GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example 10
Source Project: JDKSourceCode1.8   Source File: DirectoryManager.java    License: MIT License 6 votes vote down vote up
/**
  * 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));
}
 
Example 11
Source Project: spring-ldap   Source File: DirContextAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 12
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);
}
 
Example 13
Source Project: spring-boot-etcd   Source File: EtcdClientAutoConfiguration.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example 14
Source Project: iaf   Source File: LdapSender.java    License: Apache License 2.0 6 votes vote down vote up
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);
	}
}
 
Example 15
Source Project: ripple-lib-java   Source File: X509LDAPCertStoreSpi.java    License: ISC License 5 votes vote down vote up
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;
}
 
Example 16
protected CompensatingTransactionHolderSupport getNewHolder() {
    DirContext newCtx = getContextSource().getReadWriteContext();
    return new DirContextHolder(
            new DefaultCompensatingTransactionOperationManager(
                    new LdapCompensatingTransactionOperationFactory(
                            renamingStrategy)), newCtx);
}
 
Example 17
Source Project: Tomcat8-Source-Read   Source File: JNDIRealm.java    License: MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example 18
@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"));
}
 
Example 19
Source Project: embedded-ldap-junit   Source File: ContextProxyFactory.java    License: MIT License 5 votes vote down vote up
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);
    }
}
 
Example 20
Source Project: iaf   Source File: LdapClient.java    License: Apache License 2.0 5 votes vote down vote up
public String searchObjectForSingleAttributeWithCache(String objectDN, String baseDn, String attribute) throws NamingException {
   	DirContext context=getContext();
   	try {
   		return searchObjectForSingleAttributeWithCache(context, objectDN, baseDn, attribute);
   	} finally {
   		context.close();
   	}
}
 
Example 21
Source Project: pentaho-kettle   Source File: MailValidation.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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() );
}
 
Example 22
Source Project: msf4j   Source File: LDAPUserStoreManager.java    License: Apache License 2.0 5 votes vote down vote up
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
        }
    }
 
Example 23
@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"));
}
 
Example 24
/**
 * 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;
}
 
Example 25
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
    * {@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;
		}
	});
}
 
Example 26
Source Project: olat   Source File: LDAPLoginManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 27
Source Project: tomcatsrc   Source File: WebappClassLoaderBase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set associated resources.
 */
public void setResources(DirContext resources) {

    this.resources = resources;

    if (resources instanceof ProxyDirContext) {
        contextName = ((ProxyDirContext) resources).getContextName();
    }
}
 
Example 28
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 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();
}
 
Example 29
Source Project: spring-ldap   Source File: DirContextAdapterTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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");
}
 
Example 30
Source Project: hadoop   Source File: TestLdapGroupsMapping.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}