org.springframework.ldap.core.ContextMapper Java Examples

The following examples show how to use org.springframework.ldap.core.ContextMapper. 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: SupportedControlsITest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
   @Category(NoAdTest.class)
public void testExpectedControlsSupported() throws Exception {
	/**
	 * Maps the 'supportedcontrol' attribute to a string array.
	 */
	ContextMapper mapper = new ContextMapper() {

		public Object mapFromContext(Object ctx) {
			DirContextAdapter adapter = (DirContextAdapter) ctx;
			return adapter.getStringAttributes(SUPPORTED_CONTROL);
		}

	};

	String[] controls = (String[]) tested.lookup("", new String[] { SUPPORTED_CONTROL }, mapper);
	System.out.println(Arrays.toString(controls));

       HashSet<String> controlsSet = new HashSet<String>(Arrays.asList(controls));

       assertThat(controlsSet.contains("1.3.6.1.4.1.4203.1.10.1")).as("Entry Change Notification LDAPv3 control,").isTrue();
	assertThat(controlsSet.contains("1.3.6.1.4.1.4203.1.10.1")).as("Subentries Control,").isTrue();
	assertThat(controlsSet.contains("2.16.840.1.113730.3.4.2")).as("Manage DSA IT LDAPv3 control,").isTrue();
}
 
Example #2
Source File: LdapUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static Name getDnOfEntry(LdapTemplate ldapTemplate, String baseDN,
    String objectClass, String filterAttributeName, String filterAttributeValue) {

    ContextMapper<Name> mapper =
        new AbstractContextMapper<Name>() {
            public Name doMapFromContext(DirContextOperations ctx) {
                return ctx.getDn();
            }
        };

    AndFilter filter = new AndFilter();
    filter.and(
        new EqualsFilter("objectclass", objectClass)).and(
            new EqualsFilter(filterAttributeName, filterAttributeValue));

    List<Name> result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, mapper);

    if (result != null && !result.isEmpty()) {
        //not only the first one....
        return result.get(0);
    }
    return null;
}
 
Example #3
Source File: UsersTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testStudentAuthenticate() throws AuthenticationException {
    DistinguishedName dn = new DistinguishedName("ou=Students");
    List<String> mockGroups = new ArrayList<String>();
    mockGroups.add("Student");
    Mockito.when(
            ldapTemplate.search(Mockito.eq(dn), Mockito.eq("(&(objectclass=posixGroup)(memberuid=studentuser))"),
                    Mockito.any(GroupContextMapper.class))).thenReturn(mockGroups);

    Mockito.when(
            ldapTemplate.authenticate(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=studentuser))"),
                    Mockito.eq("studentuser1234"), Mockito.any(AuthenticationErrorCallback.class))).thenReturn(true);

    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put("userName", "Student User");
    attributes.put("userType", "student");
    attributes.put("employeeNumber", "1234567890");
    User mockUser = new User("studentuser", mockGroups, attributes);

    Mockito.when(
            ldapTemplate.searchForObject(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=studentuser))"),
                    Mockito.any(ContextMapper.class))).thenReturn(mockUser);

    UserService.User user = userService.authenticate("Students", "studentuser", "studentuser1234");
    assertEquals("1234567890", user.getUserId());
    assertEquals("Student User", user.getAttributes().get("userName"));
    assertEquals("student", user.getAttributes().get("userType"));
    assertEquals(1, user.getRoles().size());
    assertEquals("Student", user.getRoles().get(0));
}
 
Example #4
Source File: LdapTemplateLookupOpenLdapITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that only the subset is used when specifying a subset of the
 * available attributes as return attributes.
 */
public void testLookup_ReturnAttributes_ContextMapper() {
    ContextMapper mapper = new PersonContextMapper();

    Person person = (Person) tested.lookup(
            "cn=Some Person2, ou=company1,c=Sweden", new String[] { "cn" },
            mapper);

    assertThat(person.getFullname()).isEqualTo("Some Person2");
    assertThat(person.getLastname()).as("lastName should not be set").isNull();
    assertThat(person.getDescription()).as("description should not be set").isNull();
}
 
