alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/admin/CompanyWebHandler.java,v 1.37 2005/01/26 18:46:50 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.37 $
 * $Date: 2005/01/26 18:46:50 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program 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 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Tran Van Giang trangiang1605@users.sourceforge.net
 * @author: Minh Nguyen    minhnn@MyVietnam.net
 */
package com.mvnforum.admin;

import java.io.*;
import java.sql.Timestamp;
import java.util.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import com.mvnforum.MVNForumGlobal;
import com.mvnforum.MVNForumResourceBundle;
import com.mvnforum.MyUtil;
import com.mvnforum.auth.*;
import com.mvnforum.db.CompanyBean;
import com.mvnforum.db.DAOFactory;
import com.mvnforum.search.company.CompanyIndexer;
import com.mvnforum.search.company.CompanySearchQuery;
import net.myvietnam.mvncore.exception.*;
import net.myvietnam.mvncore.fileupload.*;
import net.myvietnam.mvncore.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

class CompanyWebHandler {

    private static Log log = LogFactory.getLog(CompanyWebHandler.class);

    private OnlineUserManager onlineUserManager = OnlineUserManager.getInstance();

    CompanyWebHandler() {
    }

    void processAdd(ServletContext context, HttpServletRequest request)
        throws BadInputException, ObjectNotFoundException, CreateException, DatabaseException, DuplicateKeyException,
        ForeignKeyNotFoundException, AuthenticationException, AssertionException, IOException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanAdminSystem();

        Timestamp now = DateUtil.getCurrentGMTTimestamp();

        String companyName              = ParamUtil.getParameterSafe(request, "CompanyName", true);
        String companyAddress           = ParamUtil.getParameterSafe(request, "CompanyAddress", false);
        String companyCity              = ParamUtil.getParameterSafe(request, "CompanyCity", false);
        String companyCAP               = ParamUtil.getParameterSafe(request, "CompanyCAP", false);
        String companyProvince          = ParamUtil.getParameterSafe(request, "CompanyProvince", false);
        String companyRegion            = ParamUtil.getParameterSafe(request, "CompanyRegion", false);
        String companyPhone             = ParamUtil.getParameterSafe(request, "CompanyPhone", false);
        String companyFax               = ParamUtil.getParameterSafe(request, "CompanyFax", false);
        String companyWebsite           = ParamUtil.getParameterUrl(request, "CompanyWebsite");
        String companyEmail             = ParamUtil.getParameterEmail(request, "CompanyEmail");
        String companySpaceName         = ParamUtil.getParameterSafe(request, "CompanySpaceName", true);
        String companySpaceHeader       = ParamUtil.getParameterSafe(request, "CompanySpaceHeader", false);
        String companySpaceFooter       = ParamUtil.getParameterSafe(request, "CompanySpaceFooter", false);
        String companyVATNumber         = ParamUtil.getParameterSafe(request, "CompanyVATNumber", true);
        String companyLogo              = "";
        String companyCss               = "";
        Timestamp companyCreationDate   = now;
        Timestamp companyModifiedDate   = now;

        // First, check the alternate key of Company, ensure things is okie before adding Group
        try {
            //Check if alternate key already exists
            DAOFactory.getCompanyDAO().findByAlternateKey_CompanyName(companyName);
            //If so, then we have to throw an exception
            throw new DuplicateKeyException("Alternate key already exists. Cannot create new Company with the same <CompanyName> (" + companyName + ").");
        } catch(ObjectNotFoundException e) {
            //Otherwise we can go ahead
        }

        try {
            //Check if alternate key already exists
            DAOFactory.getCompanyDAO().findByAlternateKey_CompanyEmail(companyEmail);
            //If so, then we have to throw an exception
            throw new DuplicateKeyException("Alternate key already exists. Cannot create new Company with the same <CompanyEmail> (" + companyEmail + ").");
        } catch(ObjectNotFoundException e) {
            //Otherwise we can go ahead
        }

        try {
            //Check if alternate key already exists
            DAOFactory.getCompanyDAO().findByAlternateKey_CompanySpaceName(companySpaceName);
            //If so, then we have to throw an exception
            throw new DuplicateKeyException("Alternate key already exists. Cannot create new Company with the same <CompanySpaceName> (" + companySpaceName + ").");
        } catch(ObjectNotFoundException e) {
            //Otherwise we can go ahead
        }

