http://www.javabeat.net/2011/05/introduction-to-spring-ldap/all/1/
JavaBeat
Java / J2EE Web Frameworks XML Technologies Tools & IDEs RIA Web Servers Internet Scripting
Hosting Java
Ads by Google
Java Download
Java
Java Tutorial
Nearshore Software
Spring LDAP
Introduction
1.0 Client!
www.swiftmq.com
Adaxes: AD im Griff
LDAP operations
In this section, we will illustrate the usage of various operations that can be performed on LDAP directory using Spring. The examples given here are tested with Apache Directory server, however the code should work with any LDAP implementations. The operations that will be getting covered in the following sections are, Searching Adding objects Removing objects Modifying objects
Searching objects
For illustrating search operations in LDAP, we will create objects under the node system/users. We will be creating objects of type person in this node. Note that for having an object oriented access for the person type, we will create a java class User that maps to it. Have a look at the declaration of this class.
1 package net.javabeat.articles.spring.ldap; 2
1 von 11
27.05.2012 04:33
http://www.javabeat.net/2011/05/introduction-to-spring-ldap/all/1/
3 public class User { 4 5 private String commonName; 6 private String telephone; 7 8 public String getCommonName() { 9 return commonName; 10 } 11 12 public void setCommonName(String commonName) { 13 this.commonName = commonName; 14 15 16 17 18 19 20 21 22 23 24 25 26 27 } }
The class definition is pretty simple. It defines two simple properties commonName and telephone. The search class that makes use of Spring libraries is given below. Go through the following code carefully.
1 package net.javabeat.articles.spring.ldap.operations; 2 3 import java.util.HashSet; 4 import java.util.Set; 5 6 7 8 9 10 import net.javabeat.articles.spring.ldap.User; import net.javabeat.articles.spring.ldap.UserAttributesMapper;
UserAttributesMapper mapper = new UserAttributesMapper(); return new HashSet<User>( ldapTemplate.search("ou=users,ou=system", "(objectClass=person)", mapper)); }
SimpleSearch simpleSearch = new SimpleSearch(); simpleSearch.setLdapTemplate(context.getBean("ldapTemplate", LdapTemplate.class)); for (User user : simpleSearch.getAllUsers()){ System.out.println(user); } }
Note that the class defines an instance of LdapTemplate class. This template class follows the template pattern and is very similar to the existing template classes like JdbcTemplate, JmsTemplate etc. Performing operations on the LDAP directory becomes simple with this template class. Note that before using this template class, it has to be configured with various properties such as username, password and the url of the directory server. We will see the configuration in the later section of this
2 von 11
27.05.2012 04:33
http://www.javabeat.net/2011/05/introduction-to-spring-ldap/all/1/
article. Carefully examine the method getAllUsers(). This method calls the search() method defined on LdapTemplate for searching objects in the directory server. Note that this method takes two parameters, the first being the base domain name and the second one defines the filter. In our case, since the objects are located under the node system/users, the base domain name happens to be ou=users,ou=system, here ou stands for organizational unit. For the second parameter we have used the value objectClass=person which means that we want to search objects of type person. Note that since LDAP can store objects of any type, the return objects have to be mapped to some implementation representing a custom model and for the same purpose, we have used the customized implementation of AttributesMapper implementation which is UserAttributesMapper.
1 package net.javabeat.articles.spring.ldap; 2 3 import javax.naming.NamingException; 4 import javax.naming.directory.Attributes; 5 6 import org.springframework.ldap.core.AttributesMapper; 7 8 public class UserAttributesMapper implements AttributesMapper { 9 10 @Override 11 public User mapFromAttributes(Attributes attributes) throws NamingException { 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 }
String commonName = (String)attributes.get("cn").get(); userObject.setCommonName(commonName); if (attributes.get("telephoneNumber") == null){ System.out.println("Telephone is null for " + commonName); }else{ String telephone = attributes.get("telephoneNumber").get().toString(); userObject.setTelephone(telephone); } return userObject; }
Note that in the above class, the method mapFromAttributes() is overridden which takes the input as Attributes which represents a general purpose attribute collection. The implementation creates a customized flavor of model implementation by gathering the relevant attributes and then constructs the object accordingly.
AndFilter filterObject = new AndFilter(); filterObject.and(new EqualsFilter("objectClass", "person")); filterObject.and(new EqualsFilter("sn", surName));
3 von 11
27.05.2012 04:33
http://www.javabeat.net/2011/05/introduction-to-spring-ldap/all/1/
34 35 36 37 38 39 40 41 42 43 44 45 46 47 }
DynamicSearch dynamicSearch = new DynamicSearch(); dynamicSearch.setLdapTemplate(context.getBean("ldapTemplate", LdapTemplate.class)); for (User user : dynamicSearch.getAllUsers("David")){ System.out.println(user); } }
A variation of searching objects dynamically in the directory server is given above. In the above code, the obvious variation is the search filter being dynamically constructed using Filter APIs. We have dynamically constructed search parameters objectClass, sn and have anded them using AndFilter. Rest of the code in the above section remains the same.
Adding objects
In this section, we will see how to add objects in the LDAP directory. For adding objects, the bind() defined on LdapTemplate can be used. Note that the bind() methods takes the distinguished name and the list of attributes as parameters. Note that the unique distinguished name represents the combination of base name and the common name. The base name is ou=users,ou=system in our case and the common name will come as user input.
import net.javabeat.articles.spring.ldap.User; 8 9 import org.springframework.context.ApplicationContext; 10 import org.springframework.context.support.ClassPathXmlApplicationContext; 11 import org.springframework.ldap.core.DistinguishedName; 12 import org.springframework.ldap.core.LdapTemplate; 13 14 public class AddUser { 15 16 private LdapTemplate ldapTemplate; 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
4 von 11
27.05.2012 04:33
http://www.javabeat.net/2011/05/introduction-to-spring-ldap/all/1/
48 49 50 51 52 53 54 55 }
SimpleSearch simpleSearch = new SimpleSearch(); simpleSearch.setLdapTemplate(ldapTemplate); for (User user : simpleSearch.getAllUsers()){ System.out.println(user); } }
For adding simple attributes, we can use the put() method defined on the BasicAttributes class. The attribute objectClass is a multi-valued attribute. By default, any object defined in LDAP will have the objectClass set to top. Hence, in our case, the object type for the person objects will be {top, person}. Hence for adding a multi-valued attribute such as objectClass, the attribute values have to be packaged as a BasicAttribute object and then have to be added to the main attribute.
Removing objects
For removing objects from the directory server, the method unbind() can be used. Because a distinguished name represents a unique name in the directory server, the unbind() method takes an instance of distinguished name as an argument.
Online Dashboard software Online reporting solution to manage KPIs in web based dashboards
www.bittle-solutions.com
1 package net.javabeat.articles.spring.ldap.operations; 2 3 import net.javabeat.articles.spring.ldap.User; 4 5 import org.springframework.context.ApplicationContext; 6 import org.springframework.context.support.ClassPathXmlApplicationContext; 7 import org.springframework.ldap.core.DistinguishedName; 8 import org.springframework.ldap.core.LdapTemplate; 9 10 public class RemoveUser { 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 } } } private LdapTemplate ldapTemplate;
ldapTemplate.unbind(distinguisedName);
SimpleSearch simpleSearch = new SimpleSearch(); simpleSearch.setLdapTemplate(ldapTemplate); for (User user : simpleSearch.getAllUsers()){ System.out.println(user); }
The above code tries to remove a person and then queries for the list of person objects in the directory server.
Modifying objects
Existing objects can be modified by invoking the method modifyAttributes() defined on the LdapTemplate class. Note that the arguments to this method are the distinguished name and the list of attributes to be modified.
5 von 11
27.05.2012 04:33
http://www.javabeat.net/2011/05/introduction-to-spring-ldap/all/1/
1 2 3 4 5 6 7 8 9 10 11
package net.javabeat.articles.spring.ldap.operations;
import net.javabeat.articles.spring.ldap.User;
Attribute telephoneAttribute = new BasicAttribute("telephoneNumber", telephone); ModificationItem telephoneItem = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, telephoneAttribute); ldapTemplate.modifyAttributes(distinguisedName, new ModificationItem[]{telephoneItem}); }
SimpleSearch simpleSearch = new SimpleSearch(); simpleSearch.setLdapTemplate(ldapTemplate); for (User user : simpleSearch.getAllUsers()){ System.out.println(user); } }
Each attribute to be modified must be represented through a ModificationItem object which specifies the flag whether the value of the existing attribute has to be replaced or a new attribute can be created of the attribute if it doesnt exist. In the above sample, for modifying the telephoneNumber attribute, we have used the REPLACE_ATTRIBUTE flag which will replace the existing attribute value for the person object.
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans 4 5 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 6 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"> 7 <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate"> 8 9 <property name="contextSource" ref="contextSource" /> </bean> 10 11 12 <bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource"> 13 14 15 16 <property <property <property <property name="url" value="ldap://localhost:10389" /> name="userDn" value="uid=admin,ou=system" /> name="password" value="secret" /> name="pooled" value="false" />
6 von 11
27.05.2012 04:33
http://www.javabeat.net/2011/05/introduction-to-spring-ldap/all/1/
17 </bean> 18 19 </beans>
The Spring configuration file for configuring LdapTemplate instance is given below. Note that the property contextSource has to be populated. The contextSource property is of type LdapContextSource and the mandatory properties userDn, password and url have to be specified.
~~~~~~~~~~~~
LDIF Parser
LDIF stands for LDAP Directory Interchange Format and it represents the way of storing LDAP objects information in a flat file so that they can be easily transported to different machines hosting LDAP servers. Spring LDAP framework provides support for parsing LDAP objects available in a text file and this section illustrates the usage of these APIs.
1 2 3 4 5 6 7 8 9 10 11 12 13
dn: ou=users,ou=system sn: SN-1 telephoneNumber: 33333 objectClass: person objectClass: top cn: CN-1
dn: ou=users,ou=system sn: SN-2 telephoneNumber: 77777 objectClass: person objectClass: top cn: CN-2
Now we will see how to make use of LDIF parser. The program constructs an instance of LdifParser object and then calls the hasMoreRecords() and getRecord() for reading all attribute information from the text file. A call to getRecord() will retrieve a single record information from the file. The method getAll() will return all the attribute names for the record. Since there is a possibility for an attribute to contain multiple values, we again call getAll() method to collect the attribute values.
1 2 3 4 5 6
package net.javabeat.articles.spring.ldif;
7 import org.springframework.core.io.FileSystemResource; 8 import org.springframework.ldap.ldif.parser.LdifParser; 9 import org.springframework.ldap.ldif.parser.Parser; 10 11 public class LdifTest { 12 13 public static void main(String[] args) throws Exception{ 14 15 Parser parser = new LdifParser(); 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 } }
while (parser.hasMoreRecords()){
7 von 11
27.05.2012 04:33
http://www.javabeat.net/2011/05/introduction-to-spring-ldap/all/1/
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 } }
while (attributeNames.hasMoreElements()) {
ODM Manager
ODM stands for Object Directory Mapping and this facilitates mapping of the LDAP objects directly to java objects with the help of annotations. For this example, we will create a customized type applicationEntity under the node system/configuration/services. We will start with the java model class ApplicationEntity which will have the core attributes cn, description and presentationAddress.
1 package net.javabeat.artices.spring.odm; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import javax.naming.Name; 7 8 import org.springframework.ldap.odm.annotations.Attribute; 9 import org.springframework.ldap.odm.annotations.Entry; 10 import org.springframework.ldap.odm.annotations.Id; 11 12 @Entry(objectClasses = {"applicationEntity", "top"}) 13 public class ApplicationEntity { 14 15 @Id 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 private Name distinguisedName;
8 von 11
27.05.2012 04:33
http://www.javabeat.net/2011/05/introduction-to-spring-ldap/all/1/
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 }
public String toString(){ return cn + "#" + description + "#" + objectClassNames + "#" + presentationAddress; }
To specify that the java class maps directly to some ldap object, the annotation @Entry has to be used. Note that this annotation has to be configured with the list of object types, in our case, this happens to be top and applicationEntiy. One mandatory attribute of type Name representing the distinguished name has to be defined and has to be annotated with @Id. The attributes for this entity can then be defined, each annotated with @Attribute annotation.
1 package net.javabeat.artices.spring.odm; 2 3 import java.util.List; 4 5 import javax.naming.directory.SearchControls; 6 7 import org.springframework.context.ApplicationContext; 8 import org.springframework.context.support.ClassPathXmlApplicationContext; 9 import org.springframework.ldap.core.DistinguishedName; 10 import org.springframework.ldap.odm.core.OdmManager; 11 12 public class Main { 13 14 public static void main(String[] args) { 15 16 ApplicationContext context = new ClassPathXmlApplicationContext("config.xml"); 17 OdmManager odmManager = context.getBean("odmManager", OdmManager.class); 18 19 create(odmManager); 20 list(odmManager); 21 read(odmManager); 22 } 23 24 private static void create(OdmManager odmManager){ 25 ApplicationEntity addressEntity = new ApplicationEntity(); 26 27 28 DistinguishedName distinguishedName = new DistinguishedName("ou=services,ou=configuration,ou=system"); distinguishedName.add("cn", "Address"); 29 addressEntity.setDistinguisedName(distinguishedName); 30 addressEntity.setCn("Address"); 31 addressEntity.setDescription("Contains information about the Address entity"); 32 33 34 35 36 37 addressEntity.setPresentationAddress("Address");
addressEntity.getObjectClassNames().add("top"); addressEntity.getObjectClassNames().add("applicationEntity");
9 von 11
27.05.2012 04:33
http://www.javabeat.net/2011/05/introduction-to-spring-ldap/all/1/
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
odmManager.create(addressEntity); }
List<ApplicationEntity> applicationEntityList = odmManager.findAll( ApplicationEntity.class, distinguisedName, searchControls); for (ApplicationEntity applicationEntity : applicationEntityList){ System.out.println(applicationEntity); } }
64 65 }
For creating a new object, we can use the method create() defined on OdmManager class. An instance of ApplicationEntity is created and the distinguished name is set by calling the setDistinguishedName() method. After that the various attributes like cn, address and presentationAddress is populated on the entity object. For reading an entity, the method read() can be used by passing in an instance of distinguished name. For listing all the objects of a particular object type, the method findAll() defined on OdmManager class can be used. This method takes the entity type and the distinguished name as parameters.
Conclusion
This article started with covering the basics of Spring LDAP by illustrating the various operations such as search, add, remove, modify etc that can be performed. Lots of samples were also given for the better illustration of these concepts. LDAP directory data can be stored externally in a file for easier migration and hence Spring LDAP supports parsing data from such files with the help of LDIF Parser. The final section of the article illustrated the usage of ODM Manager which provides a directory mapping between ldap objects and java objects through annotations.
Hosting Java
Ads by Google
Java Download
Java
Java Tutorial
Comments
0 comments
Add a comment...
Comment using...
Related posts: 1. Introduction to Spring JDBC Framework 2. Introduction to Spring OXM 3. Introduction to Spring Converters and Formatters 4. Introduction to Spring Expression Language (SpEL) 5. Introduction to Spring Validation Spring LDAP
About krishnas View all posts by krishnas How to integrate legacy views with designer tools in Griffon
10 von 11
27.05.2012 04:33
http://www.javabeat.net/2011/05/introduction-to-spring-ldap/all/1/
Like Login
Showing 0 comments
M Subscribe by email S RSS
Subscribe Submit your email id to receive the latest news on Java Technology.
Recent Posts Annotation Based Bean Wiring @Autowired in Spring framework Enhanced Collections API in Java 8- Supports Lambda expressions A sneak peak at the Lambda Expressions in Java 8 Whats new in Spring 3.0? What are Functional Interfaces and Functional Descriptor? Recent Comments Annotation Based Bean Wiring @Autowired in Spring frameworkJavaBeat on Introduction to Spring Web Framework Annotation Based Bean Wiring @Autowired in Spring frameworkJavaBeat on Spring Framework Interview Questions Enhanced Collections API in Java 8- Supports Lambda expressionsJavaBeat on Virtual Extension (or Defender) Methods in Java 8 Shahjoyful on Mapping Java Objects and XML Documents using JAXB in Java 6.0 Shahjoyful on Mapping Java Objects and XML Documents using JAXB in Java 6.0 Popular Posts Spring Framework Interview Questions 6 comment(s) | 111 view(s) Introduction to Spring MVC Framework 2 comment(s) | 74 view(s) File Upload and Download using Java 10 comment(s) | 72 view(s) Introduction to Hibernate Caching 0 comment(s) | 63 view(s) Design Patterns Interview Questions 0 comment(s) | 61 view(s) Spring and Hibernate ORM Framework Integration 2 comment(s) | 52 view(s)
TechBreaths Greenshot A Free Screenshot Tool for Windows How to add Post Statistics link for JetPack plugin? Desktop App for Amazon Cloud Drive Google Drive offers 5GB Free Storage How to add author RSS Feed in WordPress Blog? Archives
Categories
May 2011 M T W T F S S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Apr Jun Recent Posts Annotation Based Bean Wiring @Autowired in Spring framework Enhanced Collections API in Java 8- Supports Lambda expressions A sneak peak at the Lambda Expressions in Java 8 Whats new in Spring 3.0? What are Functional Interfaces and Functional Descriptor? JavaBeat Copyright 2012. All Rights Reserved.
11 von 11
27.05.2012 04:33