Example #5
Source File: LdapTemplateLookupOpenLdapITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * This method depends on a DirObjectFactory ({@link org.springframework.ldap.core.support.DefaultDirObjectFactory})
 * being set in the ContextSource.
 */
public void testLookup_ContextMapper() {
    ContextMapper mapper = new PersonContextMapper();
    Person person = (Person) tested.lookup(
            "cn=Some Person2, ou=company1,c=Sweden", mapper);

    assertThat(person.getFullname()).isEqualTo("Some Person2");
    assertThat(person.getLastname()).isEqualTo("Person2");
    assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2");
}
 
Example #6
Source File: LdapTemplateSearchResultITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test(expected = SizeLimitExceededException.class)
public void verifyThatSearchWithCountLimitWithFlagToFalseThrowsException() {
    tested.setIgnoreSizeLimitExceededException(false);
    tested.search(query()
            .countLimit(3)
            .where("objectclass").is("person"), new ContextMapper<Object>() {
        @Override
        public Object mapFromContext(Object ctx) throws NamingException {
            return new Object();
        }
    });
}
 
Example #7
Source File: LdapTemplateSearchResultITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyThatSearchWithCountLimitReturnsTheEntriesFoundSoFar() {
    List<Object> result = tested.search(query()
            .countLimit(3)
            .where("objectclass").is("person"), new ContextMapper<Object>() {
        @Override
        public Object mapFromContext(Object ctx) throws NamingException {
            return new Object();
        }
    });

    assertThat(result).hasSize(3);
}
 
Example #8
Source File: LdapTemplateLookupITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that only the subset is used when specifying a subset of the
 * available attributes as return attributes.
 */
@Test
public void testLookup_ReturnAttributes_ContextMapper() {
	ContextMapper mapper = new PersonContextMapper();

	Person person = (Person) tested.lookup("cn=Some Person2, ou=company1,ou=Sweden", new String[] { "cn" }, mapper);

	assertThat(person.getFullname()).isEqualTo("Some Person2");
	assertThat(person.getLastname()).as("lastName should not be set").isNull();
	assertThat(person.getDescription()).as("description should not be set").isNull();
}
 
Example #9
Source File: LdapTemplateLookupITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * This method depends on a DirObjectFactory (
 * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory})
 * being set in the ContextSource.
 */
@Test
public void testLookup_ContextMapper() {
	ContextMapper mapper = new PersonContextMapper();
	Person person = (Person) tested.lookup("cn=Some Person2, ou=company1,ou=Sweden", mapper);

	assertThat(person.getFullname()).isEqualTo("Some Person2");
	assertThat(person.getLastname()).isEqualTo("Person2");
	assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2");
}
 
Example #10
Source File: LdapTemplateContextMapperITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Demonstrates how to retrieve all values of a multi-value attribute.
 * 
 * @see LdapTemplateAttributesMapperITest#testSearch_AttributesMapper_MultiValue()
 */
@Test
public void testSearch_ContextMapper_MultiValue() throws Exception {
	ContextMapper mapper = new ContextMapper() {
		public Object mapFromContext(Object ctx) {
			DirContextAdapter adapter = (DirContextAdapter) ctx;
			String[] members = adapter.getStringAttributes("uniqueMember");
			return members;
		}
	};
	List result = tested.search("ou=groups", "(&(objectclass=groupOfUniqueNames)(cn=ROLE_USER))", mapper);

	assertThat(result).hasSize(1);
	assertThat(((String[]) result.get(0)).length).isEqualTo(4);
}
 
Example #11
Source File: LdapTemplateContextMapperITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * This method depends on a DirObjectFactory ({@link org.springframework.ldap.core.support.DefaultDirObjectFactory})
 * being set in the ContextSource.
 */
