使用JAVA自帶方法增刪改查LDAP

今天搭建了一個openLDAP的環境,並建立了下面的結構: html

dc=ibm,dc=com
ou=developer,dc=ibm,dc=com
ou=tester,dc=ibm,dc=com
uid=bill,ou=developer,dc=ibm,dc=com
uid=kent,ou=tester,dc=ibm,dc=com java

OpenLDAP的配置方法:

1, 安裝.  windows

2, 修改slapd.conf, 更改suffix和root dn. 重啓instance. 若是是windows,則重啓service. oracle

3, 建立ldif文件, 寫入要往ldap中添加的entry. 能夠參考openLDAP目錄下給的example. ide

4, 執行添加任務. 若是存在ldapadd,則運行"ldapadd -x -D "bindDN" -w password -f xxx.ldif". 若是沒有,則使用slapdadd. "slapadd -v -l xxx.ldif". 記住,執行slapdadd以前,要先停掉ldap. oop

5, 在Base DN下搜用戶 ldapsearch -b "ou=tester,dc=ibm,dc=com "(uid=bi*)" ui

JAVA操做LDAP:

Official Guide:http://docs.oracle.com/javase/jndi/tutorial/getStarted/examples/directory.html this

使用JAVA自帶方法,添加修改查詢並刪除下面的記錄
uid=test,ou=tester,dc=ibm,dc=com spa

執行類 code

public class TestLdap {
	public static void main(String[] args) throws NamingException {
		Ldap ldap = Factory.createInstance();
		
		ldap.connect();
		try {
			// add uid=test,ou=tester,dc=ibm,dc=com
			ldap.add();
			// search uid=test
		    ldap.search();
		    // update cn with new value of "changed name"
		    ldap.update();
		    // search uid=test to see cn value.
		    ldap.search();
		    // delete uid=test,ou=tester,dc=ibm,dc=com
		    ldap.delete();
		    // search again.
		    ldap.search();
		} finally {
			ldap.close();
		}
	}
}

接口

public interface Ldap {
	public void connect() throws NamingException;
	public void search() throws NamingException;
	public void update() throws NamingException;
	public void add() throws NamingException;
	public void delete() throws NamingException;
	public void close() throws NamingException;
}

靜態工廠模式

public class Factory {
	private static Ldap instance;
	public synchronized static Ldap createInstance() {
		if (instance == null) {
			try {
				instance = (Ldap) Class.forName("ldap.LdapImpl").newInstance();
			} catch (Exception e) {
				throw new RuntimeException(e);
			} 
		}
		return instance;
	}
}

接口實現

public class LdapImpl implements Ldap {
	private DirContext ds;

	@Override
	public void search() throws NamingException {
		System.out.println("Searching...");
		SearchControls searchCtls = new SearchControls();

		// Specify the search scope
		searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		// specify the LDAP search filter
		String searchFilter = "uid=test";

		// Specify the Base for the search
		String searchBase = "dc=ibm,dc=com";

		// Specify the attributes to return
		String returnedAtts[] = { "cn" };
		searchCtls.setReturningAttributes(returnedAtts);

		// Search for objects using the filter
		NamingEnumeration<SearchResult> entries = ds.search(searchBase,
				searchFilter, searchCtls);

		// Loop through the search results
		while (entries.hasMoreElements()) {
			SearchResult entry = entries.next();
			System.out.println(">>>" + entry.getName());
			// Print out the groups
			Attributes attrs = entry.getAttributes();
			if (attrs != null) {
				for (NamingEnumeration<? extends Attribute> names = attrs
						.getAll(); names.hasMore();) {
					Attribute attr = names.next();
					System.out.println("AttributeID: " + attr.getID());
					for (NamingEnumeration<?> e = attr.getAll(); e.hasMore();) {
						System.out.println("Attributes:" + e.next());
					}
				}
			}
		}
		System.out.println("Search complete.");
	}

	@Override
	public void update() throws NamingException {
		System.out.println("Updating...");
		 ModificationItem[] mods = new ModificationItem[1];
         Attribute attr = new BasicAttribute("cn", "changed value");
         
         // Support add, replace and remove an attribute.
         mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);
         ds.modifyAttributes("uid=test,ou=tester,dc=ibm,dc=com", mods);
		System.out.println("Updated.");
	}

	@Override
	public void add() throws NamingException {
		System.out.println("Adding...");
		Attributes attrs = new BasicAttributes();
		attrs.put("uid", "test");
		attrs.put("sn", "test");
		attrs.put("cn", "test test");
		attrs.put("userPassword", "111111".getBytes());
		// the following attribute has two values
		Attribute objclass = new BasicAttribute("objectClass");
		objclass.add("inetOrgPerson");
		attrs.put(objclass);

		this.ds.createSubcontext("uid=test,ou=tester,dc=ibm,dc=com", attrs);
		System.out.println("Add complete.");
	}

	@Override
	public void delete() throws NamingException {
		System.out.println("Deleting...");
		this.ds.destroySubcontext("uid=test,ou=tester,dc=ibm,dc=com");
		System.out.println("Deleted.");
	}

	@Override
	public synchronized void connect() throws NamingException {
		System.out.println("connecting...");
		if (ds == null) {
			Hashtable<String, Object> env = new Hashtable<String, Object>(11);
			env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
			env.put(Context.PROVIDER_URL, "ldap://localhost:389");
			env.put(Context.SECURITY_AUTHENTICATION, "simple");
			env.put(Context.SECURITY_PRINCIPAL, "cn=Manager,dc=ibm,dc=com");
			env.put(Context.SECURITY_CREDENTIALS, "secret");

			ds = new InitialDirContext(env);
			// ds = (DirContext) initial.lookup("ldap://localhost:389");
		}
		System.out.println("connected.");
	}

	@Override
	public void close() throws NamingException {
		System.out.println("closing...");
		ds.close();
		System.out.println("closed.");
	}

}
相關文章
相關標籤/搜索