com.baobao121.baby.common.SimpleUploaderServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.baobao121.baby.common.SimpleUploaderServlet.java

Source

/*
 * FCKeditor - The text editor for internet
 * Copyright (C) 2003-2005 Frederico Caldeira Knabben
 * 
 * Licensed under the terms of the GNU Lesser General Public License:
 *       http://www.opensource.org/licenses/lgpl-license.php
 * 
 * For further information visit:
 *       http://www.fckeditor.net/
 * 
 * File Name: SimpleUploaderServlet.java
 *    Java File Uploader class.
 * 
 * Version:  2.3
 * Modified: 2005-08-11 16:29:00
 * 
 * File Authors:
 *       Simone Chiaretta (simo@users.sourceforge.net)
 */

package com.baobao121.baby.common;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.baobao121.app.common.SystemConstant;
import com.baobao121.app.common.UserCommonInfo;
import com.baobao121.app.persistence.Photo;
import com.baobao121.app.persistence.PhotoAlbum;
import com.baobao121.baby.dao.BabyAlbumDao;
import com.baobao121.baby.dao.BabyPhotoDao;
import com.baobao121.common.util.tool.DateUtil;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * Servlet to upload files.<br>
 * 
 * This servlet accepts just file uploads, eventually with a parameter
 * specifying file type
 * 
 * @author Simone Chiaretta (simo@users.sourceforge.net)
 */

public class SimpleUploaderServlet extends HttpServlet {
    private static ApplicationContext context = null;

    private static BabyPhotoDao babyPhotoDao;
    private static BabyAlbumDao babyAlbumDao;
    private static String[] path = SimpleUploaderServlet.class.getResource("").toString().split("classes");
    static {
        context = new FileSystemXmlApplicationContext(
                new String[] { path[0] + "springconfig/applicationContext-DB.xml",
                        path[0] + "springconfig/applicationContext-Dao.xml" });

        babyPhotoDao = (BabyPhotoDao) context.getBean("babyPhotoDao");
        babyAlbumDao = (BabyAlbumDao) context.getBean("babyAlbumDao");
    }
    private static String baseDir;
    private static boolean debug = false;
    private static boolean enabled = false;
    private static Hashtable allowedExtensions;
    private static Hashtable deniedExtensions;

    /**
     * Initialize the servlet.<br>
     * Retrieve from the servlet configuration the "baseDir" which is the root
     * of the file repository:<br>
     * If not specified the value of "/UserFiles/" will be used.<br>
     * Also it retrieve all allowed and denied extensions to be handled.
     * 
     */
    public void init() throws ServletException {

        debug = (new Boolean(getInitParameter("debug"))).booleanValue();

        if (debug)
            System.out.println("\r\n---- SimpleUploaderServlet initialization started ----");

        enabled = (new Boolean(getInitParameter("enabled"))).booleanValue();
        if (baseDir == null)
            baseDir = "/uploadDir/";
        String realBaseDir = getServletContext().getRealPath(baseDir);
        File baseFile = new File(realBaseDir);
        if (!baseFile.exists()) {
            baseFile.mkdir();
        }

        allowedExtensions = new Hashtable(3);
        deniedExtensions = new Hashtable(3);
        allowedExtensions.put("Image", stringToArrayList(getInitParameter("AllowedExtensionsImage")));
        // deniedExtensions.put("Image",stringToArrayList(getInitParameter("DeniedExtensionsImage")));
        if (debug)
            System.out.println("---- SimpleUploaderServlet initialization completed ----\r\n");

    }

