web.DirectoryaddblobController.java Source code

Java tutorial

Introduction

Here is the source code for web.DirectoryaddblobController.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.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ldap.LdapApi;
import model.Collabrum;
import model.Directory;
import model.Photo;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
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 san.SanException;
import util.*;

/**
 *
 * @author Smitha Gudur (smitha@redbasin.com)
 * @version $Revision: 1.2 $
 */
public class DirectoryaddblobController extends BaseController implements Controller {

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

    /**
     * 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 synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

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

        if (!WebUtil.isLicenseProfessional(login)) {
            return handleError("Cannot manage directory feature in deluxe version.");
        }

        // ***************************************************************************
        // This is the only line of code you need to get all session info initialized!
        // Always be the first line before anything else is done. Add to each controller's
        // handlRequest method. Also remember to extend SessionObject.
        // ***************************************************************************
        outOfSession(request, response);

        if (RegexStrUtil.isNull(login) || (loginInfo == null)) {
            return handleUserpageError("Login/loginInfo is null.");
        }
        String directoryid = request.getParameter(DbConstants.DIRECTORY_ID);

        DirectoryDao directoryDao = (DirectoryDao) daoMapper.getDao(DbConstants.DIRECTORY);
        if (directoryDao == null) {
            return handleError("DirectoryDao null, DirectoryaddblobController, login " + login + " directoryid = "
                    + directoryid);
        }

        /**
        * if the user quota is enabled, check if the user quota is set
             * If the user quota is not yet set, dont allow the user
        * to upload the files.
             * If the user quota is set, check if the user has exceeded the limit for the
        * quota, if he has don't allow the user to upload the files
        */
        String userUsedQuota = null;
        String userQuotaSize = null;
        List userStructureList = null;
        if (WebUtil.isUserQuotaEnabled()) {
            String quotaSize = directoryDao.getQuotaSize(loginInfo.getValue(DbConstants.LOGIN_ID));
            if (RegexStrUtil.isNull(quotaSize) || quotaSize.equals("0")) {
                return handleError("user quota is net yet set, so cannot upload the files");
            } else {
                List qNames = null;
                String[] qTypes = null;
                LdapApi ldapConnection = null;
                try {
                    ldapConnection = new LdapApi();
                    if (ldapConnection == null) {
                        return handleError("ldapConnection is null, UserpageController");
                    }
                } catch (Exception e) {
                    return handleError("error ldapConnection, for login " + login + e.getMessage(), e);
                }

                try {
                    String email = null;
                    if (loginInfo != null) {
                        email = loginInfo.getValue(DbConstants.EMAIL);
                        logger.info("email = " + email);
                    }
                    qNames = ldapConnection.getUserStructure(LdapConstants.ldapAttrMail, email);
                    qTypes = LdapUtil.getQTypes();
                    logger.info("qNames = " + qNames.toString());
                    logger.info("qTypes = " + qTypes[0] + " " + qTypes[1] + " " + qTypes[2] + " " + qTypes[3] + " "
                            + qTypes[4]);
                } catch (Exception e) {
                    return handleError("ldapException, getUserStructure() for login " + login + e.getMessage(), e);
                }

                /**
                 * If directoryid is null or not specified, show the 
                 * top of the directory
                 */
                String quotaMsg = null;
                try {
                    // based on dirname=login
                    Directory directory = null;
                    String directoryId = directoryDao.getDirectoryId(login);
                    if (!RegexStrUtil.isNull(directoryId)) {
                        directory = directoryDao.viewDirectory(directoryId,
                                loginInfo.getValue(DbConstants.LOGIN_ID), login, DbConstants.READ_FROM_SLAVE,
                                DbConstants.BLOB_READ_FROM_SLAVE, DbConstants.WEBSITE_READ_FROM_SLAVE);
                    } else {
                        return handleError("directoryId is null, for dirname=" + login);
                    }
                    String loginId = loginInfo.getValue(DbConstants.LOGIN_ID);
                    userQuotaSize = directoryDao.getQuotaSize(loginId);
                    logger.info("userQuotaSize = " + userQuotaSize);
                    userStructureList = directoryDao.getUserQuotas(loginId, qTypes, qNames,
                            DbConstants.READ_FROM_SLAVE);
                    logger.info("userStructureList = " + userStructureList.toString());

                    try {
                        //SanUtils sanUtils = new SanUtils();
                        //userUsedQuota = sanUtils.getUsedQuota(login, SanConstants.sanPath, directory.getValue(DbConstants.DIRPATH));   
                        String totalSize = directoryDao.getDirUsedQuota(loginInfo.getValue(DbConstants.LOGIN_ID));
                        logger.info("totalSize = " + totalSize);
                        userUsedQuota = LdapUtil.getSizeWithType(totalSize);
                        logger.info("userUsedQuota = " + userUsedQuota);
                    } catch (SanException e) {
                        return handleError("getUsedQuota(),login=" + login + e.getMessage(), e);
                    }
                    try {
                        boolean exceeds = LdapUtil.checkMaxLimit(userQuotaSize, userStructureList, userUsedQuota);
                        logger.info("users's used quota exceeds the quota limit " + exceeds);
                        if (exceeds) {
                            return handleError(login + " exceeds quota, usedQuota=" + userUsedQuota);
                        }
                    } catch (Exception e) {
                        return handleError(
                                "Exception LdapUtil.checkUserQuotaLimit() member " + login + " " + e.getMessage(),
                                e);
                    }
                } catch (Exception e) {
                    return handleError(
                            "Exception login in either viewDirectory()/getUserQuotas() " + login + e.getMessage(),
                            e);
                }
            }
        }

