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

📄 dbuser.java

📁 一套会员管理系统组件
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/**
 * $RCSfile: DbUser.java,v $
 * $Revision: 1.1.1.1 $
 * $Date: 2002/09/09 13:50:59 $
 *
 * New Jive  from Jdon.com. Modified by Frank Chu
 *
 * This software is the proprietary information of CoolServlets, Inc.
 * Use is subject to license terms.
 */

package com.airinbox.member.forum.database;

import com.airinbox.member.forum.*;
import com.airinbox.member.util.*;

import java.util.*;
import java.sql.*;

import com.airinbox.component.authorize.UnauthorizedException;
import com.airinbox.component.authorize.Authorization;
import com.airinbox.member.forum.User;

/**
 * Database implementation of the User interface. Additionally, it filters all
 * HTML tags from fields before returning them for security purposes.<p>
 *
 * The DbUser keeps track of a user's reward points. Optionally, you
 * can specify a initial number of reward points to assign a newly created user
 * by setting the Jive property <tt>rewards.initialPoints</tt>. If no value is
 * set, the default will be 0 points.
 */
public class DbUser implements User, Cacheable {

    /** DATABASE QUERIES **/
    private static final String LOAD_PROPERTIES =
        "SELECT name, propValue FROM "+Globals.getConfig(Globals._TABLE_USER_PROP)+" WHERE userID=?";
    private static final String DELETE_PROPERTY =
        "DELETE FROM "+Globals.getConfig(Globals._TABLE_USER_PROP)+" WHERE userID=? AND name=?";
    private static final String DELETE_PROPERTIES =
        "DELETE FROM "+Globals.getConfig(Globals._TABLE_USER_PROP)+" WHERE userID=?";
    private static final String INSERT_PROPERTY =
        "INSERT INTO "+Globals.getConfig(Globals._TABLE_USER_PROP)+"(userID,name,propValue) VALUES(?,?,?)";
    private static final String LOAD_USER_BY_ID =
        "SELECT userID,nameVisible,emailVisible,"+
        "rewardPoints,rate,coins,article FROM "+Globals.getConfig(Globals._TABLE_USER)+" WHERE userID=?";
    private static final String INSERT_USER = "INSERT INTO "+Globals.getConfig(Globals._TABLE_USER)+
		"(userID,nameVisible,emailVisible,rewardPoints,rate,coins,article) VALUES(?,?,?,?,?,?,?)";
    private static final String SAVE_USER =
        "UPDATE "+Globals.getConfig(Globals._TABLE_USER)+" SET nameVisible=?," +
        "emailVisible=?,rewardPoints=?,rate=?,coins=?,article=? WHERE " +
        "userID=?";
    private static final String SAVE_REWARD_POINTS =
        "UPDATE "+Globals.getConfig(Globals._TABLE_USER)+" SET rewardPoints=? WHERE userID=?";
    private static final String SAVE_RATE =
        "UPDATE "+Globals.getConfig(Globals._TABLE_USER)+" SET rate=? WHERE userID=?";
    private static final String SAVE_COINS =
        "UPDATE "+Globals.getConfig(Globals._TABLE_USER)+" SET coins=? WHERE userID=?";
    private static final String SAVE_ARTICLE =
        "UPDATE "+Globals.getConfig(Globals._TABLE_USER)+" SET article=? WHERE userID=?";
    
    /**
     * Controls whether extended properties should be lazily loaded (not loaded
     * until requested). If the properties are infrequently used, this provides
     * a great speedup in initial object loading time. However, if your
     * application does use extended properties all the time, you may wish to
     * turn lazy loading off, as it's actually faster in total db lookup time
     * to load everything at once.
     */
    private static final boolean LAZY_PROP_LOADING = true;

    private static final ForumPermissions USER_ADMIN_PERMS =
            new ForumPermissions(false,false,false,true,false,false,false,false,false);