    /**
     * Manage the Upload requests.<br>
     * 
     * The servlet accepts commands sent in the following format:<br>
     * simpleUploader?Type=ResourceType<br>
     * <br>
     * It store the file (renaming it in case a file with the same name exists)
     * and then return an HTML file with a javascript command in it.
     * 
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        if (debug)
            System.out.println("--- BEGIN DOPOST ---");

        response.setContentType("text/html; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        String currentPath = "";
        String currentDirPath = "";
        String typeStr = request.getParameter("Type");
        UserCommonInfo info = null;
        info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.USER_COMMON_INFO);
        if (info == null) {
            info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.ADMIN_INFO);
        }
        currentPath = baseDir + "images/";
        currentDirPath = getServletContext().getRealPath(currentPath);
        if (!(new File(currentDirPath).isDirectory())) {
            new File(currentDirPath).mkdir();
        }
        if (info.getObjectTableName() == null || info.getObjectTableName().equals("")) {
            currentPath += "admin/";
        } else {
            if (info.getObjectTableName().equals(SystemConstant.BABY_INFO_TABLE_NAME)) {
                currentPath += "babyInfo/";
            }
            if (info.getObjectTableName().equals(SystemConstant.KG_TEACHER_INFO_TABLE_NAME)) {
                currentPath += "teacherInfo/";
            }
        }
        currentDirPath = getServletContext().getRealPath(currentPath);
        if (!(new File(currentDirPath).isDirectory())) {
            new File(currentDirPath).mkdir();
        }
        currentPath += info.getId();
        currentDirPath = getServletContext().getRealPath(currentPath);
        if (!(new File(currentDirPath).isDirectory())) {
            new File(currentDirPath).mkdir();
        }
        if (debug)
            System.out.println(currentDirPath);

        String retVal = "0";
        String newName = "";
        String fileUrl = "";
        String errorMessage = "";

        if (enabled) {
            DiskFileUpload upload = new DiskFileUpload();
            try {
                upload.setHeaderEncoding("utf-8");
                List items = upload.parseRequest(request);

                Map fields = new HashMap();

                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField())
                        fields.put(item.getFieldName(), item.getString());
                    else
                        fields.put(item.getFieldName(), item);
                }
                FileItem uplFile = (FileItem) fields.get("NewFile");

                String fileNameLong = uplFile.getName();
                InputStream is = uplFile.getInputStream();
                fileNameLong = fileNameLong.replace('\\', '/');
                String[] pathParts = fileNameLong.split("/");
                String fileName = pathParts[pathParts.length - 1];
                Calendar calendar = Calendar.getInstance();
                String nameWithoutExt = String.valueOf(calendar.getTimeInMillis());
                ;
                String ext = getExtension(fileName);
                fileName = nameWithoutExt + "." + ext;
                fileUrl = currentPath + "/" + fileName;
                if (extIsAllowed(typeStr, ext)) {
                    FileOutputStream desc = new FileOutputStream(currentDirPath + "/" + fileName);
                    changeDimension(is, desc, 450, 1000);
                    if (info.getObjectTableName() != null && !info.getObjectTableName().equals("")) {
                        Photo photo = new Photo();
                        photo.setPhotoName(fileName);
                        PhotoAlbum album = babyAlbumDao.getMAlbumByUser(info.getId(), info.getObjectTableName());
                        if (album.getId() != null) {
                            Long albumId = album.getId();
                            photo.setPhotoAlbumId(albumId);
                            photo.setPhotoLink(fileUrl);
                            photo.setDescription("");
                            photo.setReadCount(0L);
                            photo.setCommentCount(0L);
                            photo.setReadPopedom("1");
                            photo.setCreateTime(DateUtil.getCurrentDateTimestamp());
                            photo.setModifyTime(DateUtil.getCurrentDateTimestamp());
                            babyPhotoDao.save(photo);
                            babyAlbumDao.updateAlbumCount(albumId);
                        }
                    }
                } else {
                    retVal = "202";
                    errorMessage = "";
                    if (debug)
                        System.out.println("?: " + ext);
                }
            } catch (Exception ex) {
                if (debug)
                    ex.printStackTrace();
                retVal = "203";
            }
        } else {
            retVal = "1";
            errorMessage = "??";
        }

        out.println("<script type=\"text/javascript\">");
        out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + request.getContextPath() + fileUrl + "','"
                + newName + "','" + errorMessage + "');");
        out.println("</script>");
        out.flush();
        out.close();

        if (debug)
            System.out.println("--- END DOPOST ---");

    }

    /*
     * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF
     * bug #991489
     */
    private static String getNameWithoutExtension(String fileName) {
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    /*
     * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF
     * bug #991489
     */
    private String getExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    /**
     * Helper function to convert the configuration string to an ArrayList.
     */

    private ArrayList stringToArrayList(String str) {

        if (debug)
            System.out.println(str);
        String[] strArr = str.split("\\|");

        ArrayList tmp = new ArrayList();
        if (str.length() > 0) {
            for (int i = 0; i < strArr.length; ++i) {
                if (debug)
                    System.out.println(i + " - " + strArr[i]);
                tmp.add(strArr[i].toLowerCase());
            }
        }
        return tmp;
    }

    /**
     * Helper function to verify if a file extension is allowed or not allowed.
     */

    private boolean extIsAllowed(String fileType, String ext) {

        ext = ext.toLowerCase();

        ArrayList allowList = (ArrayList) allowedExtensions.get(fileType);
        if (allowList.contains(ext))
            return true;
        else
            return false;
    }

    public static void changeDimension(InputStream bis, FileOutputStream desc, int w, int h) throws IOException {
        Image src = javax.imageio.ImageIO.read(bis); // Image
        int width = src.getWidth(null); // ?
        int height = src.getHeight(null); // ?
        if (width <= w && height <= h) {
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(src, 0, 0, width, height, null); // ??
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(desc);
            encoder.encode(tag);
            desc.flush();
            desc.close();
            bis.close();
        } else {
            if (width != height) {
                if (w * height < h * width) {
                    h = (int) (height * w / width);
                } else {
                    w = (int) (width * h / height);
                }
            }
            BufferedImage tag = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(src, 0, 0, w, h, null); // ??
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(desc);
            encoder.encode(tag);
            desc.flush();
            desc.close();
            bis.close();
        } // JPEG?
    }
}