dbusermanager.java

来自「Jive是基于JSP/JAVA技术构架的一个大型BBS论坛系统,这是Jive论坛」· Java 代码 · 共 418 行

JAVA
418
字号
/** * $RCSfile: DbUserManager.java,v $ * $Revision: 1.9 $ * $Date: 2002/06/17 20:59:21 $ * * Copyright (C) 1999-2001 CoolServlets, Inc. All rights reserved. * * This software is the proprietary information of CoolServlets, Inc. * Use is subject to license terms. */package com.jivesoftware.forum.database;import java.util.*;import java.sql.*;import com.jivesoftware.util.*;import com.jivesoftware.forum.*;/** * Database implementation of the UserManager interface. It uses the DbUser * class along with the jiveUser database table to store and manipulate user * information.<p> * * This UserManager implementation uses three global caches to vastly improve speed:<ul> *   <li> userMessageCountCache *   <li> userCache *   <li> userIDCache </ul><p> * * If making your own UserManager implementation, it's highly recommended that * you also use these caches. */public class DbUserManager implements UserManager {    /** DATABASE QUERIES **/    private static final String USER_MESSAGE_COUNT =        "SELECT count(1) FROM jiveMessage WHERE jiveMessage.userID=?";    private static final String USER_COUNT = "SELECT count(1) FROM jiveUser";    private static final String ALL_USER_MESSAGES =        "SELECT messageID FROM jiveMessage WHERE userID=? ORDER BY modifiedDate DESC";    private static final String DELETE_USER_MESSAGES =        "UPDATE jiveMessage set userID=NULL WHERE userID=?";    private static final String DELETE_USER_PERMS =        "DELETE FROM jiveUserPerm WHERE userID=?";    private static final String DELETE_USER_GROUPS =        "DELETE FROM jiveGroupUser WHERE userID=?";    private static final String DELETE_USER_PROPS =        "DELETE FROM jiveUserProp WHERE userID=?";    private static final String DELETE_USER_WATCHES =        "DELETE FROM jiveWatch WHERE userID=?";    private static final String DELETE_USER =        "DELETE FROM jiveUser WHERE userID=?";    private static final String ALL_USERS =        "SELECT userID from jiveUser";    private DbForumFactory factory;    /**     * Creates a new UserManager.     */    public DbUserManager() {        this.factory = DbForumFactory.getInstance();    }    //FROM THE USERMANAGER INTERFACE//    public User createUser(String username, String password, String email)            throws UserAlreadyExistsException    {        User newUser = null;        // Strip extra or invisible characters from the username so that        // existing usernames can't be forged.        username = username.trim();        username = StringUtils.replace(username, "&nbsp;", "");        try {            getUser(username);            //The user already exists since now exception, so:            throw new UserAlreadyExistsException();        }        catch (UserNotFoundException unfe) {            //The user doesn't already exist so we can create a new user            newUser = new DbUser(username, password, email);        }        return newUser;    }    public User createUser(String username, String password, String name,            String email, boolean nameVisible, boolean emailVisible,            Map properties) throws UserAlreadyExistsException    {        User newUser = null;        // Strip extra or invisible characters from the username so that        // existing usernames can't be forged.        username = username.trim();        username = StringUtils.replace(username, "&nbsp;", "");        try {            getUser(username);            //The user already exists since now exception, so:            throw new UserAlreadyExistsException();        }        catch (UserNotFoundException unfe) {            //The user doesn't already exist so we can create a new user            newUser = new DbUser(username, password, name, email,                    nameVisible, emailVisible, properties);        }        return newUser;    }    public User getUser(long userID) throws UserNotFoundException {        if (!factory.cacheManager.isCacheEnabled()) {            return new DbUser(userID);        }        //Cache is enabled.        User user = (User)factory.cacheManager.userCache.get(new Long(userID));        if (user == null) {            user = new DbUser(userID);            factory.cacheManager.userCache.put(new Long(userID), user);        }        return user;    }    public User getUser(String username) throws UserNotFoundException {        if (username == null) {            throw new UserNotFoundException("Username with null value is not valid.");        }        // Do a special check to see if chache is disabled. This will let us        // avoid more db hits than necessary if it is.        if (!factory.cacheManager.isCacheEnabled()) {            return new DbUser(username, factory);        }        // Cache is enabled.        return getUser(getUserID(username));    }    public long getUserID(String username) throws UserNotFoundException {        if (!factory.cacheManager.isCacheEnabled()) {            return new DbUser(username, factory).getID();        }        // Cache is enabled.        Long userIDLong =                (Long)factory.cacheManager.userIDCache.get(username);        // If ID wan't found in cache, load it up and put it there.        if (userIDLong == null) {            User user = new DbUser(username, factory);            userIDLong = new Long(user.getID());            factory.cacheManager.userIDCache.put(username, userIDLong);        }        return userIDLong.longValue();    }    public void deleteUser(User user) throws UnauthorizedException {        long userID = user.getID();        // Get array of all user's messages in the system so that        // we can expire them from cache.        LongList messages = new LongList();        Connection con = null;        PreparedStatement pstmt = null;        try {            con = ConnectionManager.getConnection();            pstmt = con.prepareStatement(ALL_USER_MESSAGES);            pstmt.setLong(1, user.getID());            ResultSet rs = pstmt.executeQuery();            while (rs.next()) {                messages.add(rs.getLong(1));            }        }        catch( SQLException sqle ) {            sqle.printStackTrace();        }        finally {            try {  pstmt.close(); }            catch (Exception e) { e.printStackTrace(); }            try {  con.close();   }            catch (Exception e) { e.printStackTrace(); }        }        con = null;        pstmt = null;        boolean abortTransaction = false;        try {            con = ConnectionManager.getTransactionConnection();            // Mark all message by user as anonymous            pstmt = con.prepareStatement(DELETE_USER_MESSAGES);            pstmt.setLong(1,userID);            pstmt.execute();            pstmt.close();            // Remove all permissions given to user            pstmt = con.prepareStatement(DELETE_USER_PERMS);            pstmt.setLong(1,userID);            pstmt.execute();            pstmt.close();            // Remove user from all groups            pstmt = con.prepareStatement(DELETE_USER_GROUPS);            pstmt.setLong(1,userID);            pstmt.execute();            pstmt.close();            // Delete all of the users's extended properties            pstmt = con.prepareStatement(DELETE_USER_PROPS);            pstmt.setLong(1,userID);            pstmt.execute();            pstmt.close();            // Delete all of user's watches            pstmt = con.prepareStatement(DELETE_USER_WATCHES);            pstmt.setLong(1, userID);            pstmt.execute();            pstmt.close();            // Delete the actual user entry            pstmt = con.prepareStatement(DELETE_USER);            pstmt.setLong(1,userID);            pstmt.execute();        }        catch (Exception e) {            e.printStackTrace();            abortTransaction = true;        }        finally {            try {  pstmt.close(); }            catch (Exception e) { e.printStackTrace(); }            ConnectionManager.closeTransactionConnection(con, abortTransaction);        }        // Expire user's messages from cache        long [] messagesArray = messages.toArray();        for (int i=0; i<messagesArray.length; i++) {            factory.cacheManager.messageCache.remove(new Long(messagesArray[i]));        }        // Expire user perms cache.        factory.cacheManager.userPermsCache.clear();        // Expire user caches.        factory.cacheManager.userCache.remove(new Long(userID));        factory.cacheManager.userIDCache.remove(user.getUsername());    }    public int getUserCount() {        int count = 0;        Connection con = null;        PreparedStatement pstmt = null;        try {            con = ConnectionManager.getConnection();            pstmt = con.prepareStatement(USER_COUNT);            ResultSet rs = pstmt.executeQuery();            if (rs.next()) {                count = rs.getInt(1);            }        }        catch( SQLException sqle ) {            sqle.printStackTrace();        }        finally {            try {  pstmt.close();   }            catch (Exception e) { e.printStackTrace(); }            try {  con.close();   }            catch (Exception e) { e.printStackTrace(); }        }        return count;    }    public Iterator users() {        LongList users = new LongList(500);        Connection con = null;        PreparedStatement pstmt = null;        try {            con = ConnectionManager.getConnection();            pstmt = con.prepareStatement(ALL_USERS);            ResultSet rs = pstmt.executeQuery();            // Set the fetch size. This will prevent some JDBC drivers from trying            // to load the entire result set into memory.            ConnectionManager.setFetchSize(rs, 500);            while (rs.next()) {                users.add(rs.getLong(1));            }        }        catch(SQLException sqle) {            sqle.printStackTrace();        }        finally {            try {  pstmt.close();   }            catch (Exception e) { e.printStackTrace(); }            try {  con.close();   }            catch (Exception e) { e.printStackTrace(); }        }        return new DatabaseObjectIterator(JiveGlobals.USER, users.toArray(), this);    }    public Iterator users(int startIndex, int numResults) {        LongList users = new LongList();        Connection con = null;        PreparedStatement pstmt = null;        try {            con = ConnectionManager.getConnection();            pstmt = ConnectionManager.createScrollablePreparedStatement(con, ALL_USERS);            ResultSet rs = pstmt.executeQuery();            ConnectionManager.setFetchSize(rs, startIndex+numResults);            // Move to start of results we're interested in.            ConnectionManager.scrollResultSet(rs, startIndex);            // Now read in desired number of results (or stop if we run out            // of results).            for (int i=0; i<numResults; i++) {                if (rs.next()) {                    users.add(rs.getLong(1));                }                else {                    break;                }            }        }        catch( SQLException sqle ) {            sqle.printStackTrace();        }        finally {            try {  pstmt.close(); }            catch (Exception e) { e.printStackTrace(); }            try {  con.close();   }            catch (Exception e) { e.printStackTrace(); }        }        return new DatabaseObjectIterator(JiveGlobals.USER, users.toArray(), this);    }    public int userMessageCount(User user) {        Long key = new Long(user.getID());        // See if the value is in cache.        Integer msgCount =                (Integer)factory.cacheManager.userMessageCountCache.get(key);        if (msgCount != null) {            return msgCount.intValue();        }        // Not cached, so load from database.        int count = 0;        Connection con = null;        PreparedStatement pstmt = null;        try {            con = ConnectionManager.getConnection();            pstmt = con.prepareStatement(USER_MESSAGE_COUNT);            pstmt.setLong(1, user.getID());            ResultSet rs = pstmt.executeQuery();            if (rs.next()) {                count = rs.getInt(1);            }        }        catch( SQLException sqle ) {            sqle.printStackTrace();        }        finally {            try {  pstmt.close(); }            catch (Exception e) { e.printStackTrace(); }            try {  con.close();   }            catch (Exception e) { e.printStackTrace(); }        }        // Add to cache.        msgCount = new Integer(count);        factory.cacheManager.userMessageCountCache.put(key, msgCount);        return count;    }    public Iterator userMessages(User user) {        LongList messages = new LongList();        Connection con = null;        PreparedStatement pstmt = null;        try {            con = ConnectionManager.getConnection();            pstmt = con.prepareStatement(ALL_USER_MESSAGES);            pstmt.setLong(1, user.getID());            ResultSet rs = pstmt.executeQuery();            while (rs.next()) {                messages.add(rs.getLong(1));            }        }        catch( SQLException sqle ) {            sqle.printStackTrace();        }        finally {            try {  pstmt.close(); }            catch (Exception e) { e.printStackTrace(); }            try {  con.close();   }            catch (Exception e) { e.printStackTrace(); }        }        return new DatabaseObjectIterator(JiveGlobals.MESSAGE, messages.toArray(),                factory);    }    public Iterator userMessages(User user, int startIndex, int numResults) {        LongList messages = new LongList();        Connection con = null;        PreparedStatement pstmt = null;        try {            con = ConnectionManager.getConnection();            pstmt = con.prepareStatement(ALL_USER_MESSAGES);            pstmt.setLong(1, user.getID());            ResultSet rs = pstmt.executeQuery();            // Move to start of index            for (int i=0; i<startIndex; i++) {                rs.next();            }            // Now read in desired number of results (or stop if we run out            // of results).            for (int i=0; i<numResults; i++) {                if (rs.next()) {                    messages.add(rs.getLong(1));                }                else {                    break;                }            }        }        catch( SQLException sqle ) {            sqle.printStackTrace();        }        finally {            try {  pstmt.close(); }            catch (Exception e) { e.printStackTrace(); }            try {  con.close();   }            catch (Exception e) { e.printStackTrace(); }        }        return new DatabaseObjectIterator(JiveGlobals.MESSAGE, messages.toArray(),                factory);    }}

⌨️ 快捷键说明

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