ITPub博客

首页 > Linux操作系统 > Linux操作系统 > [转贴]一个LDAP应用的例子,在Sun ONE Directory Server 5.2

[转贴]一个LDAP应用的例子,在Sun ONE Directory Server 5.2

原创 Linux操作系统 作者:haishi633 时间:2009-08-13 12:53:10 0 删除 编辑

先说一下环境Win2000AdvancedServer + Sun ONE Directory Server 5.2 + JDK1.4.2
Directory Server, 和JDK可以到Sun的网站上去下载。
Directory Server的安装:
首先用鼠标右键单击我的电脑->属性->网络标识->属性
这里可以看到计算机名,我的计算机名为acer。
点击其他,将此计算机的主DNS后缀栏为输入com然后点击确定。
这是可以看到完整的计算机名称:acer.com。接下来重新启动计算机。
启动完成后就可以安装Directory Server了。

以下是安装过程中我的Directory Server的一些配置。
Fully Qualified Computer Name: acer.com

Server Identifier: acer
Server Port: 64150
Suffix: dc=com

admin id: admin
admin pwd: admin

Administration Domain: com

Directory Manager Settings:
Directory Manager DN: cn=Directory Manager
pwd: manager
Administration Port: 64151

到此完成了基本的配置。
 程序1


从管理界面打开Directory Server的Directory当要创建用户时你会发现有这样几个属性:
必选属性:First Name,Last Name,Common Name(s)
可选属性:User ID,Password,E-Mail,Phone,Fax。
我主要根据这些属性来编写。

//LDAPTest.java

import java.util.*;

import javax.naming.*;
import javax.naming.directory.*;

public final class LDAPTest {

        private DirContext ctx;
        private Hashtable env;
       
        //服务器地址
        private static final String LDAP_URL =
                "ldap://localhost:64150";
        //管理域的dn
        private static final String MANAGER_DN =
                "cn=Directory Manager";
        //管理域的密码
        private static final String MANAGER_PASSWORD =
                "manager";
        //管理域的验证方式
        private static final String AUTH_TYPE =
                "simple";
        //
        private static final String CONTEXT_FACTORY =
                "com.sun.jndi.ldap.LdapCtxFactory";
        //用于测试的用户组的DN
        private static final String BASE_DN =
                "cn=student,ou=People,dc=com";
       
        //构造函数用于初始化ldap连接和创建用于测试的用户组
        public LDAPTest()
        throws NamingException {
                setEnvironment();
                ctx = new InitialDirContext(env);
                createGroup();
        }
       
        //设置登录到LDAP服务器的信息
        private void setEnvironment() {
                env = new Hashtable();
                env.put(Context.INITIAL_CONTEXT_FACTORY,
                        CONTEXT_FACTORY);
                env.put(Context.PROVIDER_URL,
                        LDAP_URL);
                env.put(Context.SECURITY_AUTHENTICATION,
                        AUTH_TYPE);
                env.put(Context.SECURITY_PRINCIPAL,
                        MANAGER_DN);
                env.put(Context.SECURITY_CREDENTIALS,
                        MANAGER_PASSWORD);
        }
       
        //创建一个用于测试的用户组(当用户组不存在时创建)
        private void createGroup()
        throws NamingException {
                try {
                        Attributes attr = ctx.getAttributes(BASE_DN);
                } catch (NamingException ne) {
                        Attribute bjclass = new BasicAttribute("objectclass");
                        objclass.add("top");
                        objclass.add("groupofuniquenames");

                        Attribute cn = new BasicAttribute("cn", "student");

                        Attributes attrs = new BasicAttributes();
                        attrs.put(objclass);
                        attrs.put(cn);
       
                        ctx.bind(BASE_DN, null, attrs);
                        System.out.println("Group created.n");
                }
        }
       
        //关闭到LDAP服务器的连接
        private void closeConnection() {
                try {
                        ctx.close();
                } catch (NamingException ne) {
                        System.out.println(ne);
                }
        }
       
        //验证用户是否存在
        private boolean isUserexist(String uid) {
                try {
                        Attributes attrs = findUser(uid);
                        if (attrs != null) { return true; }
                        else { return false; }
                } catch (NamingException ne) {
                        return false;
                }
        }
       
