org.springframework.ldap.support.LdapUtils Java Examples
The following examples show how to use
org.springframework.ldap.support.LdapUtils.
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: LdapTemplateTest.java From spring-ldap with Apache License 2.0 | 6 votes |
@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 #2
Source File: LdapTemplateTest.java From spring-ldap with Apache License 2.0 | 6 votes |
@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 #3
Source File: BaseDAOTest.java From geofence with GNU General Public License v2.0 | 6 votes |
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 File: LdapAuthenticationProvider.java From hesperides with GNU General Public License v3.0 | 6 votes |
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 #5
Source File: UserService.java From spring-ldap with Apache License 2.0 | 6 votes |
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 #6
Source File: LdapTestUtils.java From spring-ldap with Apache License 2.0 | 6 votes |
@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 #7
Source File: LdapTemplateBindUnbindITest.java From spring-ldap with Apache License 2.0 | 6 votes |
@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 #8
Source File: NameAwareAttribute.java From spring-ldap with Apache License 2.0 | 6 votes |
@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 #9
Source File: LdapTemplateTest.java From spring-ldap with Apache License 2.0 | 6 votes |
@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 #10
Source File: LdapTemplateNoBaseSuffixITest.java From spring-ldap with Apache License 2.0 | 6 votes |
@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 #11
Source File: DirContextAdapterTest.java From spring-ldap with Apache License 2.0 | 6 votes |
@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 File: LdapTemplateOdmWithDnAnnotationsITest.java From spring-ldap with Apache License 2.0 | 6 votes |
@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 #13
Source File: RebindOperationExecutorTest.java From spring-ldap with Apache License 2.0 | 6 votes |
@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 #14
Source File: LdapAuthRepositoryCustomImpl.java From Spring-5.0-Projects with MIT License | 6 votes |
@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 #15
Source File: LdapTemplateOdmGroupManipulationITest.java From spring-ldap with Apache License 2.0 | 6 votes |
@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 #16
Source File: LdapTemplateOdmWithDnAnnotationsITest.java From spring-ldap with Apache License 2.0 | 6 votes |
@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 #17
Source File: BaseLdapPathBeanPostprocessorNamespaceConfigITest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testPostProcessBeforeInitializationWithNamespaceConfigAndPooling() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( "/conf/baseLdapPathPostProcessorPoolingNamespaceTestContext.xml"); DummyBaseLdapPathAware tested = ctx.getBean(DummyBaseLdapPathAware.class); DistinguishedName base = tested.getBase(); assertThat(base).isNotNull(); assertThat(base).isEqualTo(new DistinguishedName("dc=jayway,dc=se")); DummyBaseLdapNameAware otherTested = ctx.getBean(DummyBaseLdapNameAware.class); assertThat(otherTested.getBaseLdapPath()).isEqualTo(LdapUtils.newLdapName("dc=jayway,dc=se")); }
Example #18
Source File: DifferentSubtreeTempEntryRenamingStrategyTest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testGetTemporaryName() { LdapName originalName = LdapUtils.newLdapName( "cn=john doe, ou=somecompany, c=SE"); DifferentSubtreeTempEntryRenamingStrategy tested = new DifferentSubtreeTempEntryRenamingStrategy( LdapUtils.newLdapName("ou=tempEntries")); int nextSequenceNo = tested.getNextSequenceNo(); // Perform test Name result = tested.getTemporaryName(originalName); // Verify result assertThat(result.toString()).isEqualTo("cn=john doe" + nextSequenceNo + ",ou=tempEntries"); }
Example #19
Source File: DirContextAdapterTest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testNewLdapNameWithString() throws NamingException { tested.addAttributeValue("member", LdapUtils.newLdapName("CN=test,DC=root")); tested.addAttributeValue("member2", LdapUtils.newLdapName("CN=test2,DC=root")); Attributes attrs = tested.getAttributes(); assertThat(attrs.get("member").get()).isEqualTo(LdapUtils.newLdapName("CN=test,DC=root")); assertThat(attrs.get("member2").get()).isEqualTo(LdapUtils.newLdapName("CN=test2,DC=root")); }
Example #20
Source File: LdapTemplatePooledITest.java From spring-ldap with Apache License 2.0 | 5 votes |
/** * This method depends on a DirObjectFactory ( * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) * being set in the ContextSource. */ @Test public void verifyThatInvalidConnectionIsAutomaticallyPurged() throws Exception { LdapTestUtils.startEmbeddedServer(1888, "dc=261consulting,dc=com", "jayway"); LdapTestUtils.cleanAndSetup(contextSource, LdapUtils.emptyLdapName(), new ClassPathResource("/setup_data.ldif")); DirContextOperations result = tested.lookupContext("cn=Some Person2, ou=company1,ou=Sweden"); assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person2"); assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); assertThat(result.getStringAttribute("description")).isEqualTo("Sweden, Company1, Some Person2"); // Shutdown server and kill all existing connections LdapTestUtils.shutdownEmbeddedServer(); LdapTestUtils.startEmbeddedServer(1888, "dc=261consulting,dc=com", "jayway"); try { tested.lookup("cn=Some Person2, ou=company1,ou=Sweden"); fail("Exception expected"); } catch (Exception expected) { // This should fail because the target connection was closed assertThat(true).isTrue(); } LdapTestUtils.cleanAndSetup(contextSource, LdapUtils.emptyLdapName(), new ClassPathResource("/setup_data.ldif")); // But this should be OK, because the dirty connection should have been automatically purged. tested.lookup("cn=Some Person2, ou=company1,ou=Sweden"); }
Example #21
Source File: BaseLdapPathBeanPostProcessorTest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testPostProcessBeforeInitializationWithLdapNameAwareBasePathSet() throws Exception { String expectedPath = "dc=example, dc=com"; tested.setBasePath(expectedPath); Object result = tested.postProcessBeforeInitialization(ldapNameAwareMock, "someName"); verify(ldapNameAwareMock).setBaseLdapPath(LdapUtils.newLdapName(expectedPath)); assertThat(result).isSameAs(ldapNameAwareMock); }
Example #22
Source File: DefaultController.java From spring-ldap with Apache License 2.0 | 5 votes |
@RequestMapping("/showTree.do") public ModelAndView showTree() { LdapTree ldapTree = ldapTreeBuilder.getLdapTree(LdapUtils.emptyLdapName()); HtmlRowLdapTreeVisitor visitor = new PersonLinkHtmlRowLdapTreeVisitor(); ldapTree.traverse(visitor); return new ModelAndView("showTree", "rows", visitor.getRows()); }
Example #23
Source File: LdapTemplateListITest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testListBindings_ContextMapper_Name() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); LdapName dn = LdapUtils.newLdapName("ou=company2,ou=Sweden"); List list = tested.listBindings(dn, contextMapper); assertThat(list).hasSize(1); }
Example #24
Source File: LdapTemplateOdmWithNoDnAnnotationsITest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testFindByDn() { Person person = tested.findByDn(LdapUtils.newLdapName("cn=Some Person3,ou=company1,ou=Sweden"), Person.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"); assertThat(person.getEntryUuid()).describedAs("The operational attribute 'entryUUID' was not set").isNotEmpty(); }
Example #25
Source File: GroupController.java From spring-ldap with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/groups/{name}/members", method = POST) public String addUserToGroup(@PathVariable String name, @RequestParam String userId) { Group group = groupRepo.findByName(name); group.addMember(userService.toAbsoluteDn(LdapUtils.newLdapName(userId))); groupRepo.save(group); return "redirect:/groups/" + name; }
Example #26
Source File: GroupController.java From spring-ldap with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/groups/{name}/members", method = DELETE) public String removeUserFromGroup(@PathVariable String name, @RequestParam String userId) { Group group = groupRepo.findByName(name); group.removeMember(userService.toAbsoluteDn(LdapUtils.newLdapName(userId))); groupRepo.save(group); return "redirect:/groups/" + name; }
Example #27
Source File: NameAwareAttributeTest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testComparingWDistinguishedNameValueWithInvalidName() throws NamingException { // The names here are syntactically equal, but differ in exact string representation String expectedName1 = "cn=Jane Doe,ou=People"; String expectedValue2 = "thisisnotavaliddn"; NameAwareAttribute attr1 = new NameAwareAttribute("someAttribute"); attr1.add(LdapUtils.newLdapName(expectedName1)); NameAwareAttribute attr2 = new NameAwareAttribute("someAttribute"); attr2.add(expectedValue2); assertThat(attr1.equals(attr2)).isFalse(); assertThat(attr1.get()).isEqualTo(expectedName1); assertThat(attr2.get()).isEqualTo(expectedValue2); }
Example #28
Source File: UserService.java From spring-ldap with Apache License 2.0 | 5 votes |
public Iterable<Name> toRelativeIds(Iterable<Name> absoluteIds) { return Iterables.transform(absoluteIds, new Function<Name, Name>() { @Override public Name apply(Name input) { return LdapUtils.removeFirst(input, baseLdapPath); } }); }
Example #29
Source File: DirContextAdapter.java From spring-ldap with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override public SortedSet<String> getAttributeSortedStringSet(String name) { try { TreeSet<String> attrSet = new TreeSet<String>(); LdapUtils.collectAttributeValues(originalAttrs, name, attrSet, String.class); return attrSet; } catch (NoSuchAttributeException e) { // The attribute does not exist - contract says to return null. return null; } }
Example #30
Source File: LdapTemplateBindUnbindITest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testBindAndUnbindWithAttributesUsingLdapName() { Attributes attributes = setupAttributes(); tested.bind(LdapUtils.newLdapName(DN), null, attributes); verifyBoundCorrectData(); tested.unbind(LdapUtils.newLdapName(DN)); verifyCleanup(); }