com.pureinfo.tgirls.servlet.TestServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.pureinfo.tgirls.servlet.TestServlet.java

Source

/**
 * PureInfo TGirls
 * @(#)TestServlet.java   1.0 2009-3-6
 * 
 * Copyright(c) 2004-2005, PureInfo Information Technology Corp. Ltd. 
 * All rights reserved, see the license file.
 * 
 * www.pureinfo.com.cn
 */

package com.pureinfo.tgirls.servlet;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.pureinfo.ark.ArkHelper;
import com.pureinfo.ark.content.ArkContentHelper;
import com.pureinfo.force.exception.PureException;
import com.pureinfo.force.fileserver.FileFactory;
import com.pureinfo.tfr.cache.core.CacheManager;
import com.pureinfo.tfr.cache.core.IWriteCache;
import com.pureinfo.tgirls.domain.IUserMgr;
import com.pureinfo.tgirls.model.User;
import com.pureinfo.tgirls.sns.constants.APPConstants;
import com.pureinfo.tgirls.utils.servlet.CookieUtils;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class TestServlet extends HttpServlet {
    private Logger logger = Logger.getLogger(this.getClass().getName());

    final long MAX_SIZE_5M = 5000 * 1024;//  5000K

    final long MAX_SIZE_400K = 400 * 1024;

    // ??
    final String[] allowedExt = new String[] { "jpg", "gif", "bmp" };
    private IWriteCache informationWriteCache = CacheManager.getWrite2DBCache("informationSaveCache");

    @Override
    protected void doGet(HttpServletRequest _req, HttpServletResponse _resp) throws ServletException, IOException {
        this.doPost(_req, _resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("=================parameter from request====================");
        Enumeration ereq = request.getParameterNames();
        while (ereq.hasMoreElements()) {
            String name = (String) ereq.nextElement();
            System.out.println(name + "[" + request.getParameter(name) + "]");
        }
        System.out.println("=================end====================");

        String userTabaoId = request.getParameter("id");

        if (StringUtils.isEmpty(userTabaoId)) {
            userTabaoId = "1";
        }
        try {
            IUserMgr mgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
            User _loginUser = mgr.getUserByTaobaoId(userTabaoId);

            addCookie(_loginUser, request, response);

            Cookie[] cookies = request.getCookies();

            if (cookies == null) {
                System.out.println("=====cookie is null=======");
            } else {
                for (int i = 0; i < cookies.length; i++) {
                    Cookie cookie = cookies[i];
                    System.out.println("cookie[" + i + "]:[" + cookie.getName() + ":" + cookie.getValue() + "("
                            + cookie.getMaxAge() + ")]");
                }

            }

            //request.getSession().setAttribute(ArkHelper.ATTR_LOGIN_USER, _loginUser);

            System.out.println("loginuser:" + _loginUser);

            response.sendRedirect(request.getContextPath());
            return;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace(System.err);
        }

    }

    private void addCookie(User _loginUser, HttpServletRequest _request, HttpServletResponse _response)
            throws UnsupportedEncodingException {
        Cookie name = new Cookie(CookieUtils.NAME, URLEncoder.encode(_loginUser.getName(), "utf-8"));
        Cookie nickName = new Cookie(CookieUtils.NICK_NAME, URLEncoder.encode(_loginUser.getNickname(), "utf-8"));
        Cookie taobaoId = new Cookie(CookieUtils.TAOBAO_ID, URLEncoder.encode(_loginUser.getTaobaoID(), "utf-8"));
        Cookie img = new Cookie(CookieUtils.HEAD_IMG, URLEncoder.encode(_loginUser.getHeadImg(), "utf-8"));
        //Cookie topsession = new Cookie(CookieUtils.TOP_SESSION_ID, _request.getParameter(APPConstants.REQ_PARAMETER_SESSION));

        //name.setPath("/");
        //nickName.setPath(_request.getContextPath());

        _response.addCookie(name);
        _response.addCookie(nickName);
        _response.addCookie(taobaoId);
        _response.addCookie(img);

    }

    private File uploadFile(HttpServletRequest request) throws Exception {
        // ,??ServletFileUpload
        DiskFileItemFactory dfif = new DiskFileItemFactory();
        dfif.setSizeThreshold(4096);// ?,4K.
        String tempfilepath = FileFactory.getInstance().lookupPathConfigByFlag("UP", true).getLocalPath();
        dfif.setRepository(new File(tempfilepath));// 

        // 
        ServletFileUpload sfu = new ServletFileUpload(dfif);
        sfu.setHeaderEncoding("utf-8");
        // 
        //sfu.setSizeMax(MAX_SIZE_5M);

        // PrintWriter out = response.getWriter();
        // request  
        List fileList = null;
        try {
            fileList = sfu.parseRequest(request);
        } catch (FileUploadException e) {// ?
            logger.error("FileUploadException", e);
            if (e instanceof SizeLimitExceededException) {
                throw new Exception("?:" + MAX_SIZE_5M / 1024 + "K");
            }
        }
        // 
        if (fileList == null || fileList.size() == 0) {
            throw new Exception("");
        }
        // 
        Iterator fileItr = fileList.iterator();
        // ?
        while (fileItr.hasNext()) {
            FileItem fileItem = null;
            String path = null;
            long size = 0;
            // ?
            fileItem = (FileItem) fileItr.next();
            // ?form?(<input type="text" />)

            if (fileItem == null || fileItem.isFormField()) {
                continue;
            }
            // 
            path = fileItem.getName();

            logger.debug("path:" + path);

            // ?
            size = fileItem.getSize();
            if ("".equals(path) || size == 0) {
                throw new Exception("");
            }

            // ??
            String t_name = path.substring(path.lastIndexOf("\\") + 1);
            // ??(????)
            String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);

            logger.debug("the file ext name:" + t_ext);

            // ???
            int allowFlag = 0;
            int allowedExtCount = allowedExt.length;
            for (; allowFlag < allowedExtCount; allowFlag++) {
                if (allowedExt[allowFlag].equals(t_ext.toLowerCase()))
                    break;
            }
            if (allowFlag == allowedExtCount) {
                String error = ":";
                for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
                    error += "*." + allowedExt[allowFlag] + "  ";
                throw new Exception(error);
            }

            // ?
            String u_name = FileFactory.getInstance().getNextFileName("UP", t_ext, true);
            File temp = new File(u_name);

            int[] imgSize = getimgSize(fileItem);
            if ((imgSize[0] > 0 && imgSize[0] < 300) || (imgSize[1] > 0 && imgSize[1] < 300)) {
                throw new Exception("300x300");
            }

            logger.debug("to write file:" + temp);

            // ?
            fileItem.write(temp);

            temp = resizePic(temp);
            return temp;

        }

        throw new Exception("");

    }

    private File resizePic(File _file) {
        File temp = _file;
        long filesize = temp.length();

        logger.debug("file[" + temp + "]size:" + filesize);

        FileFactory ff = FileFactory.getInstance();
        String jpgfile;
        if (filesize <= MAX_SIZE_400K) {
            return temp;
        }

        for (int i = 9; i > 1; i--) {
            try {
                jpgfile = ff.getNextFileName("UP", "jpg", true);
                BufferedImage output = null;
                output = getImg(temp, i / 10.0f);

                writeJpg(output, jpgfile);
                temp = new File(jpgfile);
                filesize = temp.length();
                logger.debug("to jpg file[" + temp.getName() + "] size[" + filesize + "]");
                if (filesize <= MAX_SIZE_400K) {
                    return temp;
                }

            } catch (PureException e) {
                // TODO Auto-generated catch block
                e.printStackTrace(System.err);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace(System.err);
            }

        }

        return temp;
    }

    private BufferedImage getImg(File _temp, float _i) throws IOException {
        BufferedImage output;
        Image img = ImageIO.read(_temp);
        int width = img.getWidth(null);
        int height = img.getHeight(null);

        Float f = width * _i;
        width = f.intValue();
        f = height * _i;
        height = f.intValue();

        output = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = output.getGraphics();
        g.drawImage(img, 0, 0, width, height, null);
        g.dispose();
        return output;
    }

    private void writeJpg(BufferedImage _output, String _jpgfile) throws ImageFormatException, IOException {

        FileOutputStream out = new FileOutputStream(_jpgfile);
        try {
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(_output);
            param.setQuality(0.8f, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(_output);
        } finally {
            out.close();
        }
    }

    private int[] getimgSize(FileItem _fileItem) {
        try {
            logger.debug("to calc img width and height.");

            Image image = ImageIO.read(_fileItem.getInputStream());
            int[] s = new int[2];
            s[0] = image.getWidth(null);
            s[1] = image.getHeight(null);

            logger.debug("width[" + s[0] + "] height[" + s[1] + "]");

            return s;
        } catch (Exception e) {
            logger.error("error when calc image size.", e);
            return new int[] { -1, -1 };
        }
    }

}