        // remember any request parameters have to be added thru the field list.
        // cannot use request.getParameter in this program.

        boolean isDirectory = false;
        if ((request.getParameter(DbConstants.IS_DIRECTORY) != null)
                && request.getParameter(DbConstants.IS_DIRECTORY).equals((Object) "1")) {
            isDirectory = true;
        }

        String collabrumid = request.getParameter(DbConstants.COLLABRUM_ID);
        if (isDirectory) {
            if (RegexStrUtil.isNull(directoryid)) {
                return handleError("directoryid is null in DirectoryaddblobController");
            }
            directoryid = RegexStrUtil.goodNameStr(directoryid);
        } else {
            if (RegexStrUtil.isNull(collabrumid)) {
                return handleError("collabrumid is null in DirectoryaddblobController");
            }
            collabrumid = RegexStrUtil.goodNameStr(collabrumid);
        }

        Integer blobtype = new Integer(request.getParameter(DbConstants.BLOBTYPE));
        if (blobtype < GlobalConst.categoryMinSize || blobtype > GlobalConst.categoryMaxSize) {
            return handleUserpageError(
                    "category or blobtype is not appropriate type in DirectoryaddblobController");
        }

        byte[] blob = null;
        String mtype = null;
        String btitle = null;
        int zoom = 100;
        List fileList = null;
        DiskFileUpload upload = null;
        try {
            boolean isMultipart = FileUpload.isMultipartContent(request);
            // Create a new file upload handler
            upload = new DiskFileUpload();
            //upload.setSizeMax((long)10000000);
            //upload.setSizeMax(webConstants.getFileuploadsize());
            upload.setSizeMax(GlobalConst.fileUploadSize);

            // Parse the request
            fileList = upload.parseRequest(request);
        } catch (Exception e) {
            return handleError("Exception occurred in uploading the photo file." + e.getMessage(), e);
        }

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

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

