⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 usersldaprepository.java

📁 java 开发的邮件服务器平台。支持以下协议。 协议可以修改为自己的专门标识
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*********************************************************************** * Copyright (c) 2000-2004 The Apache Software Foundation.             * * All rights reserved.                                                * * ------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); you * * may not use this file except in compliance with the License. You    * * may obtain a copy of the License at:                                * *                                                                     * *     http://www.apache.org/licenses/LICENSE-2.0                      * *                                                                     * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS,   * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or     * * implied.  See the License for the specific language governing       * * permissions and limitations under the License.                      * ***********************************************************************/package org.apache.james.userrepository;import org.apache.avalon.framework.activity.Initializable;import org.apache.avalon.framework.component.ComponentManager;import org.apache.avalon.framework.component.Composable;import org.apache.avalon.framework.configuration.Configurable;import org.apache.avalon.framework.configuration.Configuration;import org.apache.avalon.framework.configuration.ConfigurationException;import org.apache.avalon.framework.context.Context;import org.apache.avalon.framework.context.ContextException;import org.apache.avalon.framework.context.Contextualizable;import org.apache.avalon.framework.logger.AbstractLogEnabled;import org.apache.avalon.framework.logger.LogEnabled;import org.apache.avalon.framework.logger.Logger;import org.apache.james.Constants;import org.apache.james.services.User;import org.apache.james.services.UsersRepository;import javax.naming.AuthenticationException;import javax.naming.NamingEnumeration;import javax.naming.NamingException;import javax.naming.directory.*;import java.util.*;/** * Implementation of a Repository to store users. * * This clas is a dummy for the proposal! * * @version This is $Revision: 1.9.4.5 $ */public class UsersLDAPRepository    extends AbstractLogEnabled    implements UsersRepository, Composable, Configurable, Contextualizable, Initializable{    private ComponentManager comp;    private Logger logger;    private String path;    private String name;    private String destination;    private String type;    private String model;    private DirContext ctx;    private String LDAPHost;    private String rootNodeDN;    private String rootURL;    private String serverRDN;    private String baseNodeDN;    private String baseURL;    private String mailAddressAttr;    private String identAttr;    private String authType;    private String principal;    private String password;    private String usersDomain;    private String membersAttr;    private boolean manageGroupAttr;    private String groupAttr;    private boolean managePasswordAttr;    private String passwordAttr;    /**     * @see org.apache.avalon.framework.context.Contextualizable#contextualize(Context)     */    public void contextualize(Context context)        throws ContextException {        Collection serverNames            = (Collection)context.get(Constants.SERVER_NAMES);        usersDomain = (String)serverNames.iterator().next();    }    /**     * @see org.apache.avalon.framework.component.Composable#compose(ComponentManager)     */    public void compose(ComponentManager compMgr) {        this.comp = compMgr;    }    /**     * @see org.apache.avalon.framework.configuration.Configurable#configure(Configuration)     */    public void configure(Configuration conf)        throws ConfigurationException {        LDAPHost = conf.getChild("LDAPServer").getValue();        rootNodeDN = conf.getChild("LDAPRoot").getValue();        serverRDN = conf.getChild("ThisServerRDN").getValue();        mailAddressAttr            = conf.getChild("MailAddressAttribute").getValue();        identAttr = conf.getChild("IdentityAttribute").getValue();        authType = conf.getChild("AuthenticationType").getValue();        principal = conf.getChild("Principal").getValue();        password = conf.getChild("Password").getValue();        membersAttr = conf.getChild("MembersAttribute").getValue();        manageGroupAttr            = conf.getChild("ManageGroupAttribute").getValueAsBoolean( false );        groupAttr = conf.getChild("GroupAttribute").getValue();        managePasswordAttr = conf.getChild("ManagePasswordAttribute").getValueAsBoolean( false );        passwordAttr = conf.getChild("PasswordAttribute").getValue();    }    public void setServerRoot() {        StringBuffer serverRootBuffer =            new StringBuffer(128)                    .append(serverRDN)                    .append(", ")                    .append(rootNodeDN);        this.setBase(serverRootBuffer.toString());    }    public void setBase(String base) {        baseNodeDN = base;    }    /**     * @see org.apache.avalon.framework.activity.Initializable#initialize()     */    public void initialize() throws Exception {        //setServerRoot();        StringBuffer urlBuffer =            new StringBuffer(128)                    .append(LDAPHost)                    .append("/");        rootURL = urlBuffer.toString() + rootNodeDN;        baseURL = urlBuffer.toString() + baseNodeDN;        getLogger().info("Creating initial context from " + baseURL);        //System.out.println("Creating initial context from " + baseURL);        Hashtable env = new Hashtable();        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,                "com.sun.jndi.ldap.LdapCtxFactory");        env.put(javax.naming.Context.PROVIDER_URL, baseURL);        try {            ctx = new InitialDirContext(env); // Could throw a NamingExcpetion        } catch (Exception e) {            getLogger().error("Exception creating InitialDirContext: ", e);        }        getLogger().info("Initial context initialized from " + baseURL);    }    public String getChildDestination(String childName) {        String destination = null;        String filter = "cn=" + childName;        SearchControls ctls = new SearchControls();        try {            NamingEnumeration result  = ctx.search("", filter, ctls);            if (result.hasMore()) {                StringBuffer destinationBuffer =                    new StringBuffer(128)                            .append("cn=")                            .append(childName)                            .append(", ")                            .append(baseNodeDN);                destination = destinationBuffer.toString();                getLogger().info("Pre-exisisting LDAP node: " + destination);            } else {                Attributes attrs = new BasicAttributes(true);                Attribute objclass = new BasicAttribute("objectclass");                objclass.add("top");                objclass.add("rfc822MailGroup");                attrs.put(objclass);                Attribute cname = new BasicAttribute("cn");                cname.add(childName);                attrs.put(cname);                Attribute owner = new BasicAttribute("owner");                owner.add("JAMES-unassigned");                attrs.put(owner);                ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, authType);                ctx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, principal);                ctx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, password);                ctx.createSubcontext("cn=" + childName, attrs);                ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, "none");                StringBuffer destinationBuffer =                    new StringBuffer(128)                            .append("cn=")                            .append(childName)                            .append(", ")                            .append(baseNodeDN);                destination = destinationBuffer.toString();                getLogger().info("Created new LDAP node: " + destination);            }        } catch (NamingException e) {            getLogger().error("Problem with child nodes " + e.getMessage(), e);        }        return destination;    }    /**     * List users in repository.     *     * @return Iterator over a collection of Strings, each being one user in the repository.     */    public Iterator list() {        List result = new ArrayList();        String filter = mailAddressAttr + "=*";        String[] attrIDs = {membersAttr};        try {            Attribute members                = ctx.getAttributes("", attrIDs).get(membersAttr);            if (members != null) {                NamingEnumeration enum = members.getAll();                while (enum.hasMore()) {                    result.add((String)enum.next());                }            }        } catch (NamingException e) {            getLogger().error("Problem listing mailboxes. " + e );        }        return result.iterator();    }    // Methods from interface UsersRepository --------------------------    /**     * Update the repository with the specified user object.  Unsupported for     * this user repository type.     *     * @return false     */    public boolean addUser(User user) {        return false;    }    public  User getUserByName(String name) {        return new DefaultUser("dummy", "dummy");    }    public User getUserByNameCaseInsensitive(String name) {        return getUserByName(name);    }    public boolean containsCaseInsensitive(String name) {        return contains(name);    }    // TODO: This is in violation of the contract for the interface.    //       Should only return null if the user doesn't exist.  Otherwise    //       this should return a consistent string representation of the name    public String getRealName(String name) {        return null;    }    public boolean updateUser(User user) {        return false;    }    public boolean test(String name, String password) {        return false;    }    /**     * Adds userName to the MemberAttribute (specified in conf.xml) of this     * node.     * If ManageGroupAttribute (conf.xml) is TRUE then calls addGroupToUser.     */    public synchronized void addUser(String userName, Object attributes) {        String[] attrIDs = {membersAttr};        // First, add username to mailGroup at baseNode        try {            Attribute members = ctx.getAttributes("", attrIDs).get(membersAttr);            if (members != null && members.contains(userName)) {//user already here                StringBuffer infoBuffer =                    new StringBuffer(64)                            .append("Found ")                            .append(userName)                            .append(" already in mailGroup. ");                getLogger().info(infoBuffer.toString());                //System.out.println(infoBuffer.toString());            } else {                ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, authType);                ctx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, principal);                ctx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, password);                ModificationItem[] mods = new ModificationItem[1];                mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(membersAttr, userName));                ctx.modifyAttributes("", mods);                ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, "none");                StringBuffer infoBuffer =                    new StringBuffer(128)                            .append(userName)                            .append(" added to mailGroup ")                            .append(baseNodeDN);                getLogger().info(infoBuffer.toString());                //System.out.println(infoBuffer.toString());            }        } catch (NamingException e) {            StringBuffer exceptionBuffer =                new StringBuffer(256)                        .append("Problem adding user ")                        .append(userName)                        .append(" to: ")                        .append(baseNodeDN)                        .append(e);            getLogger().error(exceptionBuffer.toString());        }        // Add attributes to user objects, if necessary        if (manageGroupAttr) {            addGroupToUser(userName);        }        if (managePasswordAttr) {            String userPassword = (String) attributes; // Not yet implemented        }    }    private void addGroupToUser(String userName) {        String[] attrIDs = {membersAttr};        Hashtable env = new Hashtable();        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");        env.put(javax.naming.Context.PROVIDER_URL, rootURL);        DirContext rootCtx = null;        try {            rootCtx = new InitialDirContext(env);            String[] returnAttrs = {groupAttr};            SearchControls ctls = new SearchControls();            ctls.setReturningAttributes(attrIDs);            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);            StringBuffer filterBuffer =                new StringBuffer(128)                        .append(mailAddressAttr)                        .append("=")                        .append(userName)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -