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

📄 usermanager.java

📁 实现了Jms的服务器源码,支持多种适配器,DB,FTP,支持多种数据库
💻 JAVA
字号:
/**
 * Redistribution and use of this software and associated documentation
 * ("Software"), with or without modification, are permitted provided
 * that the following conditions are met:
 *
 * 1. Redistributions of source code must retain copyright
 *    statements and notices.  Redistributions must also contain a
 *    copy of this document.
 *
 * 2. Redistributions in binary form must reproduce the
 *    above copyright notice, this list of conditions and the
 *    following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. The name "Exolab" must not be used to endorse or promote
 *    products derived from this Software without prior written
 *    permission of Exoffice Technologies.  For written permission,
 *    please contact info@exolab.org.
 *
 * 4. Products derived from this Software may not be called "Exolab"
 *    nor may "Exolab" appear in their names without prior written
 *    permission of Exoffice Technologies. Exolab is a registered
 *    trademark of Exoffice Technologies.
 *
 * 5. Due credit should be given to the Exolab Project
 *    (http://www.exolab.org/).
 *
 * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Copyright 2003 (C) Exoffice Technologies Inc. All Rights Reserved.
 *
 **/
package org.exolab.jms.authentication;

import java.sql.Connection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;

import javax.transaction.TransactionManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.exolab.core.service.ServiceException;
import org.exolab.jms.config.Configuration;
import org.exolab.jms.config.ConfigurationManager;
import org.exolab.jms.config.SecurityConfiguration;
import org.exolab.jms.persistence.DatabaseService;
import org.exolab.jms.persistence.PersistenceAdapter;
import org.exolab.jms.persistence.SQLHelper;


/**
 * The user manager is responsible for creating and managing users.
 *
 * @version     $Revision: 1.3 $ $Date: 2003/08/07 13:32:49 $
 * @author      <a href="mailto:knut@lerpold.no">Knut Lerpold</a>
 */
public class UserManager {

    /**
     * A list of all users are maintained
     * in this data structure.
     */
    private HashMap _userCache = new HashMap();

    /**
     * The logger
     */
    private static final Log _log = LogFactory.getLog(UserManager.class);


    /**
     * Construct a new <code>UserManager</code>
     *
     * @throws ServiceException if the service cannot be initialised
     */
    protected UserManager() throws ServiceException {
        init();
    }

    /**
     * Create a new user
     *
     * @param user the userobject containing username and password
     * @return <code>true</code> if the user is created
     * otherwise <code>false</code>
     */
    public synchronized boolean createUser(User user) {
        boolean success = false;
        PersistenceAdapter adapter = DatabaseService.getAdapter();

        if (_userCache.get(user.getUsername()) == null) {
            Connection connection = null;
            try {
                connection = DatabaseService.getConnection();
                adapter.addUser(connection, user);
                addToUserCache(user);
                connection.commit();
                success = true;
            } catch (Exception exception) {
                _log.error("Failed to create user", exception);
                SQLHelper.rollback(connection);
            } finally {
                SQLHelper.close(connection);
            }
        }

        return success;
    }

    /**
     * Update user.
     * Only possible update is password.
     *
     * @param user the userobject containing the username
     * @return <code>true</code> if password is updated
     * otherwise <code>false</code>
     */
    public synchronized boolean updateUser(User user) {
        boolean success = false;
        PersistenceAdapter adapter = DatabaseService.getAdapter();

        if (_userCache.get(user.getUsername()) != null) {
            Connection connection = null;
            try {
                connection = DatabaseService.getConnection();
                adapter.updateUser(connection, user);
                connection.commit();
                addToUserCache(user);
                success = true;
            } catch (Exception exception) {
                _log.error("Failed to update user", exception);
                SQLHelper.rollback(connection);
            } finally {
                SQLHelper.close(connection);
            }
        }

        return success;
    }

    /**
     * Delete a users
     *
     * @param user the userobject containing the username
     * @return <code>true</code> if the is removed
     * otherwise <code>false</code>
     */
    public synchronized boolean deleteUser(User user) {
        boolean success = false;
        PersistenceAdapter adapter = DatabaseService.getAdapter();

        if (_userCache.get(user.getUsername()) != null) {
            Connection connection = null;
            try {
                connection = DatabaseService.getConnection();
                adapter.removeUser(connection, user);
                removeFromUserCache(user);
                success = true;
                connection.commit();
            } catch (Exception exception) {
                _log.error("Failed to remove user", exception);
                SQLHelper.rollback(connection);
            } finally {
                SQLHelper.close(connection);
            }
        }
        return success;
    }

    /**
     * Return a user
     *
     * @param user the userobject containing the username
     * @return a User
     */
    public synchronized User getUser(User user) {
        return (User) _userCache.get(user.getUsername());
    }

    /**
     * Return a list of user names currently supported by the user
     * manager. This includes all types of users.
     *
     * @return an enumeration of the user names
     */
    public Iterator userNames() {
        return _userCache.keySet().iterator();
    }

    /**
     * Destroy this manager. This is brutal and final
     */
    public synchronized void destroy() {
        _userCache.clear();
        _userCache = null;
    }

    /**
     * Determines if a user's name and password are valid
     *
     * @param username the user's name
     * @param password the user's password
     * @return <code>true</code> if the name and password are valid,
     * otherwise <code>false</code>
     */
    public synchronized boolean validateUser(String username,
                                             String password) {
        boolean result = false;

        SecurityConfiguration config =
            ConfigurationManager.getConfig().getSecurityConfiguration();
        if (!config.getSecurityEnabled()) {
            // security disabled
            result = true;
        }

        User user = (User) _userCache.get(username);
        if (user != null && user.getPassword().equals(password)) {
            result = true;
        }

        return result;
    }

    /**
     * Initialise user manager.
     *
     * @throws ServiceException if the user manager cannot be initialised
     */
    protected void init() throws ServiceException {
        Connection connection = null;
        TransactionManager tm = null;
        try {
            connection = DatabaseService.getConnection();

            Enumeration iter =
                DatabaseService.getAdapter().getAllUsers(connection);
            connection.commit();

            while (iter.hasMoreElements()) {
                // add each user to the cache
                User user = (User) iter.nextElement();
                addToUserCache(user);
            }
        } catch (Exception exception) {
            SQLHelper.rollback(connection);
            _log.error("Failed to initialise UserManager", exception);
            throw new ServiceException(exception);
        } finally {
            SQLHelper.close(connection);
        }

        registerConfiguredUsers();
    }

    /**
     * Add the specified entry to the user cache, if it doesn't
     * already exist.
     *
     * @param user - user to add
     */
    protected void addToUserCache(User user) {
        if (!_userCache.containsKey(user.getUsername())) {
            _userCache.put(user.getUsername(), user);
        }
    }

    /**
     * Remove the specified user from the cache
     *
     * @param user the user to remove
     */
    protected void removeFromUserCache(User user) {
        _userCache.remove(user.getUsername());
    }

    /**
     * Registers users specified in the configuration
     */
    protected void registerConfiguredUsers() {
        Configuration config = ConfigurationManager.getConfig();
        if (config.getUsers() != null) {
            org.exolab.jms.config.User[] users = config.getUsers().getUser();
            for (int i = 0; i < users.length; ++i) {
                User user = new User(users[i].getName(),
                    users[i].getPassword());
                createUser(user);
            }
        }
    }

}

⌨️ 快捷键说明

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