Java Code Examples for org.springframework.ldap.support.LdapUtils

The following examples show how to use org.springframework.ldap.support.LdapUtils. 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
Source Project: Spring-5.0-Projects   Source File: LdapAuthRepositoryCustomImpl.java    License: MIT License 6 votes vote down vote up
@Override
public boolean authenticateLdapUserWithContext(String userName, String password) {
	DirContext ctx = null;
	try {
		String userDn = getDnForUser(userName);
		ctx = ldapTemplate.getContextSource().getContext(userDn, password);
		return true;
	} catch (Exception e) {
		// If exception occurred while creating Context, means - authentication did not succeed
		logger.error("Authentication failed ", e.getMessage(),e);
		return false;
	} finally {
		// DirContext must be closed here.
		LdapUtils.closeContext(ctx);
	}
}
 
Example 2
private Set<String> extractGroupAuthoritiesRecursivelyWithCache(DirContextAdapter userData, String username, String password) {
    Attributes attributes;
    try {
        attributes = userData.getAttributes("");
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    }
    LdapSearchContext ldapSearchContext = createLdapSearchContext(username, password);
    try {
        cachedParentLdapGroupAuthorityRetriever.setParentGroupsDNRetriever(ldapSearchContext);
        Set<String> groupAuthorities = new HashSet<>();
        HashSet<String> parentGroupsDN = extractDirectParentGroupDNs(attributes);
        for (String groupDN : parentGroupsDN) {
            groupAuthorities.addAll(cachedParentLdapGroupAuthorityRetriever.retrieveParentGroups(groupDN));
        }
        return groupAuthorities;
    } finally {
        ldapSearchContext.closeContext();
    }
}
 
Example 3
Source Project: geofence   Source File: BaseDAOTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static void loadData() throws Exception
{
    // Bind to the directory
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl("ldap://127.0.0.1:10389");
    contextSource.setUserDn("uid=admin,ou=system");
    contextSource.setPassword("secret");
    contextSource.setPooled(false);
    //contextSource.setDirObjectFactory(null);
    contextSource.afterPropertiesSet();

    // Create the Sprint LDAP template
    LdapTemplate template = new LdapTemplate(contextSource);

    // Clear out any old data - and load the test data
    LdapTestUtils.clearSubContexts(contextSource, LdapUtils.newLdapName("dc=example,dc=com"));
    LdapTestUtils.loadLdif(contextSource, new ClassPathResource("data.ldif"));
}
 
Example 4
Source Project: spring-ldap   Source File: LdapTestUtils.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private static void loadLdif(DirContext context, Name rootNode, Resource ldifFile) {
       try {
           LdapName baseDn = (LdapName)
                   context.getEnvironment().get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY);

           LdifParser parser = new LdifParser(ldifFile);
           parser.open();
           while (parser.hasMoreRecords()) {
               LdapAttributes record = parser.getRecord();

               LdapName dn = record.getName();

               if(baseDn != null) {
                   dn = LdapUtils.removeFirst(dn, baseDn);
               }

               if(!rootNode.isEmpty()) {
                   dn = LdapUtils.prepend(dn, rootNode);
               }
               context.bind(dn, null, record);
           }
       } catch (Exception e) {
           throw new UncategorizedLdapException("Failed to populate LDIF", e);
       }
   }
 
Example 5
Source Project: spring-ldap   Source File: NameAwareAttribute.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean remove(Object attrval) {
    if (attrval instanceof Name) {
        initValuesAsNames();

        Name name = LdapUtils.newLdapName((Name) attrval);
        String removedValue = valuesAsNames.remove(name);
        if(removedValue != null) {
            values.remove(removedValue);

            return true;
        }

        return false;
    }
    return values.remove(attrval);
}
 
