web.ZipUploadController.java Source code

Java tutorial

Introduction

Here is the source code for web.ZipUploadController.java

Source

/**
* Copyright (c) 2001-2012 "Redbasin Networks, INC" [http://redbasin.org]
*
* This file is part of Redbasin OpenDocShare community project.
*
* Redbasin OpenDocShare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package web;

import dao.BaseDaoException;
import dao.CarryonDao;
import dao.CobrandDao;
import dao.DisplaypageDao;
import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Displaypage;
import model.Userpage;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import util.*;

/**
 * This controller is invoked when the author presses the Upload
 *
 */
public class ZipUploadController extends BaseController implements Controller {

    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

    private volatile Long maxRequestSize;
    private volatile String tempDirectory;
    private volatile Integer maxMemorySize;
    private volatile MimeMap mimeMap;
    private volatile ValidateImage validImage;
    private volatile TraversalZipTool zipUtil;
    private volatile Integer defaultWidth;
    private volatile Integer defaultHeight;

    /**
     * This method is called by the spring framework. The configuration
     * for this controller to be invoked is based on the pagetype and
     * is set in the urlMapping property in the spring config file.
     *
     * @param request the <code>HttpServletRequest</code>
     * @param response the <code>HttpServletResponse</code>
     * @throws ServletException
     * @throws IOException
     * @return ModelAndView this instance is returned to spring
     */
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            ModelAndView modelAndView = super.handleRequest(request, response);
        } catch (Exception e) {
            return handleError("error in handleRequest", e);
        }

        outOfSession(request, response);

        if (RegexStrUtil.isNull(login) && RegexStrUtil.isNull(member)) {
            return handleUserpageError("Login & member are null.");
        }

        String category = request.getParameter(DbConstants.CATEGORY);
        boolean isCobrand = false;
        if (!RegexStrUtil.isNull(request.getParameter(DbConstants.IS_COBRAND))) {
            isCobrand = request.getParameter(DbConstants.IS_COBRAND).equals((Object) "1");
        }

        if ((!RegexStrUtil.isNull(category) && category.equals(DbConstants.FILE_CATEGORY)) || isCobrand) {
            if (!WebUtil.isLicenseProfessional(login)) {
                return handleError(
                        "Cannot access user carryon features or cobrand user in deluxe version." + login);
            }
        }
        if (RegexStrUtil.isNull(category)) {
            return handleError("category is null in CarryonupdateController. " + login);
        }

        if (daoMapper == null) {
            return handleError("DaoMapper is null in carryon update.");
        }

        CarryonDao carryonDao = (CarryonDao) daoMapper.getDao(DbConstants.CARRYON);
        if (carryonDao == null) {
            return handleError("CarryonDao is null for carryon update.");
        }

        byte[] blob = null;
        String mtype = null;
        if (!RegexStrUtil.isNull(category)) {
            int catVal = new Integer(category).intValue();
            if (catVal < GlobalConst.categoryMinSize || catVal > GlobalConst.categoryMaxSize) {
                return handleError("category values are not correct" + catVal);
            }
        }

        CobrandDao cobrandDao = (CobrandDao) daoMapper.getDao(DbConstants.COBRAND);
        if (cobrandDao == null) {
            return handleError("cobrandDao is null for CarryonupdateController");
        }

        DisplaypageDao displayDao = (DisplaypageDao) daoMapper.getDao(DbConstants.DISPLAY_PAGE);
        if (displayDao == null) {
            return handleError("displayDao is null for CarryonupdateController");
        }

        Displaypage displaypage = null;
        Userpage cobrand = null;
        try {
            displaypage = displayDao.getDisplaypage(login, DbConstants.READ_FROM_SLAVE);
            cobrand = cobrandDao.getUserCobrand(loginInfo.getValue(DbConstants.LOGIN_ID));
        } catch (BaseDaoException e) {
            return handleError("Exception occurred in getDisplaypage() for login " + login, e);
        }

        System.setProperty("jmagick.systemclassloader", "no");

        List fileList = null;
        ServletFileUpload upload = null;
        try {
            // Check that we have a file upload request
            boolean isMultipart = FileUpload.isMultipartContent(request);
            if (isMultipart) {
                // Create a factory for disk-based file items
                DiskFileItemFactory factory = new DiskFileItemFactory();

                // Set factory constraints
                factory.setSizeThreshold(maxMemorySize.intValue());
                //factory.setRepository(new File(tempDirectory));

                // Create a new file upload handler
                upload = new ServletFileUpload(factory);

                // Set overall request size constraint
                upload.setSizeMax(maxRequestSize.longValue());

                // Parse the request
                fileList = upload.parseRequest(request);

                long fieldsize = 0;
                String fieldname, fieldvalue;
                fieldname = fieldvalue = null;

                // educate the fieldnames to this form by using the setFieldName()
                String label = "btitle";
                String caption = "";
                String tagsLabel = DbConstants.USER_TAGS;
                String fileName = null;
                String usertags = null;
                String btitle = null;

                // Process the uploaded items
                Iterator iter = fileList.iterator();
                while (iter.hasNext()) {
                    FileItem fileItem = (FileItem) iter.next();
                    if (fileItem.isFormField()) {
                        fileItem.setFieldName(label);
                        fieldname = fileItem.getFieldName();
                        logger.info("fieldname = " + fieldname);
                        if (fieldname.equalsIgnoreCase(DbConstants.USER_TAGS)) {
                            usertags = fileItem.getString();
                            label = "";
                        } else {
                            if (fieldname.equalsIgnoreCase("btitle")) {
                                btitle = fileItem.getString();
                                label = DbConstants.CAPTION;
                            } else {
                                if (fieldname.equalsIgnoreCase("caption")) {
                                    caption = fileItem.getString();
                                    label = DbConstants.USER_TAGS;
                                } else {
                                    fieldvalue = fileItem.getString();
                                }
                            }
                        }
                    } else {
                        logger.info("contentType = " + fileItem.getContentType());
                        if (fileItem.getContentType().contains("zip")) {
                            List entries = zipUtil.getEntries(fileItem.get());
                            logger.info("num entries = " + entries.size());
                            Iterator iter1 = entries.iterator();
                            while (iter1.hasNext()) {
                                Media media = (Media) iter1.next();
                                blob = media.getData();
                                mtype = mimeMap.getMimeType(zipUtil.getSuffix(media.getName()));
                                fileName = media.getName();
                                fieldsize = media.getData().length;
                                if (RegexStrUtil.isNull(btitle)) {
                                    btitle = fileName;
                                }
                                if ((fieldsize <= 0) || (RegexStrUtil.isNull(mtype))
                                        || (RegexStrUtil.isNull(btitle)) || (blob == null)) {
                                    return handleError(
                                            "fieldsize/mtype/btitle/blob one of them is empty, cannot upload files.");
                                }
                                if (!isCobrand) {
                                    if (btitle.length() > GlobalConst.blobTitleSize) {
                                        btitle = btitle.substring(0, GlobalConst.blobTitleSize);
                                    }
                                    int zoom = 100;
                                    if (!RegexStrUtil.isNull(usertags)) {
                                        if (usertags.length() > GlobalConst.usertagsSize) {
                                            usertags = usertags.substring(0, GlobalConst.usertagsSize);
                                        }
                                        usertags = RegexStrUtil.goodText(usertags);
                                    }
                                    if (!RegexStrUtil.isNull(caption)) {
                                        if (caption.length() > GlobalConst.refererSize) {
                                            caption = caption.substring(0, GlobalConst.refererSize);
                                        }
                                        caption = RegexStrUtil.goodText(caption);
                                    }
                                    boolean publishPhoto = displayDao.getDisplayPhotos(login,
                                            DbConstants.READ_FROM_SLAVE);
                                    carryonDao.addCarryon(fieldsize, category, mtype, RegexStrUtil.goodText(btitle),
                                            blob, zoom, loginInfo.getValue(DbConstants.LOGIN_ID), login, usertags,
                                            caption, publishPhoto);

                                }
                            }
                        } else {
                            if (!validImage.isValid(fileItem.getContentType())) {
                                logger.warn("Found unexpected content type in upload, ignoring  "
                                        + fileItem.getContentType());
                                continue;
                            }
                            logger.debug("Is not a form field");
                            blob = fileItem.get();
                            mtype = fileItem.getContentType();
                            fileName = fileItem.getName();
                            fieldsize = fileItem.getSize();
                            if (RegexStrUtil.isNull(btitle)) {
                                btitle = fileName;
                            }
                            if ((fieldsize <= 0) || (RegexStrUtil.isNull(mtype)) || (RegexStrUtil.isNull(btitle))
                                    || (blob == null)) {
                                return handleError(
                                        "fieldsize/mtype/btitle/blob one of them is empty, cannot upload files.");
                            }
                            if (isCobrand)
                                break;
                            if (!isCobrand) {
                                if (btitle.length() > GlobalConst.blobTitleSize) {
                                    btitle = btitle.substring(0, GlobalConst.blobTitleSize);
                                }
                                int zoom = 100;
                                if (!RegexStrUtil.isNull(usertags)) {
                                    if (usertags.length() > GlobalConst.usertagsSize) {
                                        usertags = usertags.substring(0, GlobalConst.usertagsSize);
                                    }
                                    usertags = RegexStrUtil.goodText(usertags);
                                }
                                if (!RegexStrUtil.isNull(caption)) {
                                    if (caption.length() > GlobalConst.refererSize) {
                                        caption = caption.substring(0, GlobalConst.refererSize);
                                    }
                                    caption = RegexStrUtil.goodText(caption);
                                }
                                boolean publishPhoto = displayDao.getDisplayPhotos(login,
                                        DbConstants.READ_FROM_SLAVE);
                                carryonDao.addCarryon(fieldsize, category, mtype, RegexStrUtil.goodText(btitle),
                                        blob, zoom, loginInfo.getValue(DbConstants.LOGIN_ID), login, usertags,
                                        caption, publishPhoto);

                            }
                        }
                    }
                }
            } else {
                return handleError("Did not get a multipart request");
            }
        } catch (Exception e) {
            return handleError("Exception occurred in addCarryon/addCobrandUserStreamBlo()", e);
        }

        if (isCobrand) {
            try {
                String ftype = request.getParameter(DbConstants.TYPE);
                if (RegexStrUtil.isNull(ftype)) {
                    return handleError("ftype is null, CarryonUpdateController() ");
                }
                if (ftype.equals(DbConstants.COBRAND_HEADER) || ftype.equals(DbConstants.COBRAND_FOOTER)) {
                    cobrandDao.addUserCobrand(blob, ftype, loginInfo.getValue(DbConstants.LOGIN_ID), login);
                } else {
                    return handleError("cobrand type is not a header or footer in CarryonUpdateController ");
                }
            } catch (BaseDaoException e) {
                return handleError("Exception occurred in addCobrandUserStreamBlo()", e);
            }
        }

        /**
        * list the files
        */
        String loginId = loginInfo.getValue(DbConstants.LOGIN_ID);
        List carryon = null;
        List tagList = null;
        HashSet tagSet = null;
        try {
            carryon = carryonDao.getCarryonByCategory(loginId, category, DbConstants.READ_FROM_MASTER);
            tagList = carryonDao.getTags(loginId, DbConstants.READ_FROM_MASTER);
            tagSet = carryonDao.getUniqueTags(tagList);
        } catch (BaseDaoException e) {
            return handleError(
                    "Exception occurred in getCarryonByCategory()/getTags carryon update for login " + login, e);
        }

        /**
        * display information about the files, if the category of the blobs is files category(1)
        */
        String viewName = DbConstants.EDIT_PHOTOS;
        if (category.equals(DbConstants.FILE_CATEGORY)) {
            viewName = DbConstants.EDIT_FILES;
        }

        Map myModel = new HashMap();
        myModel.put(viewName, carryon);
        myModel.put(DbConstants.COBRAND, cobrand);
        if (tagSet != null) {
            myModel.put(DbConstants.USER_TAGS, RegexStrUtil.goodText(tagSet.toString()));
        }
        myModel.put(DbConstants.LOGIN_INFO, loginInfo);
        myModel.put(DbConstants.DISPLAY_PAGE, displaypage);
        myModel.put(DbConstants.USER_PAGE, userpage);
        myModel.put(DbConstants.SHARE_INFO, shareInfo);
        myModel.put(DbConstants.VISITOR_PAGE, memberUserpage);
        myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
        myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
        return new ModelAndView(viewName, "model", myModel);
    }

    /**
     * MaxRequestSize set by the spring framework.
     *
     * @param maxRequestSize set the max request size
     */
    public void setMaxRequestSize(Long maxRequestSize) {
        this.maxRequestSize = maxRequestSize;
    }

    /**
     * MaxMemorySize set by the spring framework.
     *
     * @param maxMemorySize set the max memory size
     */
    public void setMaxMemorySize(Integer maxMemorySize) {
        this.maxMemorySize = maxMemorySize;
    }

    /**
     * mimeMap set by the spring framework.
     *
     * @param mimeMap
     */
    public void setMimeMap(MimeMap mimeMap) {
        this.mimeMap = mimeMap;
    }

    /**
     * validImage set by the spring framework.
     *
     * @param validImage
     */
    public void setValidImage(ValidateImage validImage) {
        this.validImage = validImage;
    }

    /**
     * zipUtil set by the spring framework.
     *
     * @param zipUtil
     */
    public void setZipUtil(TraversalZipTool zipUtil) {
        this.zipUtil = zipUtil;
    }

    /**
     * defaultWidth set by the spring framework.
     *
     * @param defaultWidth
     */
    public void setDefaultWidth(Integer defaultWidth) {
        this.defaultWidth = defaultWidth;
    }

    /**
     * defaultHeight set by the spring framework.
     *
     * @param defaultHeight
     */
    public void setDefaultHeight(Integer defaultHeight) {
        this.defaultHeight = defaultHeight;
    }
}