DatabaseUploadListener.java

package test;

import com.dotj.upload.interfaces.IUploadListener;
import com.dotj.upload.interfaces.IUploadContext;
import com.dotj.upload.interfaces.IUploadItemContext;
import com.dotj.form.UploadedFile;
import com.dotj.web.struts.JDBCUtil;
import com.dotj.base.Util;
import org.apache.log4j.Category;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletContext;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.io.ByteArrayInputStream;

/**
 * Database upload listener - a dotJ upload listener class that can be used to store files into a database.
 */
public class DatabaseUploadListener implements IUploadListener {
    private Category           _log = null;
    private HttpServletRequest _request = null;
    private IUploadContext     _uploadContext = null;
    private ServletContext     _app = null;
    private int                _id = -1;
public DatabaseUploadListener(ServletContext app) { _app = app; }
/** * The uploadBegin event signals the beginning of the upload by the Mulitpart processor. The IUploadContext * interface is passed, where you can obtain various settings. * <br><br> * <b>You can cancel the upload by returning <code>false</code> from this method.</b> * * @param uploadContext Context of this upload. This contains various settings as well as the HTTP request and * logger used for logging. * @return <code>true</code> to continue the upload, <code>false</code> to cancel it. */ public boolean uploadBegin(IUploadContext uploadContext) { // true to continue the upload, false to cancel it boolean continueUpload = true; // save the handles to a few important objects. _uploadContext = uploadContext; _log = uploadContext.getLogger(); _request = uploadContext.getRequest(); // Discard the memory buffers for each uploaded item. The freeing of the memory is done by the Multipart // processor after the persistFileItem is called. uploadContext.setDiscardMemory(true); _log.debug("[DatabaseUploadListener.uploadBegin] content length = " + _uploadContext.getContentLength()); return continueUpload; }
/** * This event gets called by the Mulitpart processor immediately after the boundary used for the upload has been * parsed. * * @param uploadContext Context of this upload. This contains various settings as well as the HTTP request and * logger used for logging. */ public void boundaryParsed(IUploadContext uploadContext) { }
/** * The formItemParsed event. This is called by the Multipart processor after a HTML form item has been parsed. The * form item itself can be obtained via the itemContext parameter. * <br><br> * Form items are not to be confused with file items. To handle file items, see the fileItemParsed event. * * @param itemContext Context for this form item. Contains the uploaded item as well as some methods for handling * the form item. * @return Currently ignored and reserved for future use. */ public boolean formItemParsed(IUploadItemContext itemContext) { // Get the form item. UploadedFile ufile = itemContext.getUploadedItem(); if (ufile.getFieldName().equals("id")) _id = Util.parseInt(new String(ufile.getBytes()), -1); return true; }
/** * The fileItemParsed event. This is called by the Multipart processor after a file item has been parsed. The * file item itself can be obtained via the itemContext parameter. * <br><br> * File items are not to be confused with form items. To handle form items, see the formItemParsed event. * * @param itemContext Context for this file item. Contains the uploaded item as well as some methods for handling * the file item. * @return If <code>true</code> is returned, the Multipart processor will check to see if this file * exceeds the maxbytes setting. If it does, then it will be rejected. If it doesn't, then * the <code>persistFileItem</code> event will be called.<br><br> * If <code>false</code> is returned, then the <code>persistFileItem</code> event will not be * called. */ public boolean fileItemParsed(IUploadItemContext itemContext) { boolean doPersist = true; // Get the file item. UploadedFile ufile = itemContext.getUploadedItem(); _log.debug("[DatabaseUploadListener.fileItemParsed] filename = " + ufile.getFilename()); // Check to see if this file passes the 'accept' and 'deny' filters. If it doesn't, then reject the file. if (!itemContext.passesFilter()) { itemContext.rejectCurrentItem(ufile.getRejectedReason()); doPersist = false; } return doPersist; }
/** * The persistFileItem event. This is called by the Multipart processor so you can persist the file item to persistent * storage. This is typically the file system or a database. In this method, you should * either reject the file by calling <code>IUploadItemContext.rejectCurrentItem</code> or * accept the file by calling <code>IUploadItemContext.acceptCurrentItem</code>. * <br><br> * Set the return code of this method based on whether you accepted or rejected the file. * If you accepted the file, then the Multipart processor will increment the number of * bytes uploaded accordingly. * @param itemContext Context for this file item. Contains the uploaded item as well as some methods for handling * the file item. * @return <code>true</code> if you accepted the file, <code>false</code> if you rejected it. */ public boolean persistFileItem(IUploadItemContext itemContext) { Connection conn = null; PreparedStatement pstmt = null; // Get the file item. UploadedFile ufile = itemContext.getUploadedItem(); _log.debug("[DatabaseUploadListener.persistFileItem] filename = " + ufile.getFilename()); // We couldn't determine the file to overlay in the database since the "id" parameter could not be found. if (_id == -1) { itemContext.rejectCurrentItem("The file's unique id could not be determined."); return false; } try { if (ufile.getFilename() != null && ufile.getFilename().length() > 0) { java.util.Properties prop = new java.util.Properties(); prop.load(new java.io.FileInputStream(_app.getRealPath("/WEB-INF/database.properties"))); Date currentDate = new Date(); String sql = "UPDATE uploads " + "SET Created = ?," + " Filename = ?," + " ContentType = ?," + " Filelength = ?," + " Bytes = ? " + "WHERE Id = ?"; conn = JDBCUtil.getConnection(_app); pstmt = conn.prepareStatement(sql); pstmt.setTimestamp(1, new java.sql.Timestamp(currentDate.getTime())); pstmt.setString(2, ufile.getFilename()); pstmt.setString(3, ufile.getContentType()); pstmt.setInt(4, ufile.getFileLength()); ByteArrayInputStream bais = new ByteArrayInputStream(ufile.getBytes()); pstmt.setBinaryStream(5, bais, ufile.getDataLength()); pstmt.setInt(6, _id); pstmt.execute(); _log.debug("Wrote " + ufile.getDataLength() + " bytes to database"); itemContext.acceptCurrentItem(); // Accept the file! return true; } } catch (Exception e) { // An exception occurred. Reject the file and mark the upload request as being in error. itemContext.rejectCurrentItem("System error occurred in writing the file to the database."); String msg = e.getClass() + " while persisting the file " + ufile.getFilename() + ". Exception message = [" + e.getMessage() + "]"; _uploadContext.markAsError("Unable to perform upload request.", msg); _log.error(msg); } finally { try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException sqle) { ; } } return false; } }