@Test
public void testSearch_ContextMapper() {
	ContextMapper mapper = new PersonContextMapper();
	List result = tested.search("ou=company1,ou=Sweden", "(&(objectclass=person)(sn=Person2))", mapper);

	assertThat(result).hasSize(1);
	Person person = (Person) result.get(0);
	assertThat(person.getFullname()).isEqualTo("Some Person2");
	assertThat(person.getLastname()).isEqualTo("Person2");
	assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2");
}
 
Example #12
Source File: UsersTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testSandboxAuthenticate() throws AuthenticationException {
    DistinguishedName dn = new DistinguishedName("ou=SLIAdmin");
    Mockito.when(
            ldapTemplate.authenticate(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=testuser))"),
                    Mockito.eq("testuser1234"), Mockito.any(AuthenticationErrorCallback.class))).thenReturn(true);
    User mockUser = new User();
    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put("userName", "Test User");
    attributes.put("Tenant", "mytenant");
    attributes.put("isAdmin", "true");
    mockUser.attributes = attributes;
    mockUser.userId = "testuser";
    Mockito.when(
            ldapTemplate.searchForObject(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=testuser))"),
                    Mockito.any(ContextMapper.class))).thenReturn(mockUser);
    List<String> mockGroups = new ArrayList<String>();
    mockGroups.add("TestGroup1");
    mockGroups.add("TestGroup2");
    Mockito.when(
            ldapTemplate.search(Mockito.eq(dn), Mockito.eq("(&(objectclass=posixGroup)(memberuid=testuser))"),
                    Mockito.any(GroupContextMapper.class))).thenReturn(mockGroups);

    UserService.User user = userService.authenticate("SLIAdmin", "testuser", "testuser1234");
    assertEquals("testuser", user.getUserId());
    assertEquals("Test User", user.getAttributes().get("userName"));
    assertEquals("mytenant", user.getAttributes().get("Tenant"));
    assertEquals("admin", user.getAttributes().get("userType"));
    assertEquals(2, user.getRoles().size());
    assertEquals("TestGroup1", user.getRoles().get(0));
    assertEquals("TestGroup2", user.getRoles().get(1));
}
 
Example #13
Source File: UsersTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testStaffAuthenticate() throws AuthenticationException {
    DistinguishedName dn = new DistinguishedName("ou=StaffMember");
    List<String> mockGroups = new ArrayList<String>();
    mockGroups.add("Educator");
    Mockito.when(
            ldapTemplate.search(Mockito.eq(dn), Mockito.eq("(&(objectclass=posixGroup)(memberuid=staffuser))"),
                    Mockito.any(GroupContextMapper.class))).thenReturn(mockGroups);

    Mockito.when(
            ldapTemplate.authenticate(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=staffuser))"),
                    Mockito.eq("staffuser1234"), Mockito.any(AuthenticationErrorCallback.class))).thenReturn(true);

    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put("userName", "Staff User");
    attributes.put("userType", "staff");
    User mockUser = new User("staffuser", mockGroups, attributes);

    Mockito.when(
            ldapTemplate.searchForObject(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=staffuser))"),
                    Mockito.any(ContextMapper.class))).thenReturn(mockUser);

    UserService.User user = userService.authenticate("StaffMember", "staffuser", "staffuser1234");
    assertEquals("staffuser", user.getUserId());
    assertEquals("Staff User", user.getAttributes().get("userName"));
    assertEquals("staff", user.getAttributes().get("userType"));
    assertEquals(1, user.getRoles().size());
    assertEquals("Educator", user.getRoles().get(0));
}
 