Example 6
Source Project: spring-ldap   Source File: LdapTemplateNoBaseSuffixITest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBindAndUnbind_Plain() {
	DirContextAdapter adapter = new DirContextAdapter();
	adapter.setAttributeValues("objectclass", new String[] { "top", "person" });
	adapter.setAttributeValue("cn", "Some Person4");
	adapter.setAttributeValue("sn", "Person4");
	tested.bind("cn=Some Person4, ou=company1, ou=Sweden," + base, adapter, null);

	DirContextAdapter result = (DirContextAdapter) tested
			.lookup("cn=Some Person4, ou=company1, ou=Sweden," + base);

	assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person4");
	assertThat(result.getStringAttribute("sn")).isEqualTo("Person4");
	assertThat(result.getDn()).isEqualTo(LdapUtils.newLdapName("cn=Some Person4,ou=company1,ou=Sweden," + base));

	tested.unbind("cn=Some Person4,ou=company1,ou=Sweden," + base);
	try {
		tested.lookup("cn=Some Person4, ou=company1, ou=Sweden," + base);
		fail("NameNotFoundException expected");
	}
	catch (NameNotFoundException expected) {
		assertThat(true).isTrue();
	}
}
 
Example 7
@Test
public void testSetMembersSyntacticallyEqual() {
    Group group = tested.findOne(query().where("cn").is("ROLE_USER"), Group.class);

    group.setMembers(new HashSet<Name>(){{
        add(LdapUtils.newLdapName("CN=Some Person,OU=company1, ou=Sweden, " + base));
        add(LdapUtils.newLdapName("CN=Some Person2, OU=company1,ou=Sweden," + base));
    }});
    tested.update(group);

    Group verification = tested.findOne(query().where("cn").is("ROLE_USER"), Group.class);

    Set<Name> members = verification.getMembers();

    assertThat(members).hasSize(2);
    assertThat(members.contains(LdapUtils.newLdapName("cn=Some Person,ou=company1,ou=Sweden," + base))).isTrue();
    assertThat(members.contains(LdapUtils.newLdapName("cn=Some Person2,ou=company1,ou=Sweden," + base))).isTrue();
}
 
Example 8
@Test
public void testFindByDn() {
    PersonWithDnAnnotations person = tested.findByDn(LdapUtils.newLdapName("cn=Some Person3,ou=company1,ou=Sweden"),
            PersonWithDnAnnotations.class);

    assertThat(person).isNotNull();
    assertThat(person.getCommonName()).isEqualTo("Some Person3");
    assertThat(person.getSurname()).isEqualTo("Person3");
    assertThat(person.getDesc().get(0)).isEqualTo("Sweden, Company1, Some Person3");
    assertThat(person.getTelephoneNumber()).isEqualTo("+46 555-123654");

    // Automatically calculated
    assertThat(person.getCompany()).isEqualTo("company1");
    assertThat(person.getCountry()).isEqualTo("Sweden");
    assertThat(person.getEntryUuid()).describedAs("The operational attribute 'entryUUID' was not set").isNotEmpty();
}
 
Example 9
Source Project: spring-ldap   Source File: RebindOperationExecutorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPerformOperation() {
    LdapName expectedOriginalDn = LdapUtils.newLdapName(
            "cn=john doe");
    LdapName expectedTempDn = LdapUtils.newLdapName(
            "cn=john doe_temp");
    Object expectedObject = new Object();
    BasicAttributes expectedAttributes = new BasicAttributes();
    RebindOperationExecutor tested = new RebindOperationExecutor(
            ldapOperationsMock, expectedOriginalDn, expectedTempDn,
            expectedObject, expectedAttributes);

    // perform test
    tested.performOperation();
    verify(ldapOperationsMock).rename(expectedOriginalDn, expectedTempDn);
    verify(ldapOperationsMock)
            .bind(expectedOriginalDn, expectedObject, expectedAttributes);
}
 
Example 10
@Test
public void testUpdateWithChangedDn() {
    PersonWithDnAnnotations person = tested.findOne(query()
            .where("cn").is("Some Person3"), PersonWithDnAnnotations.class);

    // This should make the entry move
    person.setCountry("Norway");
    String entryUuid = person.getEntryUuid();
    assertThat(entryUuid).describedAs("The operational attribute 'entryUUID' was not set").isNotEmpty();
    tested.update(person);

    person = tested.findByDn(
            LdapUtils.newLdapName("cn=Some Person3, ou=company1, ou=Norway"),
            PersonWithDnAnnotations.class);

    assertThat(person.getCommonName()).isEqualTo("Some Person3");
    assertThat(person.getSurname()).isEqualTo("Person3");
    assertThat(person.getCountry()).isEqualTo("Norway");
    assertThat(person.getDesc().get(0)).isEqualTo("Sweden, Company1, Some Person3");
    assertThat(person.getTelephoneNumber()).isEqualTo("+46 555-123654");
    assertThat(person.getEntryUuid()).describedAs("The operational attribute 'entryUUID' was not set").isNotEmpty();
    assertThat(person.getEntryUuid()).isNotEqualTo(entryUuid);
}
 