        //设置属性
        private void putAttribute(Attributes attrs,
                String attrName, String attrValue) {
                if (attrValue != null && attrValue.length() != 0) {
                        Attribute attr =
                                new BasicAttribute(attrName, attrValue);
                        attrs.put(attr);
                }
        }
       
        //得到属性
        private String getAttribute(
                Attributes attrs, String attrName)
        throws NamingException {
                Attribute attr = attrs.get(attrName);
                if (attr == null) { return ""; }
                else { return (String)attr.get(); }
        }
       
        //查找用户
        private Attributes findUser(String uid)
        throws NamingException {
                return ctx.getAttributes("uid=" + uid + "," + BASE_DN);
        }
       
        //创建用户
        public void createUser(UserInformationObject userobj)
        throws NamingException {
                //用户对象为空
                if (userobj == null) {
                        throw new NamingException("No user informationn");
                }
               
                //检查uid
                String uid = userobj.
                        getProperty(UserInformationObject.USER_ID);
                if (uid == null && uid.length() == 0) {
                        throw new NamingException("No uid you specifyn");
                }
                if (isUserexist(uid)) {
                        throw new NamingException("The user(uid: " + uid +
                                ") is exist!n");
                }
               
                //检查firstName
                String firstName = userobj.
                        getProperty(UserInformationObject.FIRST_NAME);
                if (firstName == null || firstName.length() == 0) {
                        throw new NamingException("No first name you specify!n");
                }
               
                //检查lastName
                String lastName = userobj.
                        getProperty(UserInformationObject.LAST_NAME);
                if (lastName == null || lastName.length() == 0) {
                        throw new NamingException("No last name you specify!n");
                }
               
                //检查commonName
                String commonName = userobj.
                        getProperty(UserInformationObject.COMMON_NAME);
                if (commonName == null || commonName.length() == 0) {
                        throw new NamingException("No common name you specify!n");
                }
               
                String password = userobj.
                        getProperty(UserInformationObject.PASSWORD);
                String email = userobj.
                        getProperty(UserInformationObject.EMAIL);
                String phone = userobj.
                        getProperty(UserInformationObject.PHONE);
                String fax = userobj.
                        getProperty(UserInformationObject.FAX);
               
                Attributes attrs = new BasicAttributes();
               
                //设置属性
                Attribute bjclass = new BasicAttribute("objectclass");
                objclass.add("top");
                objclass.add("person");
                objclass.add("organizationalPerson");
                objclass.add("inetorgperson");
                attrs.put(objclass);
               
                putAttribute(attrs, "cn", commonName);
                putAttribute(attrs, "givenname", firstName);
                putAttribute(attrs, "sn", lastName);
                putAttribute(attrs, "uid", uid);
                putAttribute(attrs, "userpassword", password);
                putAttribute(attrs, "mail", email);
                putAttribute(attrs, "telephonenumber", phone);
                putAttribute(attrs, "facsimiletelephonenumber", fax);
               
                //添加用户节点
                ctx.bind("uid=" + uid + "," + BASE_DN, null, attrs);
               
                System.out.println("User(uid: " + uid + ") created.n");
               
        }
       
