Spring LDAP Mapping Attributes to POJO with AttributesMapper Example
This tutorial demonstrates how to use spring LDAP to map attributes on a POJO using the AttributesMapper<T> class.
Maven Dependencies
We use Apache Maven to manage our project dependencies. Add the following dependencies to your project.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.memorynotfound.ldap</groupId> <artifactId>attributes-mapper</artifactId> <version>1.0.0-SNAPSHOT</version> <url>https://memorynotfound.com</url> <name>Spring LDAP - ${project.artifactId}</name> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.7.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-ldap</artifactId> </dependency> <dependency> <groupId>com.unboundid</groupId> <artifactId>unboundid-ldapsdk</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
Configure Embedded LDAP Server using application.yml
We use spring boot to create and configure our embedded LDAP server. The following properties create an LDAP server running on port 12345 and populates the LDAP server using the schema.ldif which resides on the class-path.
# Spring LDAP Mapping Attributes to POJO with AttributesMapper configuration application.yml spring: ldap: # Spring LDAP # # In this example we use an embedded ldap server. When using a real one, # you can configure the settings here. # # urls: ldap://localhost:12345 # base: dc=memorynotfound,dc=com # username: uid=admin # password: secret # Embedded Spring LDAP embedded: base-dn: dc=memorynotfound,dc=com credential: username: uid=admin password: secret ldif: classpath:schema.ldif port: 12345 validation: enabled: false
Populate LDAP Server
The LDAP servers gets populated using the following schema.ldif file.
dn: dc=memorynotfound,dc=com objectclass: top objectclass: domain objectclass: extensibleObject dc: memorynotfound # Organizational Units dn: ou=groups,dc=memorynotfound,dc=com objectclass: top objectclass: organizationalUnit ou: groups dn: ou=people,dc=memorynotfound,dc=com objectclass: top objectclass: organizationalUnit ou: people # Create People dn: uid=john,ou=people,dc=memorynotfound,dc=com objectclass: top objectclass: person objectclass: organizationalPerson objectclass: inetOrgPerson cn: John Doe sn: John uid: john password: secret dn: uid=jihn,ou=people,dc=memorynotfound,dc=com objectclass: top objectclass: person objectclass: organizationalPerson objectclass: inetOrgPerson cn: Jihn Die sn: Jihn uid: jihn password: secret dn: uid=jahn,ou=people,dc=memorynotfound,dc=com objectclass: top objectclass: person objectclass: organizationalPerson objectclass: inetOrgPerson cn: Jahn Dae sn: Jahn uid: jahn password: secret # Create Groups dn: cn=developers,ou=groups,dc=memorynotfound,dc=com objectclass: top objectclass: groupOfUniqueNames cn: developers ou: developer uniqueMember: uid=john,ou=people,dc=memorynotfound,dc=com uniqueMember: uid=jihn,ou=people,dc=memorynotfound,dc=com dn: cn=managers,ou=groups,dc=memorynotfound,dc=com objectclass: top objectclass: groupOfUniqueNames cn: managers ou: manager uniqueMember: uid=jahn,ou=people,dc=memorynotfound,dc=com
Bootstrap Spring Application
We bootstrap our application using spring boot. When the application is initialized, we invoke some methods that’ll query the LDAP server.
package com.memorynotfound.ldap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import javax.annotation.PostConstruct; import java.util.List; @SpringBootApplication public class Application { private static Logger log = LoggerFactory.getLogger(Application.class); private static final String BASE = "dc=memorynotfound,dc=com"; @Autowired private PersonRepository personRepository; public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } @PostConstruct public void setup(){ log.info("Spring LDAP Mapping Attributes to POJO with AttributesMapper Example"); Listnames = personRepository.getAllPersonNames(); log.info("names: " + names); List persons = personRepository.getAllPersons(); log.info("persons: " + persons); Person person = personRepository.findPerson("uid=john,ou=people," + BASE); log.info("person: " + person); System.exit(-1); } }
Person POJO
A simple Person POJO which represents a person object in the LDAP server. We are using this POJO to map our person attributes from the LDAP server.
package com.memorynotfound.ldap; public class Person { private String fullName; private String lastName; public Person() { } public Person(String fullName, String lastName) { this.fullName = fullName; this.lastName = lastName; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return "Person{" + "fullName='" + fullName + '\'' + ", lastName='" + lastName + '\'' + '}'; } }
Spring LDAP Mapping Attributes to POJO with AttributesMapper Example
The inline implementation of AttributesMapper in the getAllPersonNames() method just gets the desired attribute value from the Attributes and returns it. Internally, LdapTemplate iterates over all entries found, calling the given AttributesMapper for each entry, and collects the results in a list. The list is returned by the search method.
Note that the AttributesMapper implementation could be modified to return a full Person object.
Entries in LDAP are uniquely identified by their distinguished name (DN). If you have the DN of an entry, you can retrieve the entry directly without searching for it. This is called a lookup in Java LDAP. The findPerson() method demonstrates a lookup for a Person object.
package com.memorynotfound.ldap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ldap.core.AttributesMapper; import org.springframework.ldap.core.LdapTemplate; import org.springframework.stereotype.Service; import javax.naming.NamingException; import javax.naming.directory.Attributes; import java.util.List; import static org.springframework.ldap.query.LdapQueryBuilder.query; @Service public class PersonRepository { @Autowired private LdapTemplate ldapTemplate; /** * Retrieves all the persons in the ldap server, but we need to map each attribute individually * @return list of person names */ public ListgetAllPersonNames() { return ldapTemplate.search( query().where("objectclass").is("person"), new AttributesMapper () { public String mapFromAttributes(Attributes attrs) throws NamingException { return (String) attrs.get("cn").get(); } }); } /** * Retrieves all the persons in the ldap server, using {@link PersonAttributesMapper} * @return list of persons */ public List getAllPersons() { return ldapTemplate.search(query() .where("objectclass").is("person"), new PersonAttributesMapper()); } /** * Searching for one person, using {@link PersonAttributesMapper} * @param dn distinguaged name for the person * @return person */ public Person findPerson(String dn) { return ldapTemplate.lookup(dn, new PersonAttributesMapper()); } /** * Custom person attributes mapper, maps the attributes to the person POJO */ private class PersonAttributesMapper implements AttributesMapper { public Person mapFromAttributes(Attributes attrs) throws NamingException { Person person = new Person(); person.setFullName((String)attrs.get("cn").get()); person.setLastName((String)attrs.get("sn").get()); return person; } } }
Output
The previous application will print the following output to the console.
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.7.RELEASE) 2017-10-02 10:58:19.462 INFO 8760 --- [main] com.memorynotfound.ldap.Application: Spring LDAP - attributesMapper Example 2017-10-02 10:58:19.499 INFO 8760 --- [main] com.memorynotfound.ldap.Application: names: [Jahn Dae, Jihn Die, John Doe] 2017-10-02 10:58:19.502 INFO 8760 --- [main] com.memorynotfound.ldap.Application: persons: [Person{fullName='Jahn Dae', lastName='Jahn'}, Person{fullName='Jihn Die', lastName='Jihn'}, Person{fullName='John Doe', lastName='John'}] 2017-10-02 10:58:19.504 INFO 8760 --- [main] com.memorynotfound.ldap.Application: person: Person{fullName='John Doe', lastName='John'}
Download
From:一号门
COMMENTS