    private static int initialRewardPoints;
    private static int initialRate;
    private static int initialCoins;
    private static int initialArticle;
    static {
        // Load the default reward points to assign new users. Default is 0.
        initialRewardPoints = 0;
        initialRate = 0;
        initialCoins = 0;
        initialArticle = 0;
        // Load a user defined value if specified.
        try {
            String points = Globals.getMemberProperty("rewards.initialPoints");
            String rate = Globals.getMemberProperty("rewards.initialRate");
            String coins = Globals.getMemberProperty("rewards.initialCoins");
            String article = Globals.getMemberProperty("rewards.initialArticle");
            if (points != null) {
                initialRewardPoints = Integer.parseInt(points);
            }
            if(rate != null)
            	initialRate = Integer.parseInt(rate);
            if(coins != null)
            	initialCoins = Integer.parseInt(coins);
            if(article != null)
            	initialArticle = Integer.parseInt(article);
        }
        catch(Exception e) { e.printStackTrace();}
    }

    /**
     * User id of -2 means no user id has been set yet. -1 is reserved for
     * "anonymous user" and 0 is reserved for "all users".
     */
    private com.airinbox.component.authorize.User originalUser = null;
    private long id = -2;
    private String username = null;
    private String password;
    private String name = "";
    private boolean nameVisible = true;
    private String email;
    private boolean emailVisible = true;
    private int rewardPoints;
    private java.util.Date creationDate;
    private int rate;
    private int coins;
    private int article;
    private Map properties;

    private DbForumFactory factory;

    /**
     * Create a new DbUser with all required AND optional fields. Using this
     * constructor can result in significantly fewer database operations than
     * calling the other create constructor and then using setter methods.
     *
     * @param username the username for the user.
     * @param password a password for the user.
     * @param email the email address for the user.
     */
    protected DbUser(com.airinbox.component.authorize.User user, 
    		boolean nameVisible, boolean emailVisible, Map properties,
            DbForumFactory factory)
    {
    	this.originalUser = user;
        this.id = user.getId();
        this.username = user.getName();
        this.email = user.getEmail();
        this.name = user.getRealName();
        this.nameVisible = nameVisible;
        this.emailVisible = emailVisible;
        this.rewardPoints = initialRewardPoints;
        this.rate = initialRate;
        this.coins = initialCoins;
        this.article = initialArticle;
        this.factory = factory;

        if (properties != null) {
            // Make sure that the none of the properties are null values.
            Iterator iter = properties.keySet().iterator();
            while (iter.hasNext()) {
                String pName = (String)iter.next();
                if (pName == null || "".equals(pName)) {
                    throw new NullPointerException(
                            "Cannot set property with empty or null value."
                    );
                }
            }
            iter = properties.values().iterator();
            while (iter.hasNext()) {
                String pValue = (String)iter.next();
                if (pValue == null || "".equals(pValue)) {
                    throw new NullPointerException(
                            "Cannot set property with empty or null value."
                    );
                }
            }
            // No null found, set the properties.
            this.properties = properties;
        }
        else {
            this.properties = new Hashtable();
        }
        insertIntoDb();
    }

    /**
     * Load a DbUser object specified by userID.
     *
     * @param userID the userID of the user to load.
     */
    protected DbUser(long userID, DbForumFactory factory)
            throws UserNotFoundException
    {
        if (userID < 1) {
            throw new UserNotFoundException();
        }
        this.id = userID;
        this.factory = factory;
        loadFromDb();
    }

    //FROM THE USER INTERFACE//
    public long getID() {
        return id;
    }

    public String getUsername() {
        return StringUtils.escapeHTMLTags(username);
    }

    public String getName() {
        return StringUtils.escapeHTMLTags(name);
    }

    public void setName(String name) throws UnauthorizedException {
        this.name = name;
        saveToDb();
        // Remove user from cache
        factory.cacheManager.userCache.remove(this.id);
    }

    public boolean isNameVisible() {
        return nameVisible;
    }

    public void setNameVisible(boolean visible) throws UnauthorizedException {
        this.nameVisible = visible;
        saveToDb();
        // Remove user from cache
        factory.cacheManager.userCache.remove(this.id);
    }

    public void setPassword(String password) throws UnauthorizedException {
        // Compute hash of password.
        this.password = password;
        saveToDb();
        // Remove user from cache
        factory.cacheManager.userCache.remove(this.id);
    }

    public String getEmail() {
        return StringUtils.escapeHTMLTags(email);
    }

    public void setEmail(String email) throws UnauthorizedException {
        this.email = email;
        saveToDb();
        // Remove user from cache
        factory.cacheManager.userCache.remove(this.id);
    }