        //修改用户信息
        public void modifyUser(UserInformationObject userobj)
        throws NamingException {
                //用户对象为空
                if (userobj == null) {
                        throw new NamingException("No user information!n");
                }
                //检查uid
                String uid = userobj.
                        getProperty(UserInformationObject.USER_ID);
                if (uid == null && uid.length() == 0) {
                        throw new NamingException("No uid you specify!n");
                }
                if (!isUserexist(uid)) {
                        throw new NamingException("The user(uid: " + uid
                                + ") does not exist!n");
                }
               
                int size = userobj.size();   //用户属性的个数
               
                //如果属性个数只有一个,那么只设置了uid,不用修改用户属性
                if (size > 1) { 
                        String password = userobj.
                                getProperty(UserInformationObject.PASSWORD);
                        String email = userobj.
                                getProperty(UserInformationObject.EMAIL);
                        String phone = userobj.
                                getProperty(UserInformationObject.PHONE);
                        String fax = userobj.
                                getProperty(UserInformationObject.FAX);
                        String commonName = userobj.
                                getProperty(UserInformationObject.COMMON_NAME);
                        String firstName = userobj.
                                getProperty(UserInformationObject.FIRST_NAME);
                        String lastName = userobj.
                                getProperty(UserInformationObject.LAST_NAME);
                       
                        //设置属性
                        Attributes attrs = new BasicAttributes();
                        putAttribute(attrs, "cn", commonName);
                        putAttribute(attrs, "givenname", firstName);
                        putAttribute(attrs, "sn", lastName);
                        putAttribute(attrs, "userpassword", password);
                        putAttribute(attrs, "mail", email);
                        putAttribute(attrs, "telephonenumber", phone);
                        putAttribute(attrs, "facsimiletelephonenumber", fax);
                       
                        //修改属性
                        ctx.modifyAttributes("uid=" + uid + "," + BASE_DN,
                                DirContext.REPLACE_ATTRIBUTE, attrs);

                        System.out.println("User(uid: " + uid +
                                ") information modified.n");
                } else {
                        throw new NamingException(
                                "No modify information you specify!n");
                }
        }
       
        //删除用户
        public void deleteUser(String uid)
        throws NamingException {
                if (!isUserexist(uid)) {
                        throw new NamingException("The user(uid: " + uid +
                                ") does not exist!n");
                }
                ctx.destroySubcontext(
                        "uid=" + uid + "," + BASE_DN);
                System.out.println("User(uid: " + uid + ") deleted.n");
        }
       
        //根据提供的uid察看用户的信息
        public void selectUser(String uid)
        throws NamingException {
                Attributes attrs;
                System.out.println("select user(uid: " + uid + ")...");
                try {
                        attrs = findUser(uid);
                        System.out.println("-----------------------------");
                        System.out.println("User(uid: " + uid + ") listing...");
                       
                        System.out.println("First Name: " +
                                getAttribute(attrs, "givenname"));
                        System.out.println("Last Name: " +
                                getAttribute(attrs, "sn"));
                        System.out.println("Common Name: " +
                                getAttribute(attrs, "cn"));
                        System.out.println("User ID: " +
                                getAttribute(attrs, "uid"));
                        System.out.println("E-Mail: " +
                                getAttribute(attrs, "mail"));
                        System.out.println("Phone: " +
                                getAttribute(attrs, "telephonenumber"));
                        System.out.println("Fax: " +
                                getAttribute(attrs, "facsimiletelephonenumber"));
                        System.out.println("List completed.");
                        System.out.println("-----------------------------n");
                } catch (NamingException ne) {
                        throw new NamingException("The user(uid: " + uid
                                + ") is not exist!n");
                }
        }
       
        //提供一个存有多个用户信息的数组查询多个用户
        public void selectUser(String[] uid) {
                for (int i = 0; i < uid.length; i++) {
                        try {
                                selectUser(uid[i]);
                        } catch (NamingException ne) {
                                System.out.println(ne);
                                continue;
                        }
                }
        }
       
        protected void finalize() {
                closeConnection();
        }
       
}
程序2


用于存放用户属性的类
//UserInformationObject.java


import java.util.Properties;

public final class UserInformationObject {
       
        public static final String FIRST_NAME = "1";
        public static final String LAST_NAME = "2";
        public static final String COMMON_NAME = "3";
        public static final String USER_ID = "4";
        public static final String PASSWORD = "5";
        public static final String EMAIL = "6";
        public static final String PHONE = "7";
        public static final String FAX = "8";
       
        private Properties props;
       
        //防止使用默认的构造函数
        private UserInformationObject() {
               
        }
       
        //用于创建用户时使用
        public UserInformationObject(
                String firstName, String lastName,
                        String commonName, String userid) {
                props = new Properties();
                props.setProperty(FIRST_NAME, firstName);
                props.setProperty(LAST_NAME, lastName);
                props.setProperty(COMMON_NAME, commonName);
                props.setProperty(USER_ID, userid);
        }
       
        //用于修改用户信息时使用
        public UserInformationObject(String userid) {
                props = new Properties();
                props.setProperty(USER_ID, userid);
        }
       
