Search code examples
javaoracle-databaseldap

Oracle LDAP Move User to a Different OU with Java


I'm looking for a way to change the OU of a user in my Oracle LDAP, using Java. So far I found only the DirContext.rename method, but that results in a corrupted LDAP entry. Below is the code I tried.

    Hashtable<String, String> environment = new Hashtable<String, String>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");
    environment.put(Context.REFERRAL, "follow");
    environment.put(Context.PROVIDER_URL, "ldap://localhost:10389");
    environment.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    environment.put(Context.SECURITY_CREDENTIALS, "admin");

    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(environment);
        String oldCn = "uid=wso21,ou=wso2,ou=Users,dc=WSO2,dc=ORG";
        String newCn = "uid=wso21,ou=vodafone,ou=Users,dc=WSO2,dc=ORG";
        ctx.rename(oldCn, newCn);
    } catch (NamingException e) {
        e.printStackTrace();
    } finally {
        try {
            ctx.close();
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

After this is executed, the moved entry is there but no attributes are present.

TIA!


Solution

  • Please modify try Block:

    try {
        ctx = new InitialDirContext(environment);
        String oldDn = "uid=wso21,ou=wso2,ou=Users,dc=WSO2,dc=ORG";
        String newDn = "uid=wso21,ou=vodafone,ou=Users,dc=WSO2,dc=ORG";
        String newCn="newCN";
        String newSn="newSN";
        Attributes attrs = ctx.getAttributes(oldDn);
        ctx.rename(oldDn,newDn);
        attrs.remove("cn");
        attrs.remove("sn");
        //if needed remove more attributes
        attrs.put("cn",newCn);
        attrs.put("sn",newSn);
        //if needed add more attributes
        ctx.modifyAttributes(newDn, DirContext.ADD_ATTRIBUTE, attrs);
    }