    public boolean isEmailVisible() {
        return emailVisible;
    }

    public void setEmailVisible(boolean visible) throws UnauthorizedException {
        this.emailVisible = visible;
        saveToDb();
        // Remove user from cache
        factory.cacheManager.userCache.remove(this.id);
    }

    public java.util.Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(java.util.Date creationDate)
            throws UnauthorizedException
    {
        this.creationDate = creationDate;
        saveToDb();
        // Remove user from cache
        factory.cacheManager.userCache.remove(this.id);
    }

    public String getProperty(String name) {
        if (LAZY_PROP_LOADING && properties == null) {
            loadPropertiesFromDb();
        }
        return StringUtils.escapeHTMLTags((String)properties.get(name));
    }

    public void setProperty(String name, String value) {
        if (LAZY_PROP_LOADING && properties == null) {
            loadPropertiesFromDb();
        }
        // Make sure the property name and value aren't null.
        if (name == null || value == null || "".equals(name) || "".equals(value)) {
            throw new NullPointerException("Cannot set property with empty or null value.");
        }
        properties.put(name, value);
        savePropertiesToDb();
        // Remove user from cache
        factory.cacheManager.userCache.remove(this.id);
    }

    public void deleteProperty(String name) {
        if (LAZY_PROP_LOADING) {
            if (properties == null) {
                loadPropertiesFromDb();
            }
        }
        properties.remove(name);
        deletePropertyFromDb(name);
        // Remove user from cache
        factory.cacheManager.userCache.remove(this.id);
    }

    public Iterator propertyNames() {
        if (LAZY_PROP_LOADING) {
            if (properties == null) {
                loadPropertiesFromDb();
            }
        }
        return Collections.unmodifiableSet(properties.keySet()).iterator();
    }

    public int getRewardPoints() {
        return rewardPoints;
    }

    public void setRewardPoints(int rewardPoints)
            throws SQLException
    {
        // Save old point value in case something goes wrong.
        int oldPoints = this.rewardPoints;
        this.rewardPoints = rewardPoints;
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = ConnectionManager.getConnection();
            pstmt = con.prepareStatement(SAVE_REWARD_POINTS);
            pstmt.setInt(1, rewardPoints);
            pstmt.setLong(2, this.id);
            pstmt.executeUpdate();
        }
        catch (SQLException sqle) {
            // Switch back to old point value.
            this.rewardPoints = oldPoints;
            // Throw an exception so that the caller knows that the update
            // operation failed.
            throw sqle;
        }
        finally {
            try {  pstmt.close();   }
            catch (Exception e) { e.printStackTrace(); }
            try {  con.close();   }
            catch (Exception e) { e.printStackTrace(); }
        }
    }

    public ForumPermissions getPermissions(Authorization authorization) {
        if (authorization.getId() == id) {
            return USER_ADMIN_PERMS;
        }
        else {
            return ForumPermissions.none();
        }
    }

    public boolean hasPermission(int type) {
        return true;
    }

    //FROM THE CACHEABLE INTERFACE//

    public int getSize() {
        // Approximate the size of the object in bytes by calculating the size
        // of each field.
        int size = 0;
        size += CacheSizes.sizeOfObject();              // overhead of object
        size += CacheSizes.sizeOfLong();                // id
        size += CacheSizes.sizeOfString(username);      // username
        size += CacheSizes.sizeOfString(password);  // password
        size += CacheSizes.sizeOfString(name);          // name
        size += CacheSizes.sizeOfString(email);         // email
        size += CacheSizes.sizeOfBoolean();             // nameVisible
        size += CacheSizes.sizeOfBoolean();             // emailVisible
        size += CacheSizes.sizeOfMap(properties);       // properties
        size += CacheSizes.sizeOfDate();                // creationDate
        size += CacheSizes.sizeOfDate();                // modifiedDate
        size += CacheSizes.sizeOfInt();                 // reward points
        size += CacheSizes.sizeOfObject();              // factory

        return size;
    }

    //OTHER METHODS

    /**
     * Returns a String representation of the User object using the username.
     *
     * @return a String representation of the User object.
     */
    public String toString() {

⌨️ 快捷键说明

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