Example 11
Source Project: spring-ldap   Source File: DirContextAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveDnAttributeSyntacticallyEqual() throws NamingException {
    BasicAttributes attributes = new BasicAttributes();
    attributes.put("uniqueMember", "cn=john doe,OU=company");

    DirContextAdapter tested = new DirContextAdapter(attributes, LdapUtils.newLdapName("cn=administrators, ou=groups"));
    tested.setUpdateMode(true);

    tested.removeAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=john doe, ou=company"));
    ModificationItem[] modificationItems = tested.getModificationItems();
    assertThat(modificationItems.length).isEqualTo(1);

    ModificationItem modificationItem = modificationItems[0];
    assertThat(modificationItem.getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
    assertThat(modificationItem.getAttribute().getID()).isEqualTo("uniqueMember");
}
 
Example 12
Source Project: spring-ldap   Source File: LdapTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnbindRecursive() throws Exception {
	expectGetReadWriteContext();

	when(namingEnumerationMock.hasMore()).thenReturn(true, false, false);
	Binding binding = new Binding("cn=Some name", null);
	when(namingEnumerationMock.next()).thenReturn(binding);

	LdapName listDn = LdapUtils.newLdapName(DEFAULT_BASE_STRING);
	when(dirContextMock.listBindings(listDn)).thenReturn(namingEnumerationMock);
	LdapName subListDn = LdapUtils.newLdapName("cn=Some name, o=example.com");
	when(dirContextMock.listBindings(subListDn)).thenReturn(namingEnumerationMock);

	tested.unbind(new CompositeName(DEFAULT_BASE_STRING), true);

       verify(dirContextMock).unbind(subListDn);
       verify(dirContextMock).unbind(listDn);
       verify(namingEnumerationMock, times(2)).close();
       verify(dirContextMock).close();
}
 
Example 13
Source Project: spring-ldap   Source File: LdapTemplateBindUnbindITest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBindAndRebindWithDirContextAdapterOnly() {
	DirContextAdapter adapter = new DirContextAdapter(LdapUtils.newLdapName(DN));
	adapter.setAttributeValues("objectclass", new String[] { "top",
			"person" });
	adapter.setAttributeValue("cn", "Some Person4");
	adapter.setAttributeValue("sn", "Person4");

	tested.bind(adapter);
	verifyBoundCorrectData();
	adapter.setAttributeValue("sn", "Person4.Changed");
	tested.rebind(adapter);
	verifyReboundCorrectData();
	tested.unbind(DN);
	verifyCleanup();
}
 
Example 14
Source Project: spring-ldap   Source File: LdapTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateWithIdSpecified() throws NamingException {
    expectGetReadWriteContext();

    Object expectedObject = new Object();
    LdapName expectedName = LdapUtils.newLdapName("ou=someOu");
    when(odmMock.getId(expectedObject)).thenReturn(expectedName);

    ArgumentCaptor<DirContextAdapter> ctxCaptor = ArgumentCaptor.forClass(DirContextAdapter.class);
    doNothing().when(odmMock).mapToLdapDataEntry(eq(expectedObject), ctxCaptor.capture());

    tested.create(expectedObject);

    verify(odmMock, never()).setId(expectedObject, expectedName);
    verify(dirContextMock).bind(expectedName, ctxCaptor.getValue(), null);
    verify(dirContextMock).close();
}
 
Example 15
Source Project: spring-ldap   Source File: LdapTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testModifyAttributesWithDirContextOperations() throws Exception {
	final ModificationItem[] expectedModifications = new ModificationItem[0];

       final LdapName epectedDn = LdapUtils.emptyLdapName();
       when(dirContextOperationsMock.getDn()).thenReturn(epectedDn);
	when(dirContextOperationsMock.isUpdateMode()).thenReturn(true);
	when(dirContextOperationsMock.getModificationItems()).thenReturn(expectedModifications);

	LdapTemplate tested = new LdapTemplate() {
		public void modifyAttributes(Name dn, ModificationItem[] mods) {
			assertThat(dn).isSameAs(epectedDn);
			assertThat(mods).isSameAs(expectedModifications);
		}
	};

	tested.modifyAttributes(dirContextOperationsMock);
}
 
Example 16
Source Project: spring-ldap   Source File: UserService.java    License: Apache License 2.0 6 votes vote down vote up
public User updateUser(String userId, User user) {
    LdapName originalId = LdapUtils.newLdapName(userId);
    User existingUser = userRepo.findOne(originalId);

    existingUser.setFirstName(user.getFirstName());
    existingUser.setLastName(user.getLastName());
    existingUser.setFullName(user.getFullName());
    existingUser.setEmail(user.getEmail());
    existingUser.setPhone(user.getPhone());
    existingUser.setTitle(user.getTitle());
    existingUser.setDepartment(user.getDepartment());
    existingUser.setUnit(user.getUnit());

    if (directoryType == DirectoryType.AD) {
        return updateUserAd(originalId, existingUser);
    } else {
        return updateUserStandard(originalId, existingUser);
    }
}
 
Example 17
Source Project: spring-ldap   Source File: DirContextAdapterBugTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testResetNullAttributeValueNotReportedAsModification() throws Exception {
    BasicAttributes attrs = new BasicAttributes("myattr", "b");
    UpdateAdapter ctx = new UpdateAdapter(attrs, LdapUtils.emptyLdapName());

    ctx.setAttributeValue("myattr", "a");
    ctx.setAttributeValue("myattr", "b");

    assertThat(ctx.getModificationItems().length).isEqualTo(0);
}
 
Example 18
Source Project: spring-ldap   Source File: DistinguishedName.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new <code>DistinguishedName</code> from the supplied
 * {@link Name}. The parts of the supplied {@link Name} must be
 * syntactically correct {@link LdapRdn}s.
 * 
 * @param name the {@link Name} to construct a new
 * <code>DistinguishedName</code> from.
 */
public DistinguishedName(Name name) {
	Assert.notNull(name, "name cannot be null");
	if (name instanceof CompositeName) {
		parse(LdapUtils.convertCompositeNameToString((CompositeName) name));
		return;
	}
	names = new LinkedList();
	for (int i = 0; i < name.size(); i++) {
		names.add(new LdapRdn(name.get(i)));
	}
}
 
Example 19
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public boolean authenticate(String base, String filter, String password) {
	return authenticate(LdapUtils.newLdapName(base), filter, password,
			new NullAuthenticatedLdapEntryContextCallback(),
			new NullAuthenticationErrorCallback());
}
 
Example 20
Source Project: spring-ldap   Source File: TestContextSourceFactoryBean.java    License: Apache License 2.0 5 votes vote down vote up
protected Object createInstance() throws Exception {
       LdapTestUtils.startEmbeddedServer(port, defaultPartitionSuffix, defaultPartitionName);

       if (contextSource == null) {
           // If not explicitly configured, create a new instance.
           LdapContextSource targetContextSource = new LdapContextSource();
           if (baseOnTarget) {
               targetContextSource.setBase(defaultPartitionSuffix);
           }

           targetContextSource.setUrl("ldap://localhost:" + port);
           targetContextSource.setUserDn(principal);
           targetContextSource.setPassword(password);
           targetContextSource.setDirObjectFactory(dirObjectFactory);
           targetContextSource.setPooled(pooled);

           if (authenticationSource != null) {
               targetContextSource.setAuthenticationSource(authenticationSource);
           }
           targetContextSource.afterPropertiesSet();

           contextSource = targetContextSource;
       }

       Thread.sleep(1000);

       if (baseOnTarget) {
		LdapTestUtils.clearSubContexts(contextSource, LdapUtils.emptyLdapName());
	}
	else {
		LdapTestUtils.clearSubContexts(contextSource, LdapUtils.newLdapName(defaultPartitionSuffix));
	}

	if (ldifFile != null) {
           LdapTestUtils.loadLdif(contextSource, ldifFile);
	}

	return contextSource;
}
 
Example 21
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> List<T> find(Name base, Filter filter, SearchControls searchControls, final Class<T> clazz) {
	Filter finalFilter = odm.filterFor(clazz, filter);

    // Search from the root if we are not told where to search from
    Name localBase = base;
    if (base == null || base.size() == 0) {
        localBase = LdapUtils.emptyLdapName();
    }

    // extend search controls with the attributes to return
    String[] attributes = odm.manageClass(clazz);
    searchControls.setReturningAttributes(attributes);
    
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Searching - base=%1$s, finalFilter=%2$s, scope=%3$s", base, finalFilter, searchControls));
    }

    List<T> result = search(localBase, finalFilter.encode(), searchControls, new ContextMapper<T>() {
        @Override
        public T mapFromContext(Object ctx) throws javax.naming.NamingException {
            return odm.mapFromLdapDataEntry((DirContextOperations) ctx, clazz);
        }
    });
    result.remove(null);

    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Found %1$s Entries - %2$s", result.size(), result));
    }

    return result;
}
 
