view jndi/src/test/java/de/codedo/jndi/JndiTestCase.java @ 23:99472565ba0b

Extract the code to create a new user to the User object
author Dirk Olmes <dirk.olmes@codedo.de>
date Tue, 25 Oct 2016 15:39:52 +0000
parents 886a28c5898c
children f6e07a3d95a2
line wrap: on
line source

package de.codedo.jndi;

import org.junit.*;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;

public class JndiTestCase extends Object
{
	private static final String GROUP_BASE = "ou=groups,dc=ldap,dc=example,dc=org";
	private static final String USER_BASE = "ou=users,dc=ldap,dc=example,dc=org";

	@Ignore
	@Test
	public void createInLdap() throws Exception
	{
		DirContext context = createContext();

		Attribute objectClass = new BasicAttribute("objectClass"); 
		objectClass.add("inetOrgPerson");
		objectClass.add("organizationalPerson");
		objectClass.add("person");
		objectClass.add("top");

		Attribute cn = new BasicAttribute("cn", "Peter");
		Attribute sn = new BasicAttribute("sn", "Penis");
		Attribute uid = new BasicAttribute("uid", "ppe");

		Attributes attributes = new BasicAttributes();
		attributes.put(objectClass);
		attributes.put(cn);
		attributes.put(sn);
		attributes.put(uid);

		String dn = "uid=ppe," + USER_BASE;
		context.createSubcontext(dn, attributes);

		context.close();
	}

	@Test
	public void createInLdap2() throws Exception
	{
		DirContext context = createContext();
		User user = new User("psb", "Fernand", "Pirschelbär");
		user.create(context);
		context.close();	
	}

	@Ignore
	@Test
	public void findHighestGroupNumber() throws Exception
	{
		DirContext context = createContext();

		int highest = 0;

		NamingEnumeration<NameClassPair> groupEnum = context.list(GROUP_BASE);
		while (groupEnum.hasMore())
		{
			NameClassPair pair = groupEnum.next();
			int groupNumber = getGroupNumber(context, pair.getName());
			highest = Math.max(highest, groupNumber);
		}

		Assert.assertEquals(10002, highest);
	}

	private int getGroupNumber(DirContext context, String groupCn) throws Exception
	{
		String dn = groupCn + "," + GROUP_BASE;
		Attributes attributes = context.getAttributes(dn);
		//System.out.println(attributes);

		Attribute gidNumber = attributes.get("gidNumber");
		//System.out.println(gidNumber);
		String value = gidNumber.get().toString();
		return Integer.valueOf(value);
	}

	private DirContext createContext() throws Exception
	{
		Hashtable<String, Object> env = new Hashtable<>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, "ldap://192.168.66.66:389");
		env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=ldap,dc=example,dc=org");
		env.put(Context.SECURITY_CREDENTIALS, "geheim");

		return new InitialDirContext(env);
	}
}