tags:

views:

624

answers:

1

I need to be able to update an attribute on OpenLDAP using a Java class.

I've taken a stab at creating an LDAP entry, but it looks like a Java object instead of a proper LDAP entry. (Grrrr)

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.NameAlreadyBoundException;
import javax.naming.directory.*;
import java.util.*;

public class TestLDAP {
     static final long serialVersionUID = -1240113639782150930L;

        final static String ldapServerName = "localhost:636";
        final static String rootdn = "cn=The Manager,ou=mydept,o=mycompany";
        final static String rootpass = "password";
        final static String rootContext = "ou=mydept,o=mycompany";

        public static void main( String[] args ) {
         System.setProperty("javax.net.ssl.trustStore", "C:\\cacerts");


                Properties env = new Properties();
                env.put("com.sun.jndi.ldap.trace.ber", System.out);
                env.put( Context.INITIAL_CONTEXT_FACTORY,
                         "com.sun.jndi.ldap.LdapCtxFactory" );
                env.put(Context.SECURITY_PROTOCOL, "ssl");
                env.put( Context.PROVIDER_URL, "ldap://" + ldapServerName + "/" + rootContext );
                env.put( Context.SECURITY_PRINCIPAL, rootdn );
                env.put( Context.SECURITY_CREDENTIALS, rootpass );

                try {
                        // obtain initial directory context using the environment
                        DirContext ctx = new InitialDirContext( env );

                        // add LDAP entry
                        Attributes myAttrs = new BasicAttributes(true);
                        Attribute oc = new BasicAttribute("objectclass");

                        oc.add("inetOrgPerson");
                        oc.add("organizationalPerson");
                        oc.add("person");
                        oc.add("top");
                        myAttrs.put(oc);
                        myAttrs.put("cn","test996");
                        myAttrs.put("sn","test 996");

         ctx.bind("cn=test997", myAttrs);
                } catch ( NameAlreadyBoundException nabe ) {
                        System.err.println( "value has already been bound!" );
                } catch ( Exception e ) {
                        e.printStackTrace();
                }
        }
}

Pleaseee help!

+2  A: 

It's been a while since I've used LDAP, but looking at the Javadoc I think you're using the wrong method. Try something like:

ctx.bind("cn=test997", null, myAttrs);

Have you read through the LDAP tutorial? I found this quite helpful a while back when I had to do some LDAP work.

Phill Sacre
LDAP Tutorial ... yup. One of the first places google brought up. Unfortunately, no joy. Didn't have information to solve the problem. Anyway, I'm very close to solving the problem. Will post the solution once I'm done.
magius