        for (int i = 0; i < fileList.size(); i++) {
            FileItem fileItem = (FileItem) fileList.get(i);
            if (fileItem.isFormField()) {
                fileItem.setFieldName(label);
                fieldname = fileItem.getFieldName();
                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 {
                blob = fileItem.get();
                mtype = fileItem.getContentType();
                long maxSize = upload.getSizeMax();
                fileName = fileItem.getName();
                fieldsize = fileItem.getSize();
            }
        }

        logger.info("mtype = " + mtype);
        //logger.info("fileMimeTypes = " + GlobalConst.fileMimeTypes);
        if (RegexStrUtil.isNull(btitle)) {
            btitle = fileName;
        }
        boolean addBlob = true;
        if ((fieldsize <= 0) || (RegexStrUtil.isNull(mtype)) || (RegexStrUtil.isNull(btitle)) || (blob == null)) {
            addBlob = false;
        }

        logger.info("mtype = " + mtype);
        if (addBlob) {
            if (WebUtil.isUserQuotaEnabled()) {
                try {
                    String newUsedQuota = LdapUtil.addUserSize(userUsedQuota, fieldsize);
                    boolean exceeds = LdapUtil.checkMaxLimit(userQuotaSize, userStructureList, newUsedQuota);
                    if (exceeds) {
                        return handleError(login + " file uploading exceeds quota, fileSize=" + fieldsize
                                + " newusedQuota=" + newUsedQuota);
                    } else {
                        logger.info("file upload does not exceed the size fileSize=" + fieldsize + " newUsedQuota="
                                + newUsedQuota);
                    }
                } catch (Exception e) {
                    return handleError(
                            "Exception LdapUtil.addUserSize()/checkMaxLimit() login " + login + e.getMessage(), e);
                }
            }
        }

        /**
        * Donot allow the user to upload the files of these types
        * check if certain types of mime types are excluded 
        * in the xml configuration.
        */
        /*
                String contentType = MimeUtil.mimeType(blob);
           logger.info("contentType = " + contentType);
           mtype = contentType;
        logger.info("mtype = " + mtype);
        */

        if (GlobalConst.isFileMimeTypeEnabled) {
            if (WebUtil.isFileMimeTypeExcluded(mtype)) {
                return handleError(
                        "contentType is not supported in this configuration, to update the support file types, look at the xml configuration in web app. contentType= "
                                + mtype);
            }
        }

        logger.info("addBlob = " + addBlob);

        if (!RegexStrUtil.isNull(btitle)) {
            btitle = RegexStrUtil.goodDirName(btitle);
        }

        String loginid = loginInfo.getValue(DbConstants.LOGIN_ID);

        if (getDaoMapper() == null) {
            return handleError("DaoMapper is null in DirectoryaddblobController");
        }

        /**
         *   get the collabrum dao
         */
        CollabrumDao collDao = null;
        if (!isDirectory) {
            collDao = (CollabrumDao) getDaoMapper().getDao(DbConstants.COLLABRUM);
            if (collDao == null) {
                return handleError("CollabrumDao is null for daoMapper, DirectoryaddblobController");
            }
        }

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

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

        if (isCobrand) {
            if (RegexStrUtil.isNull(ftype)) {
                return handleError("ftype is null for DirectoryaddblobController");
            }
            if (!ftype.equals(DbConstants.COBRAND_HEADER) && !ftype.equals(DbConstants.COBRAND_FOOTER)) {
                return handleError("cobrand filetype is neither a header nor footer DirectoryaddblobController");
            }
        }

        if (isDirectory) {
            if (directoryid.length() > GlobalConst.directoryidSize) {
                return handleError(
                        "directoryid.length() > WebConstants.directoryidSize,in DirectoryaddblobController");
            }
        }

        /**
         *  If the blob information is provided by the user, add the blob
         */
        Directory newDir = null;
        String blobtypeStr = request.getParameter(DbConstants.BLOBTYPE);
        String isOrganizer = "0";
        List tagList = null;
        List photos = null;
        Directory dir = null;
        if (isDirectory) {
            try {
                logger.info("calling viewDirectory");
                dir = directoryDao.viewDirectory(directoryid, loginid, login, DbConstants.READ_FROM_SLAVE,
                        DbConstants.BLOB_READ_FROM_MASTER, DbConstants.WEBSITE_READ_FROM_SLAVE);
            } catch (BaseDaoException e) {
                return handleError("Exception occured in viewDirectory() for directoryid = " + directoryid
                        + " loginid = " + loginid + " ErrorMsg = " + e.getMessage(), e);
            }
            if (dir == null) {
                return handleError("directory is null, viewDirectory() for directoryid = " + directoryid
                        + " loginid = " + loginid);
            }
        }

        /**
        * Blob has to be added either to directory or collabrum 
        */
        if (addBlob) {
            /**
            * addblob to directory and get the new directory 
            */
            logger.info("adding the blob");
            if (isDirectory) {
                DirectoryStreamBlobDao platzBlobDao = (DirectoryStreamBlobDao) getDaoMapper()
                        .getDao(DbConstants.DIR_BLOB);
                if (platzBlobDao == null) {
                    return handleError("DirectoryStreamBlobDao is null for daoMapper");
                }
                try {
                    if (isCobrand) {
                        cobrandDao.addCobrandDirStreamBlob(blob, directoryid, ftype, loginid, login);
                    } else {
                        logger.info("adding stream blob" + btitle);
                        platzBlobDao.addStreamBlob(fieldsize, (int) blobtype, mtype, btitle, blob, zoom, loginid,
                                directoryid, login, usertags, caption, dir.getValue(DbConstants.DIRPATH),
                                dir.getValue(DbConstants.DIRNAME));
                        logger.info("getting the update onthe directory");
                        newDir = directoryDao.viewDirectory(directoryid, loginid, login,
                                DbConstants.READ_FROM_MASTER, DbConstants.BLOB_READ_FROM_MASTER,
                                DbConstants.WEBSITE_READ_FROM_SLAVE);
                        if (blobtype == 1) {
                            tagList = platzBlobDao.getAllTags(directoryid, DbConstants.READ_FROM_MASTER);
                        }
                    }
                } catch (BaseDaoException e) {
                    return handleError("Exception occurred in addBlob() directoryStreamBlob " + e.getMessage(), e);
                }
            } else {
                /**
                      *  addblob to collabrum and get collabrum view
                      */
                if (!RegexStrUtil.isNull(collabrumid)) {
                    try {
                        if (collabrumid.length() > GlobalConst.collabrumidSize) {
                            return handleError("collabrumid.length > WebConstants.collabrumidSize");
                        }
                        if (isCobrand) {
                            cobrandDao.addCollabrumCobrand(blob, collabrumid, ftype, loginid, login);
                        } else {
                            collDao.addStreamBlob(fieldsize, (int) blobtype, mtype, btitle, blob, zoom, loginid,
                                    collabrumid, login, usertags, caption);
                        }
                    } catch (BaseDaoException e) {
                        return handleError("Exception occurred in addStreamBlob() for collabrum " + e.getMessage(),
                                e);
                    }
                }
            }
        }

        /**
        * When the blob could not be added, send the existing directory
        */
        if (newDir == null) {
            newDir = dir;
        }

        Collabrum collabrum = null;
        if (!isDirectory) {
            try {
                collabrum = collDao.viewCollabrum(collabrumid, loginid, login, DbConstants.READ_FROM_SLAVE,
                        DbConstants.BLOB_READ_FROM_MASTER);
                photos = collDao.getBlobsByCategory(collabrumid, blobtypeStr, DbConstants.BLOB_READ_FROM_MASTER);
                if (blobtype == 1) {
                    tagList = collDao.getAllTags(collabrumid, DbConstants.READ_FROM_MASTER);
                }
                if (loginInfo != null) {
                    String loginId = loginInfo.getValue(DbConstants.LOGIN_ID);
                    if (collDao.isOrganizerCollabrum(collabrumid, login, loginId)) {
                        isOrganizer = "1";
                    }
                }
            } catch (BaseDaoException e) {
                return handleError("Exception occurred in viewCollabrum() for collabrum " + e.getMessage(), e);
            }
            if (collabrum == null) {
                return handleError("collabrum is null, viewCollabrum() for collabrum ");
            }
        }

        Directory dirCobrand = null;
        Collabrum collCobrand = null;
        if (isDirectory) {
            try {
                dirCobrand = cobrandDao.getDirCobrand(directoryid);
            } catch (Exception e) {
                return handleError("exception getDirCobrand(), DirectorygetblobController " + e.getMessage(), e);
            }
        } else {
            try {
                collCobrand = cobrandDao.getCollCobrand(collabrumid);
            } catch (Exception e) {
                return handleError("exception getDirCobrand(), DirectorygetblobController " + e.getMessage(), e);
            }
        }

        /**
              *  put the model and view
              */
        StringBuffer sb = new StringBuffer();
        if (tagList != null && tagList.size() > 0) {
            for (int i = 0; i < tagList.size(); i++) {
                Photo photo = (Photo) tagList.get(i);
                if (photo != null) {
                    sb.append(photo.getValue(DbConstants.USER_TAGS));
                    sb.append(" ");
                }
            }
        }

        Map myModel = new HashMap();
        if (isCobrand) {
            String viewName = DbConstants.VIEW_DIRECTORY;
            if (isDirectory) {
                myModel.put(DbConstants.DIRECTORY, newDir);
                myModel.put(DbConstants.COBRAND, dirCobrand);
            } else {
                viewName = DbConstants.VIEW_COLLABRUM;
                myModel.put(DbConstants.COLLABRUM, collabrum);
                myModel.put(DbConstants.COBRAND, collCobrand);
            }
            myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
            myModel.put(DbConstants.USER_PAGE, userpage);
            myModel.put(DbConstants.SHARE_INFO, shareInfo);
            myModel.put(DbConstants.VISITOR_PAGE, memberUserpage);
            myModel.put(DbConstants.LOGIN_INFO, loginInfo);
            myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
            return new ModelAndView(viewName, "model", myModel);
        } else {
            String viewName = null;
            String pageNum = "1";
            if (isDirectory) {
                if (blobtypeStr.equals(DbConstants.FILE_CATEGORY)) {
                    viewName = DbConstants.EDIT_DIR_BLOB_FILE;
                    myModel.put(DbConstants.IS_DIRECTORY, "1");
                } else {
                    viewName = DbConstants.DIR_PHOTO_FOLDER;
                    //viewName = DbConstants.EDIT_DIR_BLOB_FILE;
                    myModel.put(DbConstants.IS_DIRECTORY, "1");
                    myModel.put(DbConstants.USER_TAGS, sb.toString());
                }
                myModel.put(DbConstants.LOGIN_INFO, loginInfo);
                myModel.put(DbConstants.DIRECTORY, newDir);
                myModel.put(DbConstants.DIRECTORY_ID, directoryid);
                myModel.put(DbConstants.PAGE_NUM, pageNum);
                myModel.put(DbConstants.COBRAND, dirCobrand);
                myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
                myModel.put(DbConstants.USER_PAGE, userpage);
                myModel.put(DbConstants.SHARE_INFO, shareInfo);
                myModel.put(DbConstants.VISITOR_PAGE, memberUserpage);
                myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
                myModel.put(DbConstants.SORT_BY, DbConstants.DATEDESC);
                myModel.put(DbConstants.SELECTION, DbConstants.DATE_DESC_STR);
                return new ModelAndView(viewName, "model", myModel);
            } else {
                /** collabrum */
                if (blobtypeStr.equals(DbConstants.FILE_CATEGORY)) {
                    viewName = DbConstants.EDIT_BLOB_FILE;
                } else {
                    viewName = DbConstants.COLL_PHOTO_FOLDER;
                    myModel.put(DbConstants.USER_TAGS, sb.toString());
                }
                if (sb != null) {
                    myModel.put(DbConstants.USER_TAGS, sb.toString());
                }
                myModel.put(DbConstants.LOGIN_INFO, loginInfo);
                myModel.put(viewName, photos);
                myModel.put(DbConstants.COBRAND, collCobrand);
                myModel.put(DbConstants.STYLE, collabrum.getValue(DbConstants.STYLE));
                myModel.put(DbConstants.COL_NAME, collabrum.getValue(DbConstants.NAME));
                myModel.put(DbConstants.IS_ORGANIZER, isOrganizer);
                myModel.put(DbConstants.COLLABRUM_ID, collabrumid);
                myModel.put(DbConstants.PAGE_NUM, pageNum);
                myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
                myModel.put(DbConstants.USER_PAGE, userpage);
                myModel.put(DbConstants.SHARE_INFO, shareInfo);
                myModel.put(DbConstants.VISITOR_PAGE, memberUserpage);
                myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
                return new ModelAndView(viewName, "model", myModel);
            }
        }
    }

    /**
     * BaseDaoModel set by the spring framework. It maps the DAO implementation
     * to the pagetype.
     *
     * @param daoMapper set the BaseDaoModel instance
     */
    public void setDaoMapper(BaseDaoModel daoMapper) {
        this.daoMapper = daoMapper;
    }

    /**
     * BaseDaoModel set by the spring framework. It maps the DAO implementation
     * to the pagetype.
     *
     * @return BaseDaoModel get the BaseDaoModel instance
     */
    public BaseDaoModel getDaoMapper() {
        return daoMapper;
    }

}