/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestLDAP;
/**
*
* @author max
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import TestLDAP.Bean.User;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapName;
/**
*
* @author max
*/
public class work {
private DirContext ctx = null;
private static Map<String,User> UserMap = new HashMap<String,User>(); //键是cn,值是BEAN:user
//初始连接
public boolean ConnectLdap()
{
Properties p = new Properties();
p.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
p.setProperty(Context.PROVIDER_URL, "ldap://localhost/dc=gwd,c=cn");
p.setProperty(Context.SECURITY_PRINCIPAL, "cn=Root,dc=gwd,c=cn");
p.setProperty(Context.SECURITY_CREDENTIALS, "public");
p.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
try {
ctx = new InitialDirContext(p);
System.out.println("认证成功");
return true;
} catch (NamingException ex) {
System.out.println("认证失败");
return false;
}
}
//初始化Bean
public void initBean()
{
String baseDN = "ou=user directory";
String filter = "(&(cn=*))";
try {
Name baseName = new LdapName(baseDN);
SearchControls cons = new SearchControls();
cons.setSearchScope(SearchControls.ONELEVEL_SCOPE);
NamingEnumeration<SearchResult> ne =ctx.search(baseName,filter,cons);
while(ne.hasMore())
{
SearchResult entry = ne.next();
Attributes attrs = entry.getAttributes();
User user = new User(attrs.get("cn").get().toString(),"user directory");
user.setBandWidth(attrs.get("BandWidth").get().toString());
user.setIslegal(attrs.get("Islegal").get().toString());
user.setMac(attrs.get("mac").get().toString());
user.setVodWb(attrs.get("VodWb").get().toString());
UserMap.put(user.getCn(), user);
}
} catch (InvalidNameException ex) {
Logger.getLogger(work.class.getName()).log(Level.SEVERE, null, ex);
} catch (NamingException ex) {
Logger.getLogger(work.class.getName()).log(Level.SEVERE, null, ex);
}
}
//查询信息
public void SearchLDAPByAttr(Attributes matchingAttributes) //只能查找下一级,只用ONELEVEL
{
String baseDN = "ou=user directory";
try {
Name baseName = new LdapName(baseDN);
NamingEnumeration<SearchResult> ne = ctx.search(baseName, matchingAttributes);
for(;ne.hasMore();)
{
SearchResult entry = null;
entry = ne.next();
showAttrEntry(entry);
}
} catch (InvalidNameException ex) {
Logger.getLogger(work.class.getName()).log(Level.SEVERE, null, ex);
} catch (NamingException ex) {
Logger.getLogger(work.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void searchByFilter(String filter){
String baseDN = "ou=user directory";
SearchControls cons = new SearchControls();
cons.setSearchScope(SearchControls.SUBTREE_SCOPE);
try {
NamingEnumeration<SearchResult> ne = ctx.search(baseDN, filter , cons);
for(;ne.hasMore();){ //有多少条目,就有多少个属性集
SearchResult entry = null;
entry = ne.next();
System.out.println(entry.getNameInNamespace());
System.out.println(entry.getClass());
Attributes attrs = entry.getAttributes();
NamingEnumeration<Attribute> nea = (NamingEnumeration<Attribute>) attrs.getAll();//有多少属性
while(nea.hasMore())
{
Attribute att = nea.next();
for(int i =0;i < att.size();i++) //多值属性
System.out.println(att.getID()+":"+att.get(i));
}
//showFilterEntry(entry.getName()+",ou=User directory");
}
} catch (NamingException e) {
e.printStackTrace();
}
}
private void showAttrEntry(SearchResult entry) {
//System.out.println(entry.getName());
Attributes attrs = entry.getAttributes();
Attribute attr = attrs.get("cn");
try {
NamingEnumeration<String> nes = attrs.getIDs();
while (nes.hasMore()) {
System.out.println(attrs.get(nes.next()));
}
} catch (NamingException ex) {
Logger.getLogger(work.class.getName()).log(Level.SEVERE, null, ex);
}
// try {
// NamingEnumeration<Attribute> nea = (NamingEnumeration<Attribute>) attrs.getAll();
// while(nea.hasMore())
// {
// System.out.println(nea.next().get());
// }
// } catch (NamingException ex) {
// Logger.getLogger(work.class.getName()).log(Level.SEVERE, null, ex);
// }
// NamingEnumeration<String> ne = attrs.getIDs();
// try {
// while (ne.hasMore()) {
// Attribute att = attrs.get(ne.next());
// System.out.println(att.getID()+":"+att.get());
// }
// } catch (NamingException ex) {
// Logger.getLogger(work.class.getName()).log(Level.SEVERE, null, ex);
// }
}
//添加一条信息
//读取一条信息
private void showFilterEntry(String entry) {
find(entry);
}
public void find(String entryDN){
try {
Attributes attrs = ctx.getAttributes(entryDN);
if (attrs != null) {
NamingEnumeration<String> nEnum = attrs.getIDs();
for( ; nEnum.hasMore() ; ){
String attrID = nEnum.next();
Attribute attr = (Attribute)attrs.get(attrID);
System.out.println(attr.toString());
}
System.out.println();
}else{
System.out.println("No found binding.");
}
}catch(NamingException ne) {
ne.printStackTrace();
}
}
public void modifyUser(User user)
{
if(user == null)
return ;
String baseDN = user.getDistinguishedName();
// String baseName = "cn="+user.getCn()+",ou="+user.getParentName();
if(baseDN == null||baseDN.length() == 0)
try {
throw new NamingException("No userDN you specify!n");
} catch (NamingException ex) {
Logger.getLogger(work.class.getName()).log(Level.SEVERE, null, ex);
}
if(!isUserexist(user))
{
return ;
}
Attributes attrs = new BasicAttributes();
Attribute attr = new BasicAttribute("cn",user.getCn());
attrs.put(attr);
attr = new BasicAttribute("Islegal",user.getIslegal());
attrs.put(attr);
attr = new BasicAttribute("VodWb",user.getVodWb());
attrs.put(attr);
attr = new BasicAttribute("mac",user.getMac());
attrs.put(attr);
attr = new BasicAttribute("BandWidth",user.getBandWidth());
attrs.put(attr);
try {
ctx.modifyAttributes(baseDN, DirContext.REPLACE_ATTRIBUTE, attrs);
System.out.println("succeed");
} catch (NamingException ex) {
Logger.getLogger(work.class.getName()).log(Level.SEVERE, null, ex);
}
}
public boolean isUserexist(User user)
{
if(user == null)
return false;
String DN = user.getDistinguishedName();
if(DN == null||DN.length() == 0)
return false;
if(UserMap.containsKey(user.getCn()))
return true;
System.out.println("user is not exist");
return false;
// String cn = user.getCn();
// String filter = "(&(cn="+cn+"))";
//
// String baseDN = "ou="+user.getParentName(); //RDN
//
// SearchControls cons = new SearchControls();
// cons.setSearchScope(SearchControls.ONELEVEL_SCOPE);
//
// try {
// NamingEnumeration<SearchResult> ne = ctx.search(baseDN, filter, cons);
// if(ne.hasMore())
// return true;
// return false;
// } catch (NamingException ex) {
// Logger.getLogger(work.class.getName()).log(Level.SEVERE, null, ex);
// }
// return false;
}
public void createUser(User user)
{
Attributes attrs = new BasicAttributes();
Attribute attr = new BasicAttribute("cn",user.getCn());
attrs.put(attr);
attr = new BasicAttribute("Islegal",user.getIslegal());
attrs.put(attr);
attr = new BasicAttribute("VodWb",user.getVodWb());
attrs.put(attr);
attr = new BasicAttribute("mac",user.getMac());
attrs.put(attr);
attr = new BasicAttribute("BandWidth",user.getBandWidth());
attrs.put(attr);
attr = new BasicAttribute("objectClass",user.getObjectClass());
attrs.put(attr);
try {
ctx.bind(user.getDistinguishedName(),null, attrs);
} catch (NamingException ex) {
Logger.getLogger(work.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args)
{
work m = new work();
m.ConnectLdap();
m.initBean();
//新建
User user4 = new User("user4","user directory");
user4.setBandWidth("1.5");
user4.setIslegal("0");
user4.setMac("12 34 56 78 90 12");
user4.setVodWb("Wb");
m.createUser(user4);
//修改
User user1 = UserMap.get("user1");
if(m.isUserexist(user1))
{
user1.setBandWidth("4.0");
m.modifyUser(user1);
}
//查询
String filter = "(&(objectClass=top)(mac=FF FF FF FF FF FF))";
m.searchByFilter(filter);
Attribute mac = new BasicAttribute("mac","EE EE EE EE EE EE");
Attributes attrs = new BasicAttributes();
attrs.put(mac);
m.SearchLDAPByAttr(attrs);
}
}
(1)schema为:
attributetype ( 1.3.6.1.4.1.10072.2.20.1.1
NAME 'mac'
EQUALITY caseIgnoreMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 )
attributetype ( 1.3.6.1.4.1.10072.2.20.1.2
NAME 'Islegal'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 )
attributetype ( 1.3.6.1.4.1.10072.2.20.1.3
NAME 'VodWb'
EQUALITY caseIgnoreMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 )
attributetype ( 1.3.6.1.4.1.10072.2.20.1.4
NAME 'BandWidth'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 )
objectclass ( 1.3.6.1.4.1.10072.2.20.1.5
NAME 'max'
SUP organizationalRole
STRUCTURAL
MUST (
mac $ Islegal $ VodWb $ BandWidth )
)
(2)LDIF为
dn:dc=gwd,c=cn
objectClass:dcObject
objectClass:organization
o:GW
dc:gwd
dn:ou=user directory,dc=gwd,c=cn
objectClass:top
objectClass:organizationalUnit
ou:user directory
dn:cn=user1,ou=user directory,dc=gwd,c=cn
objectClass:max
cn:user1
mac: FF FF FF FF FF FF
Islegal:1
Vodwb:Vod
BandWidth:1.5
dn:cn=user2,ou=user directory,dc=gwd,c=cn
objectClass:max
cn:user2
mac: EE EE EE EE EE EE
Islegal:0
Vodwb:wb
BandWidth:1.0
dn:cn=user3,ou=user directory,dc=gwd,c=cn
objectClass:max
cn:user3
mac: DD DD DD DD DD DD
Islegal:1
Vodwb:Vod
BandWidth:2.0
下面分别是OpenLDAP 和LDAP浏览器