dbattachment.java

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

JAVA
438
字号
/** * $RCSfile: DbAttachment.java,v $ * $Revision: 1.7 $ * $Date: 2002/07/03 00:47:29 $ * * Copyright (C) 1999-2002 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.io.*;import java.sql.*;import java.util.*;import java.util.Date;import com.jivesoftware.forum.*;import com.jivesoftware.util.*;/** * Database implementation of the Attachment interface. * * @author Matt Tucker */public class DbAttachment implements Attachment, Cacheable {    private static final String LOAD_ATTACHMENT =   		"SELECT messageID, fileName, fileSize, contentType, creationDate, " +        "modifiedDate FROM jiveAttachment WHERE attachmentID=?";    private static final String INSERT_ATTACHMENT =    	"INSERT INTO jiveAttachment(attachmentID, messageID, fileName, " +        "fileSize, contentType, creationDate, modifiedDate) VALUES(?,?,?,?,?,?,?)";    private static final String DELETE_ATTACHMENT =    	"DELETE FROM jiveAttachment WHERE attachmentID=?";    private static final String LOAD_PROPERTIES =        "SELECT name, propValue FROM jiveAttachmentProp WHERE attachmentID=?";    private static final String DELETE_PROPERTY =        "DELETE FROM jiveAttachmentProp WHERE attachmentID=? AND name=?";    private static final String INSERT_PROPERTY =        "INSERT INTO jiveAttachmentProp(attachmentID,name,propValue) VALUES(?,?,?)";     private static final String UPDATE_PROPERTY =        "UPDATE jiveAttachmentProp SET propValue=? WHERE name=? AND attachmentID=?";    private long id = -1;    private long messageID;    private String name = null;    private int size;    private String contentType = null;    private Date creationDate;    private Date modifiedDate;    private Map properties;    private transient DbForumFactory factory;    /**     * Loads an existing Attachment object.     *     * @param attachmentID the ID of the attachment to load.     * @throws AttachmentNotFoundException if loading the specified attachment     *      fails.     */    public DbAttachment(long attachmentID) throws AttachmentNotFoundException {        this.id = attachmentID;        this.factory = DbForumFactory.getInstance();        // See if the file for the attachment exists on the filesystem. If not,        // the attachment can't be loaded.        File attachmentFile = new File(DbAttachmentManager.getAttachmentDir(),                attachmentID + ".bin");        if (!attachmentFile.exists()) {            throw new AttachmentNotFoundException("The attachment data was " +                    "not found on the filesystem.");        }        attachmentFile = null;        try {            loadFromDb();        }        catch(SQLException sqle) {            sqle.printStackTrace();            throw new AttachmentNotFoundException("Exception loading " +                    "attachment information from database.");        }    }    public DbAttachment(long messageID, String name, String contentType,            InputStream data) throws AttachmentException    {        this.messageID = messageID;        this.factory = DbForumFactory.getInstance();        // See if the contentType is valid.        if (!factory.getAttachmentManager().isValidType(contentType)) {            throw new AttachmentException(AttachmentException.BAD_CONTENT_TYPE);        }        this.id = SequenceManager.nextID(JiveGlobals.ATTACHMENT);        this.name = name;        this.contentType = contentType;        this.creationDate = new Date(System.currentTimeMillis());        this.modifiedDate = new Date(creationDate.getTime());        try {            insert(data);        }        catch (IOException ioe) {            throw new AttachmentException(AttachmentException.GENERAL_ERROR, ioe);        }        catch (SQLException sqle) {            throw new AttachmentException(AttachmentException.GENERAL_ERROR, sqle);        }    }    private void readObject(java.io.ObjectInputStream in)            throws IOException, ClassNotFoundException    {        in.defaultReadObject();        factory = DbForumFactory.getInstance();    }    // FROM THE ATTACHMENT INTERFACE    public long getID() {        return id;    }    public String getName() {        return name;    }    public long getSize() {        return size;    }    public String getContentType() {        return contentType;    }    public Date getCreationDate() {        return creationDate;    }    public Date getModifiedDate() {        return modifiedDate;    }    public InputStream getData() throws IOException {        File attachmentFile = new File(DbAttachmentManager.getAttachmentDir(), id + ".bin");        BufferedInputStream data = new BufferedInputStream(new FileInputStream(                attachmentFile));        return data;    }    public String getProperty(String name) {        if (properties == null) {            loadPropertiesFromDb();        }        return (String)properties.get(name);    }    public void setProperty(String name, String value) {        if (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.");        }        // See if we need to update a property value or insert a new one.        if (properties.containsKey(name)) {            // Only update the value in the database if the property value            // has changed.            if (!(value.equals(properties.get(name)))) {                properties.put(name, value);                updatePropertyInDb(name, value);                // Re-add attachment to cache.                factory.cacheManager.attachmentCache.put(new Long(this.id), this);            }        }        else {            properties.put(name, value);            insertPropertyIntoDb(name, value);            // Re-add attachment to cache.            factory.cacheManager.attachmentCache.put(new Long(this.id), this);        }    }    public void deleteProperty(String name) {        if (properties == null) {            loadPropertiesFromDb();        }        // Only delete the property if it exists.        if (properties.containsKey(name)) {            properties.remove(name);            deletePropertyFromDb(name);            // Re-add attachment to cache.            factory.cacheManager.attachmentCache.put(new Long(this.id), this);        }    }    public Iterator propertyNames() {        if (properties == null) {            loadPropertiesFromDb();        }        return Collections.unmodifiableSet(properties.keySet()).iterator();    }    public int getCachedSize() {        // 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.sizeOfObject();              // attach manager        size += CacheSizes.sizeOfLong();                // id        size += CacheSizes.sizeOfString(name);          // name        size += CacheSizes.sizeOfString(contentType);   // content type        size += CacheSizes.sizeOfDate();                // creation date        size += CacheSizes.sizeOfDate();                // modified date        size += CacheSizes.sizeOfMap(properties);       // properties        return size;    }    /**     * Returns the messageID associated with the attachment.     */    protected long getMessageID() {        return messageID;    }    /**     * Deletes the attachment.     */    protected void delete(Connection con) throws SQLException, IOException {        PreparedStatement pstmt = null;        try {			pstmt = con.prepareStatement(DELETE_ATTACHMENT);			pstmt.setLong(1, id);			pstmt.execute();		}        finally {            try {  pstmt.close();   }            catch (Exception e) { e.printStackTrace(); }        }        File attachmentFile = new File(DbAttachmentManager.getAttachmentDir(), id + ".bin");        attachmentFile.delete();        attachmentFile = null;        // Remove the attachment from cache.        factory.cacheManager.attachmentCache.remove(new Long(id));    }    /**     * Saves the attachment to storage and updates the db     *     * @throws AttachmentException if the attachment is missing information     * @throws IOException if an error occurs writing the attachment to storage     */    private void insert(InputStream data) throws SQLException, IOException,            AttachmentException    {        // Save the data to the file system.        File attachmentFile = new File(DbAttachmentManager.getAttachmentDir(), id + ".bin");        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(                attachmentFile));        byte[] buf = new byte[1024];        int len, fileSize = 0;        while ((len = data.read(buf)) >= 0) {            fileSize += len;            out.write(buf,0,len);        }        out.close();        // Size contains the total size of the file.        this.size = fileSize;        // If the file is too big, delete it and throw an exception.        if (size > factory.getAttachmentManager().getMaxAttachmentSize()*1024) {            new File(DbAttachmentManager.getAttachmentDir(), id + ".bin").delete();            throw new AttachmentException(AttachmentException.TOO_LARGE);        }        Connection con = null;        PreparedStatement pstmt = null;        try {			con = ConnectionManager.getConnection();			pstmt = con.prepareStatement(INSERT_ATTACHMENT);            pstmt.setLong(1, id);			pstmt.setLong(2, messageID);			pstmt.setString(3, name);            pstmt.setInt(4, size);            pstmt.setString(5, contentType);			pstmt.setString(6, StringUtils.dateToMillis(creationDate));            pstmt.setString(7, StringUtils.dateToMillis(modifiedDate));			pstmt.execute();		}		catch (SQLException sqle) {            sqle.printStackTrace();        }        finally {            try { if (pstmt != null) pstmt.close(); }            catch (Exception e) { e.printStackTrace(); }            try { if (con != null) con.close(); }            catch (Exception e) { e.printStackTrace(); }        }    }    private void loadFromDb() throws SQLException, AttachmentNotFoundException {        Connection con = null;        PreparedStatement pstmt = null;        try {			con = ConnectionManager.getConnection();			pstmt = con.prepareStatement(LOAD_ATTACHMENT);			pstmt.setLong(1, id);			ResultSet rs = pstmt.executeQuery();			if (!rs.next()) {                throw new AttachmentNotFoundException("Attachment " + id                    + " not found in the database.");            }            this.messageID = rs.getLong(1);            this.name = rs.getString(2);            this.size = rs.getInt(3);            this.contentType = rs.getString(4);            this.creationDate =                new java.util.Date(Long.parseLong(rs.getString(5).trim()));            this.modifiedDate =                new java.util.Date(Long.parseLong(rs.getString(6).trim()));		}        finally {            try {  pstmt.close();   }            catch (Exception e) { e.printStackTrace(); }            try {  con.close();   }            catch (Exception e) { e.printStackTrace(); }        }    }    /**     * 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()) {                String name = rs.getString(1);                String value = rs.getString(2);                properties.put(name, value);            }        }        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 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(); }        }    }}

⌨️ 快捷键说明

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