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 32 33 34 35 36 37 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 64 65 66 67 68 69 70 71 72 73
| import java.util.Hashtable;
import java.util.Properties;
import java.util.jar.Attributes;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LdaTest{
public static void main(String[] args) {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL,"uid=admin,ou=system"); // specify the username
env.put(Context.SECURITY_CREDENTIALS,"secret");// specify the password
// TODO code application logic here
// entry's DN
String entryDN = "uid=newUser,dc=example,dc=com";
// entry's attributes
Attribute cn = new BasicAttribute("cn", "crestianao2");
Attribute sn = new BasicAttribute("sn", "ronaldino2");
Attribute mail = new BasicAttribute("mail", "crestiano2@yahoo.com");
Attribute phone = new BasicAttribute("telephoneNumber", "+1 222 333");
Attribute givenName = new BasicAttribute("givenName", "ronaldo");
Attribute userpassword = new BasicAttribute("userpassword", "crestiano");
Attribute oc = new BasicAttribute("objectClass");
oc.add("top");
oc.add("person");
oc.add("organizationalPerson");
oc.add("inetOrgPerson");
DirContext ctx = null;
try {
// get a handle to an Initial DirContext
ctx = new InitialDirContext(env);
// build the entry
BasicAttributes entry = new BasicAttributes();
entry.put(cn);
entry.put(givenName);
entry.put(sn);
entry.put(mail);
entry.put(phone);
entry.put(userpassword);
entry.put(oc);
entry.put(oc);
// Add the entry
ctx.createSubcontext(entryDN, entry);
// System.out.println( "AddUser: added entry " + entryDN + ".");
} catch (NamingException e) {
System.err.println("AddUser: error adding entry." + e);
}
}
} |
Partager