        // Next, create group for this company
        String groupName        = MVNForumGlobal.COMPANY_GROUP_FREFIX + companyName;
        String groupDesc        = "This is the default generated group for company " + companyName;
        int groupOption         = 0;//@todo review it later

        DAOFactory.getGroupsDAO().create(""/*groupOwnerName*/, groupName, groupDesc,
                               groupOption, now/*groupCreationDate*/, now/*groupModifiedDate*/);

        int groupID = DAOFactory.getGroupsDAO().getGroupIDFromGroupName(groupName);

        // Finally, create the company now
        DAOFactory.getCompanyDAO().create(groupID, companyName, companyAddress,
                                companyCity, companyCAP, companyProvince,
                                companyRegion, companyPhone, companyFax,
                                companyWebsite, companyEmail, companySpaceName,
                                companySpaceHeader, companySpaceFooter, companyVATNumber,
                                companyLogo, companyCss, companyCreationDate,
                                companyModifiedDate);

        // create new folder for the company by companyID
        int companyID = DAOFactory.getCompanyDAO().getCompanyIDFromCompanyEmail(companyEmail);

        StringBuffer bufferCompanyFolder = new StringBuffer(128);
        bufferCompanyFolder.append(context.getRealPath(MVNForumGlobal.UPLOADED_COMPANY_DIR));
        bufferCompanyFolder.append(File.separatorChar).append(companyID);
        String companyFolder = bufferCompanyFolder.toString();
        FileUtil.createDir(companyFolder, true);

        // now, add to the Search Index
        CompanyBean justAddedCompanyBean = null;
        try {
            justAddedCompanyBean = DAOFactory.getCompanyDAO().getCompany(companyID);
        } catch (ObjectNotFoundException e) {
            Locale locale = I18nUtil.getLocaleInRequest(request);
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.companyid_not_exists", new Object[] {new Integer(companyID)});
            throw new ObjectNotFoundException(localizedMessage);
        }

