package de.company;
/**
* @author
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
import java.util.Hashtable;
import java.util.*;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.io.*;
public class AddEntryToLDAP {
public static void main(String[] args) throws NamingException {
addUser();
}
private static void addUser() throws NamingException {
final Hashtable<Object, Object> env = new Hashtable<Object, Object>();
DirContext dctx = null;
try {
String url = "ldap://localhost:389";
String conntype = "simple";
String AdminDn = "cn=Manager,dc=ephesoft,dc=com";
String password = "secret";
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, conntype);
env.put(Context.SECURITY_PRINCIPAL, AdminDn);
env.put(Context.SECURITY_CREDENTIALS, password);
dctx = new InitialDirContext(env);
// Create a container set of attributes
final Attributes container = new BasicAttributes();
// Create the objectclass to add
final Attribute objClasses = new BasicAttribute("objectClass");
objClasses.add("inetOrgPerson");
// Assign the username, first name, and last name
final Attribute commonName = new BasicAttribute("cn", "TestUser");
final Attribute email = new BasicAttribute("mail", "TestUser");
final Attribute givenName = new BasicAttribute("givenName", "test1");
final Attribute uid = new BasicAttribute("uid", "TestUser");
final Attribute surName = new BasicAttribute("sn", "test2");
// Add password
final Attribute userPassword = new BasicAttribute("userpassword", "test1");
// Add these to the container
container.put(objClasses);
container.put(commonName);
container.put(givenName);
container.put(email);
container.put(uid);
container.put(surName);
container.put(userPassword);
// Create the entry
dctx.createSubcontext(getUserDN("TestUser"), container);
} finally {
if (null != dctx) {
try {
dctx.close();
} catch (final NamingException e) {
System.out.println("Error in closing ldap " + e);
}
}
}
}
private static String getUserDN(final String userName) {
String userDN = new StringBuffer().append("cn=").append(userName).append(",OU=people,dc=ephesoft,dc=com").toString();
System.out.println(userDN);
return userDN;
}
}