Example 22
@Test
public void verifyParseWithCustomValues() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-values.xml");
    ContextSource outerContextSource = ctx.getBean(ContextSource.class);
    LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);
    DirContextAuthenticationStrategy authenticationStrategy = ctx.getBean(DirContextAuthenticationStrategy.class);

    assertThat(outerContextSource).isNotNull();
    assertThat(ldapTemplate).isNotNull();

    assertThat(outerContextSource instanceof TransactionAwareContextSourceProxy).isTrue();
    ContextSource contextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget();

    assertThat(LdapUtils.newLdapName("dc=261consulting,dc=com")).isEqualTo(getInternalState(contextSource, "base"));
    assertThat("uid=admin").isEqualTo(getInternalState(contextSource, "userDn"));
    assertThat("apassword").isEqualTo(getInternalState(contextSource, "password"));
    assertThat(new String[]{"ldap://localhost:389"}).isEqualTo((Object[]) getInternalState(contextSource, "urls"));
    assertThat(Boolean.TRUE).isEqualTo(getInternalState(contextSource, "pooled"));
    assertThat(Boolean.FALSE).isEqualTo(getInternalState(contextSource, "anonymousReadOnly"));
    assertThat("follow").isEqualTo(getInternalState(contextSource, "referral"));
    assertThat(authenticationStrategy).isSameAs(getInternalState(contextSource, "authenticationStrategy"));

    assertThat(outerContextSource).isSameAs(getInternalState(ldapTemplate, "contextSource"));
    assertThat(Boolean.TRUE).isEqualTo(getInternalState(ldapTemplate, "ignorePartialResultException"));
    assertThat(Boolean.TRUE).isEqualTo(getInternalState(ldapTemplate, "ignoreNameNotFoundException"));
    assertThat(100).isEqualTo(getInternalState(ldapTemplate, "defaultCountLimit"));
    assertThat(200).isEqualTo(getInternalState(ldapTemplate, "defaultTimeLimit"));
    assertThat(SearchControls.OBJECT_SCOPE).isEqualTo(getInternalState(ldapTemplate, "defaultSearchScope"));
}
 