        CompanyIndexer.scheduleAddCompanyTask(justAddedCompanyBean);
    }

    void prepareView(HttpServletRequest request)
        throws BadInputException, ObjectNotFoundException, DatabaseException,
        AssertionException, AuthenticationException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanAdminSystem();

        String strCompanyID = ParamUtil.getParameter(request, "companyid", false);
        String strCompanyEmail = ParamUtil.getParameter(request, "companyemail", false);
        String strCompanyCreationDate = ParamUtil.getParameter(request, "companycreationdate", false);

        int companyID = 0;

        Locale locale = I18nUtil.getLocaleInRequest(request);

        if (strCompanyID.length() > 0) {
            companyID = ParamUtil.getParameterInt(request, "companyid");
        } else if (strCompanyEmail.length() > 0) {
            String companyEmail = ParamUtil.getParameterEmail(request, "companyemail"); // check for better security
            try {
                companyID = DAOFactory.getCompanyDAO().getCompanyIDFromCompanyEmail(companyEmail);
            } catch (ObjectNotFoundException e) {
                String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.company_not_exists.with_email", new Object[] {companyEmail});
                throw new ObjectNotFoundException(localizedMessage);
            }
        } else if (strCompanyCreationDate.length() > 0) {
            java.util.Date companyCreationDate = ParamUtil.getParameterDateUtil(request, "companycreationdate");
            try {
                companyID = DAOFactory.getCompanyDAO().getCompanyIDFromCompanyCreationDate(companyCreationDate);
            } catch (ObjectNotFoundException e) {
                String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.company_not_exists.with_creationdate", new Object[] {strCompanyCreationDate});
                throw new ObjectNotFoundException(localizedMessage);
            }
        } else {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_get_info_to_view_company");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Cannot get the information to view company.");
        }
        CompanyBean companyBean = null;
        try {
            companyBean = DAOFactory.getCompanyDAO().getCompany(companyID);
        } catch (ObjectNotFoundException e) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.companyid_not_exists", new Object[] {new Integer(companyID)});
            throw new ObjectNotFoundException(localizedMessage);
        }

        request.setAttribute("CompanyBean", companyBean);
    }

    void processUpdateCompanyInfo(HttpServletRequest request)
        throws BadInputException, DatabaseException, ObjectNotFoundException,
        DuplicateKeyException, AuthenticationException, AssertionException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanAdminSystem();

        Timestamp now = DateUtil.getCurrentGMTTimestamp();

        int    companyID                = ParamUtil.getParameterInt(request,"companyid");
        String companyName              = ParamUtil.getParameterSafe(request, "CompanyName", true);
        String companyAddress           = ParamUtil.getParameterSafe(request, "CompanyAddress", false);
        String companyCity              = ParamUtil.getParameterSafe(request, "CompanyCity", false);
        String companyCAP               = ParamUtil.getParameterSafe(request, "CompanyCAP", false);
        String companyProvince          = ParamUtil.getParameterSafe(request, "CompanyProvince", false);
        String companyRegion            = ParamUtil.getParameterSafe(request, "CompanyRegion", false);
        String companyPhone             = ParamUtil.getParameterSafe(request, "CompanyPhone", false);
        String companyFax               = ParamUtil.getParameterSafe(request, "CompanyFax", false);
        String companyWebsite           = ParamUtil.getParameterUrl(request, "CompanyWebsite");
        String companyEmail             = ParamUtil.getParameterEmail(request, "CompanyEmail");
        String companySpaceName         = ParamUtil.getParameterSafe(request, "CompanySpaceName", true);
        String companySpaceHeader       = ParamUtil.getParameterSafe(request,"CompanySpaceHeader", false);
        String companySpaceFooter       = ParamUtil.getParameterSafe(request, "CompanySpaceFooter", false);
        String companyVATNumber         = ParamUtil.getParameterSafe(request, "CompanyVATNumber", true);

        DAOFactory.getCompanyDAO().updateCompanyInfo(companyID,
                                                     companyName,
                                                     companyAddress,
                                                     companyCity,
                                                     companyCAP,
                                                     companyProvince,
                                                     companyRegion,
                                                     companyPhone,
                                                     companyFax,
                                                     companyWebsite,
                                                     companyEmail,
                                                     companySpaceName,
                                                     companySpaceHeader,
                                                     companySpaceFooter,
                                                     companyVATNumber,
                                                     now/*companyModifiedDate*/);
        CompanyBean companyBean = null;
        try {
            companyBean = DAOFactory.getCompanyDAO().getCompany(companyID);
        } catch (ObjectNotFoundException e) {
            Locale locale = I18nUtil.getLocaleInRequest(request);
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.companyid_not_exists", new Object[] {new Integer(companyID)});
            throw new ObjectNotFoundException(localizedMessage);
        }
        request.setAttribute("CompanyBean", companyBean);

        // Next, create group for this company
        int groupID      = companyBean.getGroupID();
        String groupName = MVNForumGlobal.COMPANY_GROUP_FREFIX + companyName;
        String groupDesc = "This is the default generated group for company " + companyName;

        DAOFactory.getGroupsDAO().update(groupID, groupName, groupDesc, now/*groupModifiedDate*/);

        // now update the search index
        CompanyIndexer.scheduleUpdateCompanyTask(companyBean);
    }

    void processChangeLogo(ServletContext context, HttpServletRequest request)
        throws BadInputException, AuthenticationException, IOException,
        AssertionException, ObjectNotFoundException, DatabaseException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanAdminSystem();

        Locale locale = I18nUtil.getLocaleInRequest(request);

        // primary key column(s)
        int companyID = ParamUtil.getParameterInt(request, "companyid");
        FileUpload fileUpload = new FileUpload();
        fileUpload.setSizeMax(70000);//70K
        fileUpload.setSizeThreshold(100000);// max memory used = 100K (more than needed)

        List fileItems;
        try {
            fileItems = fileUpload.parseRequest(request);
        } catch (FileUploadException ex) {
            log.error("Cannot upload", ex);
            String localizedMessage = MVNForumResourceBundle.getString(locale, "java.io.IOException.cannot_upload", new Object[] {ex.getMessage()});
            throw new IOException(localizedMessage);
            //throw new IOException("Cannot upload. Detailed reason: " + ex.getMessage());
        }

        // make sure only one file upload
        if (fileItems.size() != 1) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_upload_more_than_one", new Object[] {"logo"});
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Assertion: Cannot upload more than 1 file while processing upload logo file for company.");
        }

        //get the first and only file
        FileItem myFile = (FileItem)fileItems.get(0);
        if (myFile.isFormField() == true) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_process_uploaded_file_with_a_form_field", new Object[] {"logo"});
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Cannot process uploaded company logo file with a form field.");
        }

        // now everything all right, go ahead and create logo
        InputStream inputStream = myFile.getInputStream();

        StringBuffer bufferPicFile = new StringBuffer(128);
        bufferPicFile.append(context.getRealPath(MVNForumGlobal.UPLOADED_COMPANY_DIR));
        bufferPicFile.append(File.separatorChar).append(companyID);

        String companyDir =  bufferPicFile.toString();
        FileUtil.createDirs(companyDir, true/*ignore if exist*/);

        bufferPicFile.append("/").append("logo.jpg");
        String logoFile =  bufferPicFile.toString();

        log.trace("uploaded file = " + logoFile);

        //The below method closes the inputStream after it have done its work.
        ImageUtil.createThumbnail(inputStream, logoFile, 500/*maxWidth*/, 500/*maxHeight*/);// can throw BadInputException

        // now the image has been save, go ahead and update database
        StringBuffer bufferVirtualFile = new StringBuffer(128);
        bufferVirtualFile.append(MVNForumGlobal.UPLOADED_COMPANY_DIR);
        bufferVirtualFile.append("/").append(companyID).append("/").append("logo.jpg");
        String virtualFile =  bufferVirtualFile.toString();

        try {
            DAOFactory.getCompanyDAO().updateCompanyLogo(companyID, virtualFile);
        } catch (DatabaseException ex) {// we dont need to catch ObjectNotFoundException since the companyID is already exits
            log.fatal("Assertion in CompanyWebHandler.processChangeLogo");// we dont want it to be here
            // need to delete the file if the above database task failed
            FileUtil.deleteFile(logoFile);
            throw ex;
        }
        CompanyBean companyBean = null;
        try {
            companyBean = DAOFactory.getCompanyDAO().getCompany(companyID);
        } catch (ObjectNotFoundException e) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.companyid_not_exists", new Object[] {new Integer(companyID)});
            throw new ObjectNotFoundException(localizedMessage);
        }
        request.setAttribute("CompanyBean", companyBean);
    }

    void processChangeCss(ServletContext context,HttpServletRequest request)
        throws BadInputException, AuthenticationException, IOException,
        AssertionException, ObjectNotFoundException, DatabaseException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanAdminSystem();

        Locale locale = I18nUtil.getLocaleInRequest(request);

        // primary key column(s)
        int companyID = ParamUtil.getParameterInt(request, "companyid");
        FileUpload fileUpload = new FileUpload();
        fileUpload.setSizeMax(20000);//20K
        fileUpload.setSizeThreshold(70000);// max memory used = 70K (more than needed)

        List fileItems;
        try {
            fileItems = fileUpload.parseRequest(request);
        } catch (FileUploadException ex) {
            log.error("Cannot upload", ex);
            String localizedMessage = MVNForumResourceBundle.getString(locale, "java.io.IOException.cannot_upload", new Object[] {ex.getMessage()});
            throw new IOException(localizedMessage);
            //throw new IOException("Cannot upload. Detailed reason: " + ex.getMessage());
        }

        // make sure only one file upload
        if (fileItems.size() != 1) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_upload_more_than_one", new Object[] {"css"});
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Assertion: Cannot upload more than 1 file while processing upload css file for company.");
        }

        //get the first and only file
        FileItem myFile = (FileItem)fileItems.get(0);
        if (myFile.isFormField() == true) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_process_uploaded_file_with_a_form_field", new Object[] {"css"});
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Cannot process uploaded company css file with a form field.");
        }

        // now everything all right, go ahead and create logo
        InputStream inputStream = myFile.getInputStream();
        StringBuffer bufferCssFile = new StringBuffer(128);
        bufferCssFile.append(context.getRealPath(MVNForumGlobal.UPLOADED_COMPANY_DIR));
        bufferCssFile.append(File.separatorChar).append(companyID);

        String companyDir =  bufferCssFile.toString();
        FileUtil.createDirs(companyDir, true/*ignore if exist*/);

        bufferCssFile.append("/").append("style.css");
        String cssFile =  bufferCssFile.toString();

        log.trace("uploaded file = " + cssFile);

        //The below method closes the inputStream after it have done its work.
        FileUtil.createTextFile(inputStream, cssFile);// can throw BadInputException

        // now the image has been save, go ahead and update database
        StringBuffer bufferVirtualFile = new StringBuffer(128);
        bufferVirtualFile.append(MVNForumGlobal.UPLOADED_COMPANY_DIR);
        bufferVirtualFile.append("/").append(companyID).append("/").append("style.css");
        String virtualFile =  bufferVirtualFile.toString();

        try {
            DAOFactory.getCompanyDAO().updateCompanyCss(companyID, virtualFile);
        } catch (DatabaseException ex) {// we dont need to catch ObjectNotFoundException since the companyID is already exits
            log.fatal("Assertion in CompanyWebHandler.processChangeCss");// we dont want it to be here
            // need to delete the file if the above database task failed
            FileUtil.deleteFile(cssFile);
            throw ex;
        }
        CompanyBean companyBean = null;
        try {
            companyBean = DAOFactory.getCompanyDAO().getCompany(companyID);
        } catch (ObjectNotFoundException e) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.companyid_not_exists", new Object[] {new Integer(companyID)});
            throw new ObjectNotFoundException(localizedMessage);
        }
        request.setAttribute("CompanyBean", companyBean);
    }

    void prepare(HttpServletRequest request)
        throws ObjectNotFoundException, BadInputException, DatabaseException, AuthenticationException, AssertionException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanAdminSystem();

        int companyID = ParamUtil.getParameterInt(request, "companyid");

        CompanyBean companyBean = null;
        try {
            companyBean = DAOFactory.getCompanyDAO().getCompany(companyID);
        } catch (ObjectNotFoundException e) {
            Locale locale = I18nUtil.getLocaleInRequest(request);
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.companyid_not_exists", new Object[] {new Integer(companyID)});
            throw new ObjectNotFoundException(localizedMessage);
        }
        request.setAttribute("CompanyBean", companyBean);
    }

    void processDelete(ServletContext context,HttpServletRequest request)
        throws BadInputException, ObjectNotFoundException, DatabaseException, AuthenticationException, AssertionException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanAdminSystem();

        // primary key column(s)
        int companyID = ParamUtil.getParameterInt(request, "companyid");

        // now check the password
        MyUtil.ensureCorrectCurrentPassword(request);

        try {
            DAOFactory.getCompanyDAO().delete(companyID);
        } catch (ObjectNotFoundException e ) {
            Locale locale = I18nUtil.getLocaleInRequest(request);
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.companyid_not_exists", new Object[] {new Integer(companyID)});
            throw new ObjectNotFoundException(localizedMessage);
        }
        DAOFactory.getMemberCompanyDAO().delete_inCompany(companyID);

        // now delete the folder for this company
        StringBuffer bufferCompanyFolder = new StringBuffer(128);
        bufferCompanyFolder.append(context.getRealPath(MVNForumGlobal.UPLOADED_COMPANY_DIR));
        bufferCompanyFolder.append(File.separatorChar).append(companyID);
        String companyFolder = bufferCompanyFolder.toString();
        try {
            FileUtil.deleteDir(new File(companyFolder));
        } catch (IOException ioe) {
        }

        // now update the search index
        CompanyIndexer.scheduleDeleteCompanyTask(companyID);
    }

    /**
     * This method supports sorting base on many criteria
     */
    void prepareShowCompanyManagement(HttpServletRequest request)
        throws DatabaseException, AssertionException, BadInputException, AuthenticationException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanAdminSystem();

        // for sort and order stuff
        String sort  = ParamUtil.getParameter(request, "sort");
        String order = ParamUtil.getParameter(request, "order");
        if (sort.length() == 0) sort = "CompanyCreationDate";
        if (order.length()== 0) order = "DESC";

        // we continue
        int postsPerPage = onlineUser.getPostsPerPage();
        int offset = 0;
        try {
            offset = ParamUtil.getParameterInt(request, "offset");
        } catch (BadInputException e) {
            // do nothing
        }

        Locale locale = I18nUtil.getLocaleInRequest(request);

        int totalCompanies = DAOFactory.getCompanyDAO().getNumberOfCompanies();
        if (offset > totalCompanies) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.offset_greater_than_total_rows");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("The offset is not allowed to be greater than total companies.");
        }

        Collection companyBeans = DAOFactory.getCompanyDAO().getCompanies_withSortSupport_limit(offset, postsPerPage, sort, order);

        request.setAttribute("CompanyBeans", companyBeans);
        request.setAttribute("TotalCompanies", new Integer(totalCompanies));
        request.setAttribute("offset", new Integer(offset));
    }

    void processSearch(HttpServletRequest request)
        throws BadInputException, IOException, DatabaseException, ObjectNotFoundException,
        AuthenticationException, AssertionException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanAdminSystem();

        String companyNameKey  = ParamUtil.getParameter(request, "companyname", false);
        String companyAddressKey  = ParamUtil.getParameter(request, "companyaddress", false);
        String companyDateKey  = ParamUtil.getParameter(request, "companycreationdate", false);

        Locale locale = I18nUtil.getLocaleInRequest(request);

        int defaultRows = onlineUser.getPostsPerPage();

        int offset = ParamUtil.getParameterUnsignedInt(request, "offset", 0);
        int rows   = ParamUtil.getParameterUnsignedInt(request, "rows", defaultRows);
        if (rows == 0) {
            rows = defaultRows;// fix NullPointerException when rows = 0
        }

        // offset should be even when divide with rowsToReturn
        offset = (offset / rows) * rows;

        CompanySearchQuery query = new CompanySearchQuery();

        if (companyNameKey.length() > 0) {
            query.setCompanyNameKey(companyNameKey);
        } else if (companyAddressKey.length() > 0){
            query.setCompanyAddressKey(companyAddressKey);
        } else {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_search.key_is_null");
            throw new BadInputException(localizedMessage);
        }
        // dd/MM/yyyy :: default date string
        /*if ( companyDateKey.equals("dd/MM/yyyy")) {
            // do nothing
        } else if (companyDateKey.length() > 0){
            query.setCompanyDateKey(new Timestamp(ParamUtil.getParameterDate(request,"companycreationdate").getTime()));
        }*/

        int searchDate        = ParamUtil.getParameterUnsignedInt(request, "date", CompanySearchQuery.SEARCH_ANY_DATE);
        int searchBeforeAfter = ParamUtil.getParameterInt(request, "beforeafter", CompanySearchQuery.SEARCH_NEWER);

        if ((searchDate != CompanySearchQuery.SEARCH_ANY_DATE) && (searchDate < 365 * 10)) { // 10 years
            long deltaTime = DateUtil.DAY * searchDate;

            Timestamp now = DateUtil.getCurrentGMTTimestamp();
            Timestamp from = null;
            Timestamp to = null;

            long currentTime = now.getTime();

            if (searchBeforeAfter == CompanySearchQuery.SEARCH_NEWER) {
                from = new Timestamp(currentTime - deltaTime);
            } else {// older
                to = new Timestamp(currentTime - deltaTime);
            }

            query.setFromCompanyDateKey(from);
            query.setToCompanyDateKey(to);
        }


        query.searchDocuments(offset, rows);
        int hitCount = query.getHitCount();
        Collection result = query.getCompanyResult();

        if (offset > hitCount) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.offset_greater_than_total_rows");
            throw new BadInputException(localizedMessage);
        }

        request.setAttribute("offset", new Integer(offset));
        request.setAttribute("rows", new Integer(rows));
        request.setAttribute("TotalCompanies", new Integer(hitCount));
        request.setAttribute("CompanyBeans", result);
        request.setAttribute("CompanyName", companyNameKey);
        request.setAttribute("CompanyAddress", companyAddressKey); //strCompanyAddress);
        request.setAttribute("CompanyCreationDate",companyDateKey); //strCompanyCreationDate);
        request.setAttribute("CompanyModifiedDate", ""); //strCompanyModifiedDate);
        request.setAttribute("FromCompanyCreationDate", ""); // strFromCompanyCreationDate);
        request.setAttribute("ToCompanyCreationDate", ""); // strToCompanyCreationDate);
    }
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.