Example #14
Source File: UsersTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticate() throws AuthenticationException {
    DistinguishedName dn = new DistinguishedName("ou=SLIAdmin");
    Mockito.when(
            ldapTemplate.authenticate(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=testuser))"),
                    Mockito.eq("testuser1234"), Mockito.any(AuthenticationErrorCallback.class))).thenReturn(true);
    User mockUser = new User();
    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put("userName", "Test User");
    mockUser.attributes = attributes;
    mockUser.userId = "testuser";
    Mockito.when(
            ldapTemplate.searchForObject(Mockito.eq(dn), Mockito.eq("(&(objectclass=person)(uid=testuser))"),
                    Mockito.any(ContextMapper.class))).thenReturn(mockUser);
    List<String> mockGroups = new ArrayList<String>();
    mockGroups.add("TestGroup1");
    mockGroups.add("TestGroup2");
    Mockito.when(
            ldapTemplate.search(Mockito.eq(dn), Mockito.eq("(&(objectclass=posixGroup)(memberuid=testuser))"),
                    Mockito.any(GroupContextMapper.class))).thenReturn(mockGroups);

    UserService.User user = userService.authenticate("SLIAdmin", "testuser", "testuser1234");
    assertEquals("testuser", user.getUserId());
    assertEquals("Test User", user.getAttributes().get("userName"));
    assertEquals("staff", user.getAttributes().get("userType"));
    assertEquals(2, user.getRoles().size());
    assertEquals("TestGroup1", user.getRoles().get(0));
    assertEquals("TestGroup2", user.getRoles().get(1));
}
 
Example #15
Source File: LdapPrincipalDaoImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public CustomContextMapperCallbackHandler(ContextMapper mapper) {
    super(mapper);
}
 
Example #16
Source File: LdapPrincipalDaoImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public void setContextMappers(final Map<String, ContextMapper> contextMappers) {
    this.contextMappers = contextMappers;
}
 
Example #17
Source File: LdapPrincipalDaoImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public Map<String, ContextMapper> getContextMappers() {
    return this.contextMappers;
}
 
Example #18
Source File: LdapPrincipalDaoImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public <T> List<T> search(Class<T> type, Map<String, Object> criteria) {
    AndFilter filter = new AndFilter();
    
    for (Map.Entry<String, Object> entry : criteria.entrySet()) {
        //attempting to handle null values to prevent NPEs in this code.
        if (entry.getValue() == null) {
            entry.setValue("null");
        }
        if (entry.getValue() instanceof Iterable) {
            OrFilter orFilter = new OrFilter();
            for (String value : (Iterable<String>) entry.getValue()) {
                if (value.startsWith("!")) {
                    orFilter.or(new NotFilter(new LikeFilter(entry.getKey(), value.substring(1))));
                } else {
                    orFilter.or(new LikeFilter(entry.getKey(), value));
                }
            }
            filter.and(orFilter);
        }
        else {
            if (((String)entry.getValue()).startsWith("!")) {
                filter.and(new NotFilter(new LikeFilter(entry.getKey(), ((String)entry.getValue()).substring(1))));
            } else {
                filter.and(new LikeFilter(entry.getKey(), (String) entry.getValue()));
            }
        }
    };
    
    info("Using filter ", filter);

    debug("Looking up mapper for ", type.getSimpleName());
    final ContextMapper customMapper = contextMappers.get(type.getSimpleName());

    ContextMapperCallbackHandler callbackHandler = new CustomContextMapperCallbackHandler(customMapper);
    
    try {
        getLdapTemplate().search(DistinguishedName.EMPTY_PATH, 
                                 filter.encode(), 
                                 getSearchControls(), callbackHandler);
    }
    catch (SizeLimitExceededException e) {
        // Ignore this. We want to limit our results.
    }

    return callbackHandler.getList();
}
 
Example #19
Source File: EntityNamePrincipalNameMapper.java    From rice with Educational Community License v2.0 2 votes vote down vote up
/**
 * Sets the value of defaultNameMapper
 *
 * @param argDefaultNameMapper Value to assign to this.defaultNameMapper
 */
public final void setDefaultNameMapper(final ContextMapper argDefaultNameMapper) {
    this.defaultNameMapper = argDefaultNameMapper;
}
 
Example #20
Source File: EntityNamePrincipalNameMapper.java    From rice with Educational Community License v2.0 2 votes vote down vote up
/**
 * Gets the value of defaultNameMapper
 *
 * @return the value of defaultNameMapper
 */
public final ContextMapper getDefaultNameMapper() {
    return this.defaultNameMapper;
}
 
Example #21
Source File: LdapPrincipalDao.java    From rice with Educational Community License v2.0 votes vote down vote up
Map<String, ContextMapper> getContextMappers();