Example 23
Source Project: spring-ldap   Source File: LdapQueryBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildSimpleAnd() {
    LdapQuery query = query()
            .base("dc=261consulting, dc=com")
            .searchScope(SearchScope.ONELEVEL)
            .timeLimit(200)
            .countLimit(221)
            .where("objectclass").is("person").and("cn").is("John Doe");

    assertThat(query.base()).isEqualTo(LdapUtils.newLdapName("dc=261consulting, dc=com"));
    assertThat(query.searchScope()).isEqualTo(SearchScope.ONELEVEL);
    assertThat(query.timeLimit()).isEqualTo(Integer.valueOf(200));
    assertThat(query.countLimit()).isEqualTo(Integer.valueOf(221));
    assertThat(query.filter().encode()).isEqualTo("(&(objectclass=person)(cn=John Doe))");
}
 
Example 24
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
private void doUnbindRecursively(final Name dn) {
	executeReadWrite(new ContextExecutor<Object>() {
		public Object executeWithContext(DirContext ctx) {
			deleteRecursively(ctx, LdapUtils.newLdapName(dn));
			return null;
		}
	});
}
 
Example 25
/**
 * Cast the NameClassPair to a SearchResult and pass its attributes to the
 * {@link AttributesMapper}.
 * 
 * @param nameClassPair a <code> SearchResult</code> instance.
 * @return the Object returned from the mapper.
 */
