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 74 75 76 77 78 79 80
| import java.util.*;
import javax.naming.Context;
import javax.naming.NameAlreadyBoundException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.BasicAttribute;
public class AddUser {
public AddUser() {
}
private Hashtable<String, String> env;
private DirContext ctx;
private void _initialize() {
String jndiURL = "ldap://localhost:389";
String initialContextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
String authenticationMode = "simple";
String principal = "cn=admin,dc=example,dc=com";
String credentials = "secret";
env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
env.put(Context.PROVIDER_URL, jndiURL);
env.put(Context.SECURITY_AUTHENTICATION, authenticationMode);
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS, credentials);
}
public boolean createUser() {
try {
ctx = new InitialDirContext(env);
BasicAttributes attrs = new BasicAttributes();
BasicAttribute ocs = new BasicAttribute("objectclass");
ocs.add("user");
attrs.put(ocs);
BasicAttribute na = new BasicAttribute("name", "MyName");
attrs.put(na);
BasicAttribute sn = new BasicAttribute("sn", "MySurName");
attrs.put(sn);
BasicAttribute up = new BasicAttribute("mail", "essai@exemple.fr");
attrs.put(up);
BasicAttribute dn = new BasicAttribute("displayName", "MyDisplayName");
attrs.put(dn);
BasicAttribute gn = new BasicAttribute("givenName", "MyGivenName");
attrs.put(gn);
BasicAttribute des = new BasicAttribute("description",
"CECI EST MON TEST");
attrs.put(des);
ctx.createSubcontext("cn=admin,dc=example,dc=com", attrs);
ctx.close();
} catch (NameAlreadyBoundException nex) {
System.out
.println("User ID is already in use, please select a different user ID ...");
} catch (Exception ex) {
System.out
.println("Failed to create user account... Please verify the user information...");
ex.printStackTrace();
}
return true;
}
public static void main(String[] args) {
AddUser testUser = new AddUser();
testUser._initialize();
testUser.createUser();
}
} |
Partager