VII. Test for DAO
- Let's create a class executable to test our DAO.
Code:
Public class TestLdap {
/** Retrieve has Kurt Person from LDAP server and display Kurt in
Standard Out */
Public static void hand(String [] args) {
}
}
The executable class takes into account any argument.
- Let's add the main method in the Context Source
Code:
// 1 Retrieve has LdapContextSource
ContextSource consrc = null;
try {
consrc = LdapContextSourceFactory.getLdapContextSource();
} catch (Exception e) {
System.out.System.out.println("Unable to get has LdapContextSource.");
e.printStackTrace();
}
- It must also obtain a LdapTemplate.
Code:
// 2 Instanciate has LdapTemplate
LdapTemplate ldaptem = new LdapTemplate();
ldaptem.setContextSource(ldapContextSource);
- Instantiating a Dao and provide him ldapTemplate.
Code:
// 3 instanciate has PersonDao
PersonDao c = new PersonDao();
c.setLdapTemplate(ldapTemplate);
- Recovery of Kurt is just using the DAO.
Code:
// 4 retrieve has Person and display it
Person prs = cad.findByPrimaryKey("kurt");
System.out.System.out.println("Uid: " + prs.getuid());
System.out.System.out.println("FirstName: " + prs.getFirstName());
System.out.System.out.println("LastName: " + prs.getLastName());
System.out.System.out.println("Email: " + prs.getEmail() + "\ n");
Execute the program and you will get the desired results.
VIII. Improved CAD
Add a method that allows the DAO to retrieve a list of people from their name. The class LikeFilter can use filters with wildcards searches:
Here is the code for it
Code:
Public List getPersonNamesByLastName(String lsnm) {
AndFilter flt = new AndFilter();
flt.and(new EqualsFilter("objectclass", "person"));
flt.and(new LikeFilter("sn", lsnm));
return ldapTemplate.search("", Filter.encodes(),
new PersonAttributMapper());
}
- Complement the main class with an example of using this new feature.
Code:
// 5 retrieve has list of person
List lsprs = cad.getPersonNamesByLastName("* e *");
for (Object object: lsprs) {
System.out.System.out.println("Person: " + object);
}
The execution of the main class returns 2 persons in standard output.
IX. Conclusion
Spring LDAP is a library that allows J2EE simply retrieve records LDAP as java objects and free the developer from the Java knowledge LDAP mechanisms. Spring LDAP can also write to the LDAP server. Hope this tutorial was useful.
Bookmarks