public T getObjectFromNameClassPair(NameClassPair nameClassPair) {
	if (!(nameClassPair instanceof SearchResult)) {
		throw new IllegalArgumentException("Parameter must be an instance of SearchResult");
	}

	SearchResult searchResult = (SearchResult) nameClassPair;
	Attributes attributes = searchResult.getAttributes();
	try {
		return mapper.mapFromAttributes(attributes);
	}
	catch (javax.naming.NamingException e) {
		throw LdapUtils.convertLdapException(e);
	}
}
 
Example 26
Source Project: spring-ldap   Source File: DirContextAdapter.java    License: Apache License 2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public ModificationItem[] getModificationItems() {
	if (!updateMode) {
		return new ModificationItem[0];
	}

	List<ModificationItem> tmpList = new LinkedList<ModificationItem>();
	NamingEnumeration<? extends Attribute> attributesEnumeration = null;
	try {
		attributesEnumeration = updatedAttrs.getAll();

		// find attributes that have been changed, removed or added
		while (attributesEnumeration.hasMore()) {
			NameAwareAttribute oneAttr = (NameAwareAttribute) attributesEnumeration.next();

			collectModifications(oneAttr, tmpList);
		}
	}
	catch (NamingException e) {
		throw LdapUtils.convertLdapException(e);
	}
	finally {
		closeNamingEnumeration(attributesEnumeration);
	}

	if (log.isDebugEnabled()) {
		log.debug("Number of modifications:" + tmpList.size());
	}

	return tmpList.toArray(new ModificationItem[tmpList.size()]);
}
 
Example 27
Source Project: spring-ldap   Source File: DirContextAdapterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAddDnAttributeValueIdentical() {
    BasicAttributes attributes = new BasicAttributes();
    attributes.put("uniqueMember", "cn=john doe, ou=company");

    DirContextAdapter tested = new DirContextAdapter(attributes, LdapUtils.newLdapName("cn=administrators, ou=groups"));
    tested.setUpdateMode(true);

    tested.addAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=john doe, ou=company"));
    ModificationItem[] modificationItems = tested.getModificationItems();
    assertThat(modificationItems.length).isEqualTo(0);
}
 
Example 28
Source Project: spring-ldap   Source File: UnbindOperationExecutorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRollback() {
    LdapName expectedOldName = LdapUtils.newLdapName("cn=oldDn");
    LdapName expectedTempName = LdapUtils.newLdapName("cn=newDn");
    UnbindOperationExecutor tested = new UnbindOperationExecutor(
            ldapOperationsMock, expectedOldName, expectedTempName);



    // Perform test
    tested.rollback();
    verify(ldapOperationsMock).rename(expectedTempName, expectedOldName);
}
 
Example 29
Source Project: spring-ldap   Source File: LdapTemplateRenameITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRename() {
	tested.rename(DN, NEWDN);

	verifyDeleted(LdapUtils.newLdapName(DN));
	verifyBoundCorrectData();
}
 
Example 30
Source Project: spring-ldap   Source File: BindOperationExecutorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPerformOperation() {
    LdapName expectedDn = LdapUtils.newLdapName("cn=john doe");
    Object expectedObject = new Object();
    BasicAttributes expectedAttributes = new BasicAttributes();
    BindOperationExecutor tested = new BindOperationExecutor(
            ldapOperationsMock, expectedDn, expectedObject,
            expectedAttributes);

    // perform teste
    tested.performOperation();

    verify(ldapOperationsMock).bind(expectedDn, expectedObject, expectedAttributes);
}