import java.io.UnsupportedEncodingException; import com.novell.ldap.LDAPAttribute; import com.novell.ldap.LDAPAttributeSet; import com.novell.ldap.LDAPConnection; import com.novell.ldap.LDAPEntry; import com.novell.ldap.LDAPException; import com.novell.ldap.LDAPModification; public class LDAPModifyAddTest { private int ldapPort = 10389; private int ldapVersion = LDAPConnection.LDAP_V3; private String ldapHost = "localhost"; private String loginDN = "uid=admin,ou=system"; private String password = "secret"; public static void main(String[] args) { LDAPModifyAddTest test = new LDAPModifyAddTest(); test.execute(new LDAPTemplate() { public Object doInConnection(LDAPConnection lc) throws LDAPException { // Create a new group String groupDN = "cn=testgroup,ou=groups,ou=system"; LDAPAttributeSet attributeSet = new LDAPAttributeSet(); attributeSet.add(new LDAPAttribute("objectclass", new String[] { "groupOfUniqueNames", "top" })); attributeSet.add(new LDAPAttribute("cn", "testgroup")); LDAPEntry newEntry = new LDAPEntry(groupDN, attributeSet); lc.add(newEntry); // Add one member String userDN1 = "uid=user1,ou=users,ou=system"; LDAPAttribute member = new LDAPAttribute("uniqueMember", userDN1); LDAPModification mod = new LDAPModification(LDAPModification.ADD, member); lc.modify(groupDN, mod); // Add another member String userDN2 = "uid=user2,ou=users,ou=system"; member = new LDAPAttribute("uniqueMember", userDN2); mod = new LDAPModification(LDAPModification.ADD, member); lc.modify(groupDN, mod); // Retrieve group LDAPEntry entry = lc.read(groupDN); LDAPAttribute members = entry.getAttribute("uniqueMember"); String[] values = members.getStringValueArray(); assert values.length == 2 : "Expected 2 values, found " + values.length + " instead"; return null; } }); } /** * Executes a template method in the context of an LDAP connection, taking care of * opening and closing a connection and dealing with exceptions. * * @param template The template method implementing class. */ private Object execute(LDAPTemplate template) { LDAPConnection lc = new LDAPConnection(); try { lc.connect(this.ldapHost, this.ldapPort); lc.bind(this.ldapVersion, this.loginDN, this.password.getBytes("UTF8")); return template.doInConnection(lc); } catch (LDAPException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } finally { try { lc.disconnect(); } catch (LDAPException ignored) {} } } /** * Common interface for template methods. */ interface LDAPTemplate { public Object doInConnection(LDAPConnection lc) throws LDAPException; } }