        //设置First Name
        public void setFirstname(String firstName) {
                props.setProperty(FIRST_NAME, firstName);
        }
       
        //设置Last Name
        public void setLastname(String lastName) {
                props.setProperty(LAST_NAME, lastName);
        }
       
        //设置Common Name
        public void setCommonname(String commonName) {
                props.setProperty(COMMON_NAME, commonName);
        }
       
        //设置Password
        public void setPassword(String password) {
                props.setProperty(PASSWORD, password);
        }
       
        //设置E-Mail
        public void setEmail(String email) {
                props.setProperty(EMAIL, email);
        }
       
        //设置Phone
        public void setPhone(String phone) {
                props.setProperty(PHONE, phone);
        }
       
        //设置Fax
        public void setFax(String fax) {
                props.setProperty(FAX, fax);
        }
       
        //根据属性名得到属性的值
        public String getProperty(String propertyName) {
                return props.getProperty(propertyName);
        }
       
        //存储属性的个数
        public int size() {
                return props.size();
        }
}

程序3


用于测试的程序

//Test.java

public class Test {
        public static void main(String[] args) {
               
                //初始化用户
                UserInformationObject zhangsan =
                        new UserInformationObject(
                                "zhang", "san", "zhang san", "zhangsan");
                UserInformationObject lisi =
                        new UserInformationObject(
                                "li", "si", "li si", "lisi");
               
                //设置用户属性
                zhangsan.setPassword("abcdef");
                zhangsan.setPhone("02866666666");
                zhangsan.setEmail("zhangsan@163.com");
                zhangsan.setFax("02887654321");
               
                lisi.setPassword("fedcba");
                lisi.setPhone("02888888888");
                lisi.setEmail("lisi@163.com");
                lisi.setFax("02812345678");
               
                try {
                        LDAPTest ldap = new LDAPTest();
                        //创建用户
                        ldap.createUser(zhangsan);
                        ldap.createUser(lisi);
                       
                        String[] user = {"wangwu", "zhangsan", "lisi", "zhaoliu"};
                        //察看用户信息
                        ldap.selectUser(user);
                       
                        zhangsan.setPhone("02811111111");
                        zhangsan.setEmail("ldap@163.com");
                        //修改用户
                        ldap.modifyUser(zhangsan); 
                       
                        //察看用户信息
                        ldap.selectUser("zhangsan");
                       
                        //删除用户
                        ldap.deleteUser("lisi");
                       
                        //察看用户信息
                        ldap.selectUser(user);

                } catch (Exception e) {
                        System.out.println(e);
                }
        }
}
不要忘拉objectClass


初学者容易犯一个错误,就是在增加组,和用户,组织
这些节点信息时容易只增加业务信息
什么意思
也许你增加一个用户
你把workphone,cn(全名),sex,address
都设好拉
可是一执行代码偏偏报告"schemaviolation'的错误
想拉半天,不会啊,也许是requried属性没加于是又加上
那些required属性,可还是报告"schemaviolation'的错误
其实就是objectClass没加
我门用惯拉数据库的增加方式
它那就只用关心实际的业务,不会让你去当心什么yig
objectClass这样一个系统属性
所以学的时候虽然知道有objectClass这个东东
可是一用起来还是用操作数据库的思维在行事
这应该也是一个小小的注意点把
你用的LDAP服务器是Sun ONE Directory Server 5.2吗?检查一下你的环境吧。
我用我们寝室其他的机子将代码粘回来并运行都是正确的(没有用我写的源文件),这些代码是经过了多台机子的测试的。

关于设置objectClass属性在源代码的地方。
这是设置用户的objectClass
//设置属性
Attribute bjclass = new BasicAttribute("objectclass");
objclass.add("top");
objclass.add("person");
objclass.add("organizationalPerson");
objclass.add("inetorgperson");
attrs.put(objclass);

在createGroup()有设置用户组的objectClass相应的代码。
这些应该很好找吧。


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/chong232/archive/2008/04/05/2252625.aspx

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/15232308/viewspace-612123/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2009-04-09

  • 博文量
    3
  • 访问量
    6446