dbforumcategory.java

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

JAVA
1,544
字号
            if (objectIDs == null && factory.cacheManager.isShortTermQueryCacheEnabled()) {                objectIDs = (long [])factory.cacheManager.shortTermQueryCache.get(key);            }            // If already in cache, return the block.            if (objectIDs != null) {                /**                 * The actual block may be smaller than BLOCK_SIZE. If                 * that's the case, it means two things:                 *  1) We're at the end boundary of all the results.                 *  2) If the start index is greater than the length of the current                 *     block, than there aren't really any results to return.                 */                if (startIndex >= blockStart + objectIDs.length) {                    // Return an empty array                    return EMPTY_BLOCK;                }                else {                    return objectIDs;                }            }            // Otherwise, we have to load up the block from the database.            else {                LongList objectList = new LongList(BLOCK_SIZE);                Connection con = null;                Statement stmt = null;                try {                    con = ConnectionManager.getConnection();                    stmt = con.createStatement();                    // Set the maxium number of rows to end at the end of this block.                    ConnectionManager.setMaxRows(stmt, BLOCK_SIZE * (blockID+1));                    ResultSet rs = stmt.executeQuery(query);                    // Grab BLOCK_SIZE rows at a time.                    ConnectionManager.setFetchSize(rs, BLOCK_SIZE);                    // Many JDBC drivers don't implement scrollable cursors the real                    // way, but instead load all results into memory. Looping through                    // the results ourselves is more efficient.                    for (int i=0; i<blockStart; i++) {                        rs.next();                    }                    // Keep reading results until the result set is exaughsted or                    // we come to the end of the block.                    int count = 0;                    while (rs.next() && count < BLOCK_SIZE) {                        objectList.add(rs.getLong(1));                        count++;                    }                }                catch( SQLException sqle ) {                    sqle.printStackTrace();                }                finally {                    try {  stmt.close(); }                    catch (Exception e) { e.printStackTrace(); }                    try {  con.close();   }                    catch (Exception e) { e.printStackTrace(); }                }                objectIDs = objectList.toArray();                // Add the block to cache                factory.cacheManager.queryCache.put(key, objectIDs);                addQueryKey(key);                /**                 * The actual block may be smaller than BLOCK_SIZE. If                 * that's the case, it means two things:                 *  1) We're at the end boundary of all the results.                 *  2) If the start index is greater than the length of the current                 *     block, than there aren't really any results to return.                 */                if (startIndex >= blockStart + objectIDs.length) {                    // Return an empty array                    return EMPTY_BLOCK;                }                else {                    return objectIDs;                }            }        }    }    /**     * Returns the count associated with a ResultFilter query.     *     * @param key the key associted with the query.     */    private int getCount(QueryCacheKey key) {        // Synchronize on the sql query so that only one thread can try to load the        // count at once. This should help to prevent the database from        // becoming overloaded on busy sites.        StringBuffer internKey = new StringBuffer(key.getSql().length()+4);        internKey.append(key.getSql()).append(key.getBlockID());        synchronized (internKey.toString().intern()) {            Integer count = (Integer)factory.cacheManager.queryCache.get(key);            // Check in short-term cache if not in the long-term cache.            if (count == null && factory.cacheManager.isShortTermQueryCacheEnabled()) {                count = (Integer)factory.cacheManager.shortTermQueryCache.get(key);            }            // If already in cache, return the count.            if (count != null) {                return count.intValue();            }            // Otherwise, we have to load the count from the db.            else {                Connection con = null;                Statement stmt = null;                try {                    con = ConnectionManager.getConnection();                    stmt = con.createStatement();                    ResultSet rs = stmt.executeQuery(key.getSql());                    rs.next();                    count = new Integer(rs.getInt(1));                }                catch( SQLException sqle ) {                    sqle.printStackTrace();                }                finally {                    try {  stmt.close(); }                    catch (Exception e) { e.printStackTrace(); }                    try {  con.close();   }                    catch (Exception e) { e.printStackTrace(); }                }                // Add the count to cache                factory.cacheManager.queryCache.put(key, count);                addQueryKey(key);                return count.intValue();            }        }    }    /**     * Adds a key to the queryKey list. The method ensures that the list never     * grows larger than fifty elements by removing keys from the end of the     * list. This doesn't necessarily ensure proper caching behavior, but the     * queryKeys list will only grow large in rare circumstances, such as when     * statistics are being run.     *     * @param key the key to add to the queryKey list.     */    protected void addQueryKey(Object key) {        synchronized (queryKeys) {            queryKeys.add(key);            if (queryKeys.size() > 50) {                factory.cacheManager.queryCache.remove(queryKeys.removeLast());            }        }        // Re-add category to cache.        factory.cacheManager.categoryCache.put(new Long(id), this);    }    /**     * Inserts a new property into the datatabase.     */    private void insertPropertyIntoDb(String name, String value) {        Connection con = null;        PreparedStatement pstmt = null;        try {            con = ConnectionManager.getConnection();            pstmt = con.prepareStatement(INSERT_PROPERTY);            pstmt.setLong(1, id);            pstmt.setString(2, name);            pstmt.setString(3, value);            pstmt.executeUpdate();        }        catch (SQLException sqle) {           sqle.printStackTrace();        }        finally {            try {  pstmt.close();   }            catch (Exception e) { e.printStackTrace(); }            try {  con.close();   }            catch (Exception e) { e.printStackTrace(); }        }    }    /**     * Updates a property value in the database.     */    private void updatePropertyInDb(String name, String value) {        Connection con = null;        PreparedStatement pstmt = null;        try {            con = ConnectionManager.getConnection();            pstmt = con.prepareStatement(UPDATE_PROPERTY);            pstmt.setString(1, value);            pstmt.setString(2, name);            pstmt.setLong(3, id);            pstmt.executeUpdate();        }        catch (SQLException sqle) {           sqle.printStackTrace();        }        finally {            try {  pstmt.close();   }            catch (Exception e) { e.printStackTrace(); }            try {  con.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(); }        }    }    /**     * Inserts a new record into the database.     */    private void insertIntoDb(DbForumCategory parentCategory) {        Connection con = null;        PreparedStatement pstmt = null;        boolean abortTransaction = false;        try {            con = ConnectionManager.getTransactionConnection();            // First, find the the parent category's lft and rgt values.            pstmt = con.prepareStatement(FIND_LFT_RGT);            pstmt.setLong(1, parentCategory.getID());            ResultSet rs = pstmt.executeQuery();            rs.next();            int parentLft = rs.getInt(1);            int parentRgt = rs.getInt(2);            pstmt.close();            // Prepare tree for newly inserted value.            pstmt = con.prepareStatement(CHANGE_LFT);            pstmt.setInt(1, 2);            pstmt.setInt(2, parentLft);            pstmt.setInt(3, parentRgt);            pstmt.execute();            pstmt.close();            pstmt = con.prepareStatement(CHANGE_RGT);            pstmt.setInt(1, 2);            pstmt.setInt(2, parentRgt);            pstmt.execute();            pstmt.close();            // Compute lft and rgt based on parent values, then insert.            this.lft = parentRgt;            this.rgt = parentRgt + 1;            pstmt = con.prepareStatement(INSERT_CATEGORY);            pstmt.setLong(1, id);            pstmt.setString(2, name);            pstmt.setString(3, description);            pstmt.setString(4, StringUtils.dateToMillis(creationDate));            pstmt.setString(5, StringUtils.dateToMillis(modifiedDate));            pstmt.setInt(6, lft);            pstmt.setInt(7, rgt);            pstmt.executeUpdate();        }        catch (SQLException sqle) {            sqle.printStackTrace();            abortTransaction = true;        }        finally {            try {  pstmt.close(); }            catch (Exception e) { e.printStackTrace(); }            ConnectionManager.closeTransactionConnection(con, abortTransaction);        }    }    /**     * Saves the data to the database.     */    private void saveToDb() {        Connection con = null;        PreparedStatement pstmt = null;        try {            con = ConnectionManager.getConnection();            pstmt = con.prepareStatement(SAVE_CATEGORY);            pstmt.setString(1, name);            pstmt.setString(2, description);            pstmt.setString(3, StringUtils.dateToMillis(creationDate));            pstmt.setString(4, StringUtils.dateToMillis(modifiedDate));            pstmt.setLong(5, this.id);            pstmt.executeUpdate();        }        catch (SQLException sqle) {            sqle.printStackTrace();        }        finally {            try {  pstmt.close(); }            catch (Exception e) { e.printStackTrace(); }            try {  con.close();   }            catch (Exception e) { e.printStackTrace(); }        }    }    /**     * Loads a record from the database.     *     * @throws ForumCategoryNotFoundException     */    private void loadFromDb() throws ForumCategoryNotFoundException {        Connection con = null;        PreparedStatement pstmt = null;        try {            con = ConnectionManager.getConnection();            pstmt = con.prepareStatement(LOAD_CATEGORY);            pstmt.setLong(1, this.id);            ResultSet rs = pstmt.executeQuery();            if (!rs.next()) {                throw new ForumCategoryNotFoundException("Category " + id +                    " could not be loaded.");            }            this.name = rs.getString(1);            this.description = rs.getString(2);            this.creationDate =                new java.util.Date(Long.parseLong(rs.getString(3).trim()));            this.modifiedDate =                new java.util.Date(Long.parseLong(rs.getString(4).trim()));            this.lft = rs.getInt(5);            this.rgt = rs.getInt(6);            pstmt.close();            // Load properties            properties = new Hashtable();            pstmt = con.prepareStatement(LOAD_PROPERTIES);            pstmt.setLong(1, id);            rs = pstmt.executeQuery();            while(rs.next()) {                String name = rs.getString(1);                String value = rs.getString(2);                properties.put(name, value);            }        }        catch (SQLException sqle) {            sqle.printStackTrace();            throw new ForumCategoryNotFoundException("Category " + id +                    " could not be loaded.");        }        finally {            try {  pstmt.close(); }            catch (Exception e) { e.printStackTrace(); }            try {  con.close();   }            catch (Exception e) { e.printStackTrace(); }        }    }    protected void deleteFromDb(Connection con) throws SQLException    {        // Delete all child categories.        for (Iterator i=categories(); i.hasNext(); ) {            DbForumCategory category = (DbForumCategory)i.next();            category.deleteFromDb(con);        }        // Delete all forums.        for (Iterator i=forums(); i.hasNext(); ) {            DbForum forum = (DbForum)i.next();            try {                factory.deleteForum(forum);            }            catch (UnauthorizedException ue) {                ue.printStackTrace();            }        }        // Remove our own record.        PreparedStatement pstmt = null;        try {            pstmt = con.prepareStatement(DELETE_CATEGORY);            pstmt.setLong(1, id);            pstmt.execute();        }        finally {            try {  pstmt.close(); }            catch (Exception e) { e.printStackTrace(); }        }        factory.cacheManager.categoryCache.remove(new Long(id));    }}

⌨️ 快捷键说明

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