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

📄 dbforummessage.java

📁 java开发的一套非常好用的oa系统
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        properties.remove(name);
        // Only save to the db if the object is ready
        if (!isReadyToSave) {
            return;
        }
        deletePropertyFromDb(name);
        // Remove message from cache
        factory.cacheManager.messageCache.remove(this.id);
    }

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

    public boolean isAnonymous() {
        return (userID == -1);
    }

    public ForumThread getForumThread() {
        if (threadID == -1) {
            return null;
        }
        try {
            return factory.cacheManager.threadCache.get(threadID);
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

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

    //FROM CACHEABLE INTERFACE//

    public int getSize() {
        // Approximate the size of the object in bytes by calculating the size
        // of each field. Filtered variable sizes are approximated since they
        // are lazily loaded.
        int size = 0;
        size += CacheSizes.sizeOfObject();              // overhead of object
        size += CacheSizes.sizeOfLong();                // id
        size += CacheSizes.sizeOfString(subject) * 2;   // subject & filtered
        size += CacheSizes.sizeOfString(body) * 2;      // body & filtered
        size += CacheSizes.sizeOfDate();                // creation date
        size += CacheSizes.sizeOfDate();                // modified date
        size += CacheSizes.sizeOfLong();                // userID
        size += CacheSizes.sizeOfLong();                // threadID
        size += CacheSizes.sizeOfLong();                // forumID
        size += CacheSizes.sizeOfMap(properties) * 2;   // map object * filtered
        size += CacheSizes.sizeOfObject();              // ref to factory
        size += CacheSizes.sizeOfInt();                 // moderation points
        size += CacheSizes.sizeOfInt();                 // reward points

        return size;
    }

    //OTHER METHODS//

    /**
     * Returns a String representation of the message object using the subject.
     *
     * @return a String representation of the ForumMessage object.
     */
    public String toString() {
        return subject;
    }

    public int hashCode() {
        return (int)id;
    }


    public boolean equals(Object object) {
        if (this == object) {
            return true;
        }
        if (object != null && object instanceof DbForumMessage) {
            return id == ((DbForumMessage)object).getID();
        }
        else {
            return false;
        }
    }

    /**
     * Returns the number of reward points for the thread.
     */
    protected int getRewardPoints() {
        return rewardPoints;
    }

    /**
     * Sets the number of reward points for the thread.
     */
    protected void setRewardPoints(int rewardPoints, Connection con)
            throws SQLException
    {
        // Save old point value in case something goes wrong.
        int oldPoints = this.rewardPoints;
        this.rewardPoints = rewardPoints;
        try {
            saveToDb(con);
        }
        catch (SQLException sqle) {
            // Switch back to old point value.
            this.rewardPoints = oldPoints;
            throw sqle;
        }
    }

    /**
     * Loads properties from the database.
     */
    private synchronized void loadPropertiesFromDb() {
        this.properties = new Hashtable();
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = ConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_PROPERTIES);
            pstmt.setLong(1, id);
            ResultSet rs = pstmt.executeQuery();
            while(rs.next()) {
                properties.put(rs.getString(1), rs.getString(2));
            }
        }
        catch( SQLException sqle ) {
           sqle.printStackTrace();
        }
        finally {
            try {  pstmt.close();   }
            catch (Exception e) { e.printStackTrace(); }
            try {  con.close();   }
            catch (Exception e) { e.printStackTrace(); }
        }
    }

    /**
     * Saves properties to the database. Normally, this method will clear out
     * all old property values before saving new ones. However, the deletion
     * step will be skipped if specified. This is useful for the case that you
     * know that no current properties could possibly exist.
     *
     * @param con a database connection to be used for property saving.
     * @param deleteOldProps true if old properties should be deleted before
     *      saving new ones. This should be true in most cases.
     */
    private synchronized void savePropertiesToDb(Connection con,
            boolean deleteOldProps) throws SQLException
    {
        PreparedStatement pstmt = null;
        try {
            if (deleteOldProps) {
                // Delete all old values.
                pstmt = con.prepareStatement(DELETE_PROPERTIES);
                pstmt.setLong(1, id);
                pstmt.execute();
                pstmt.close();
            }
            // Now insert new values.
            pstmt = con.prepareStatement(INSERT_PROPERTY);
            Iterator iter = properties.keySet().iterator();
            while (iter.hasNext()) {
                String name = (String)iter.next();
                String value = (String)properties.get(name);
                pstmt.setLong(1, id);
                pstmt.setString(2, name);
                pstmt.setString(3, value);
                pstmt.executeUpdate();
            }
        }
        finally {
            try {  pstmt.close();   }
            catch (Exception e) { e.printStackTrace(); }
        }
    }

    /**
     * Deletes a property from the db.
     */
    private synchronized void deletePropertyFromDb(String name) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
           con = ConnectionManager.getConnection();
           pstmt = con.prepareStatement(DELETE_PROPERTY);
           pstmt.setLong(1, id);
           pstmt.setString(2, name);
           pstmt.execute();
        }
        catch( SQLException sqle ) {
            sqle.printStackTrace();
        }
        finally {
            try {  pstmt.close();   }
            catch (Exception e) { e.printStackTrace(); }
            try {  con.close();   }
            catch (Exception e) { e.printStackTrace(); }
        }
    }

    /**
     *  Loads message and user data from the database.
     */
    private void loadFromDb() throws ForumMessageNotFoundException {
        // Based on the id in the object, get the message data from the database.
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = ConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_MESSAGE);
            pstmt.setLong(1, id);
            ResultSet rs = pstmt.executeQuery();
            if (!rs.next()) {
                throw new ForumMessageNotFoundException("Message " + id +
                    " could not be loaded from the database.");
            }
            this.threadID = rs.getLong(1);
            this.forumID = rs.getLong(2);
            this.userID = rs.getLong(3);
            if (rs.wasNull()) {
                userID = -1;
            }
            this.subject = rs.getString(4);
            // The Oracle JDBC driver is lame and returns the String "null" for
            // null columns.
            if (rs.wasNull()) {
                this.subject = null;
            }
            // Use the connection manager to get the body field.
            this.body = ConnectionManager.getLargeTextField(rs, 5);
            this.moderationValue = rs.getInt(6);
            this.rewardPoints = rs.getInt(7);
            // We trim() the dates before trying to parse them because some
            // databases pad with extra characters when returning the data.
            this.creationDate =
                new java.util.Date(Long.parseLong(rs.getString(8).trim()));
            this.modifiedDate =
                new java.util.Date(Long.parseLong(rs.getString(9).trim()));

            // Load any extended message properties.
            if (!LAZY_PROP_LOADING) {
                pstmt.close();
                properties = new Hashtable();
                pstmt = con.prepareStatement(LOAD_PROPERTIES);
                pstmt.setLong(1, id);
                rs = pstmt.executeQuery();
                while(rs.next()) {
                    // Add in name, value as a new property.
                    properties.put(rs.getString(1), rs.getString(2));
                }
            }
         }
        catch( SQLException sqle ) {
            throw new ForumMessageNotFoundException( "Message with id "
                    + id + " could not be loaded from the database."
            );
        }
        catch (NumberFormatException nfe) {
            System.err.println("WARNING: In DbForumMessage.loadFromDb() -- there " +
                "was an error parsing the dates returned from the database. Ensure " +
                "that they're being stored correctly.");
            throw new ForumMessageNotFoundException( "Message with id "
                    + id + " could not be loaded from the database."
            );
        }
        finally {
            try {  pstmt.close();   }
            catch (Exception e) { e.printStackTrace(); }
            try {  con.close();   }
            catch (Exception e) { e.printStackTrace(); }
        }
    }

    /**
     * Inserts a new message into the database. A connection object must
     * be passed in. The connection must be open when passed in, and will
     * remain open when passed back. This method allows us to make insertions
     * be transactional.
     *
     * @param con an open Connection used to insert the thread to the db.
     * @param thread the ForumThread the message is being added to.
     */
    protected void insertIntoDb(DbForumThread thread, long parentMessageID,
            Connection con) throws SQLException
    {
        // Set the message threadID, forumID
        this.threadID = thread.getID();
        // Get forumID and moderation value.
        Forum forum = thread.getForum();
        this.forumID = forum.getID();
        // If the moderation value hasn't already been set, use the default.
        if (moderationValue == Integer.MIN_VALUE) {
            moderationValue = forum.getModerationDefaultMessageValue();
        }

        // Now, insert the message to the db.
        PreparedStatement pstmt = null;
        try {
            pstmt = con.prepareStatement(INSERT_MESSAGE);
            pstmt.setLong(1, id);
            if (parentMessageID == -1) {
                pstmt.setNull(2, Types.NUMERIC);
            }
            else {
                pstmt.setLong(2, parentMessageID);
            }
            pstmt.setLong(3, threadID);
            pstmt.setLong(4, thread.forumID);
            if (userID == -1) {
                pstmt.setNull(5, Types.NUMERIC);
            }
            else {
                pstmt.setLong(5, userID);
            }
            pstmt.setString(6, subject);
            // Use the connection manager to set the body field.
            ConnectionManager.setLargeTextField(pstmt, 7, body);
            pstmt.setInt(8, moderationValue);
            pstmt.setInt(9, rewardPoints);
            pstmt.setString(10, StringUtils.dateToMillis(creationDate));
            pstmt.setString(11, StringUtils.dateToMillis(modifiedDate));
            pstmt.executeUpdate();
        }
        finally {
            try {  pstmt.close();   }
            catch (Exception e) { e.printStackTrace(); }
        }

        // We're done inserting the message, so now save any extended
        // properties to the database.
        if (this.properties.size() > 0) {
            savePropertiesToDb(con, false);
        }

        // Since we're done inserting the object to the database, it is ready
        // for future saves.
        isReadyToSave = true;
    }

    /**
     * Saves message data to the database.
     */
    private synchronized void saveToDb() {
        boolean abortTransaction = false;
        Connection con = null;
        try {
            con = ConnectionManager.getTransactionConnection();
            saveToDb(con);
        }
        catch( Exception e ) {
            e.printStackTrace();
            abortTransaction = true;
        }
        finally {
            ConnectionManager.closeTransactionConnection(con, abortTransaction);
        }
    }

    /**
     * Implementation of saveToDb that takes a Connection. This is useful for
     * participating in transactions.
     */
    private synchronized void saveToDb(Connection con) throws SQLException {
        PreparedStatement pstmt = null;
        try {
            pstmt = con.prepareStatement(SAVE_MESSAGE);
            pstmt.setLong(1, userID);
            pstmt.setString(2, subject);
            // Use the connection manager to set the body field.
            ConnectionManager.setLargeTextField(pstmt, 3, body);
            pstmt.setInt(4, moderationValue);
            pstmt.setInt(5, rewardPoints);
            pstmt.setString(6, StringUtils.dateToMillis(creationDate));
            pstmt.setString(7, StringUtils.dateToMillis(modifiedDate));
            pstmt.setLong(8, id);
            pstmt.executeUpdate();
        }
        finally {
            try {  pstmt.close();   }
            catch (Exception e) { e.printStackTrace(); }
        }
    }
}

⌨️ 快捷键说明

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