com.iana.dver.controller.DverUserController.java Source code

Java tutorial

Introduction

Here is the source code for com.iana.dver.controller.DverUserController.java

Source

/*
 * Copyright (c) 2013 IANA. All Rights Reserved. THE AUTHOR MAKES NO
 * REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE
 * AUTHOR SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT
 * OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */
package com.iana.dver.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.iana.dver.service.DverDetailsService;
import com.iana.dver.service.DverSearchService;
import com.iana.dver.service.DverUserService;
import com.iana.dver.util.DVERUtil;
import com.iana.dver.vo.ChangePwdVO;
import com.iana.dver.vo.DverConfigVO;
import com.iana.dver.vo.DverFileVO;
import com.iana.dver.vo.DverSearchVO;
import com.iana.dver.vo.DverSecurityObj;
import com.iana.dver.vo.DverUserVO;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

/**
 * @author tgbaxi
 * @date 27-Sep-2013
 */
@Controller
@Scope("request")
public class DverUserController {

    @Autowired
    private DverSecurityObj securityObj;

    @Autowired
    private ServletContext servletContext;

    @Autowired
    private DverUserService dverUserService;

    @Autowired
    private DverDetailsService dverDetailsService;

    @Autowired
    private DverSearchService dverSearchService;

    private static final Logger logger = Logger.getLogger(DverUserController.class);

    /**
     * @return the dverDetailsService
     */
    public DverDetailsService getDverDetailsService() {
        return dverDetailsService;
    }

    /**
     * @param dverDetailsService
     *          the dverDetailsService to set
     */
    public void setDverDetailsService(DverDetailsService dverDetailsService) {
        this.dverDetailsService = dverDetailsService;
    }

    /**
     * @return the securityObj
     */
    public DverSecurityObj getSecurityObj() {
        return securityObj;
    }

    /**
     * @param securityObj
     *          the securityObj to set
     */
    public void setSecurityObj(DverSecurityObj securityObj) {
        this.securityObj = securityObj;
    }

    /**
     * @return the dverUserService
     */
    public DverUserService getDverUserService() {
        return dverUserService;
    }

    /**
     * @param dverUserService
     *          the dverUserService to set
     */
    public void setDverUserService(DverUserService dverUserService) {
        this.dverUserService = dverUserService;
    }

    @ModelAttribute("countries")
    public Map<Integer, String> countries() {
        Map<Integer, String> countries = new HashMap<Integer, String>();
        countries.put(1, "USA");
        countries.put(2, "CAN");
        countries.put(3, "MAX");
        return countries;
    }

    @RequestMapping(value = { "/iep/welcome", "/mc/welcome" }, method = RequestMethod.GET)
    public String setupEditCompanyProfilePage(Model model, HttpServletRequest request) {

        try {
            Integer userId = securityObj.getUserid();
            DverUserVO userVO = this.dverUserService.getUserById(userId);
            model.addAttribute("userVO", userVO);
            return "company-profile";

        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("setupEditCompanyProfilePage method of DverUserController \n " + ex);
            logger.error("Error in setupEditCompanyProfilePage()....." + ex);
            return "error";
        }
    }

    @RequestMapping(value = { "/iep/welcome", "/mc/welcome" }, method = RequestMethod.POST)
    public String submitCompanyProfile(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute("userVO") DverUserVO userVO, BindingResult result) {
        try {
            logger.info("save company profile.....");
            // Validate the VO
            validateCompanyProfile(userVO, result);
            if (!result.hasErrors()) {
                String updatedBy = this.securityObj.getUserName();
                String country = this.countries().get(userVO.getCountryId());
                userVO.setCountry(country);
                userVO.setUpdatedBy(updatedBy);
                this.dverUserService.updateDverUserDetails(userVO);
                request.setAttribute("successMsg", "Company Profile updated successfully.");
            }
            return "company-profile";
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("submitCompanyProfile method of DverUserController \n " + ex);
            logger.error("Error in submitCompanyProfile()....." + ex);
            return "error";
        }
    }

    private void validateCompanyProfile(DverUserVO userVO, BindingResult errors) {

        try {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "required.firstName",
                    "First Name can not be blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "required.lastName",
                    "Last Name can not be blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "required.title", "Title can not be blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "required.phone", "Phone can not be blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "fax", "required.fax", "Fax No. can not be blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address1", "required.address1",
                    "Address can not be blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "city", "required.city", "City can not be blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "state", "required.state",
                    "State Code can not be blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "zipCode", "required.zipCode",
                    "ZIP Code can not be blank.");

        } catch (Exception ex) {
            logger.error("Error in validateCompanyProfile()....." + ex);
            DVERUtil.sendExceptionEmails("validateCompanyProfile method of DverUserController \n " + ex);

        }
    }

    @RequestMapping(value = { "/iep/dverconfig", "/mc/dverconfig" }, method = RequestMethod.GET)
    public String setupEditDverConfigPage(Model model, HttpServletRequest request) {

        try {
            logger.info("Dver Config Edit Page.....");
            Integer userId = securityObj.getUserid();
            DverConfigVO dverConfigVO = this.dverUserService.getDverConfigById(userId);
            dverConfigVO.setUserId(userId);
            model.addAttribute("dverConfigVO", dverConfigVO);
            return "dver-config";
        } catch (Exception ex) {

            DVERUtil.sendExceptionEmails("setupEditDverConfigPage method of DverUserController \n " + ex);
            logger.error("Error in setupEditDverConfigPage()....." + ex);
            return "error";
        }

    }

    @RequestMapping(value = { "/iep/dverconfig", "/mc/dverconfig" }, method = RequestMethod.POST)
    public String submitDverConfig(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute("dverConfigVO") DverConfigVO dverConfigVO, BindingResult result) {

        try {
            logger.info("submit Dver Config Page.....");
            // Validate the VO
            validateDverConfig(dverConfigVO, result);
            if (!result.hasErrors()) {
                String updatedBy = this.securityObj.getUserName();
                dverConfigVO.setUpdatedBy(updatedBy);
                this.dverUserService.updateDverConfig(dverConfigVO);
                request.setAttribute("successMsg", "DVER Config updated successfully.");
            }
            return "dver-config";

        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("submitDverConfig method of DverUserController \n " + ex);
            logger.error("Error in submitDverConfig()....." + ex);
            return "error";
        }
    }

    private void validateDverConfig(DverConfigVO dverConfigVO, BindingResult errors) {

        try {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "required.firstName",
                    "First Name can not be blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "required.lastName",
                    "Last Name can not be blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "required.email", "Email can not be blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "required.phone", "Phone can not be blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "required.title", "Title can not be blank.");

        } catch (Exception ex) {
            logger.error("Error in validateDverConfig()....." + ex);
            DVERUtil.sendExceptionEmails("validateDverConfig method of DverUserController \n " + ex);

        }
    }

    @RequestMapping(value = { "/logout" }, method = RequestMethod.GET)
    public String performLogout(HttpServletRequest request, HttpServletResponse response) {
        try {
            if (this.securityObj != null) {
                request.getSession().removeAttribute("securityObj");
                logger.info("Removing the session attribute");
            }
            return "redirect:/login";
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("performLogout method of DverUserController \n " + ex);
            logger.error("Error in performLogout()....." + ex);
            return "error";
        }

    }

    @RequestMapping(value = { "/admin/changepwd", "/iep/changepwd", "/mc/changepwd" }, method = RequestMethod.GET)
    public String setupChangePwdPage(final Model model, HttpServletRequest request) {

        try {
            logger.info("On Change Password Page...");
            ChangePwdVO changePwdVO = new ChangePwdVO();
            changePwdVO.setUserId(this.securityObj.getUserid());
            changePwdVO.setLoginId(this.securityObj.getLoginId());
            model.addAttribute("changePwdVO", changePwdVO);
            return "change-pass";
        } catch (Exception ex) {

            DVERUtil.sendExceptionEmails("setupChangePwdPage method of DverUserController \n " + ex);
            logger.error("Error in setupChangePwdPage()....." + ex);
            return "error";
        }

    }

    @RequestMapping(value = { "/admin/changepwd", "/iep/changepwd", "/mc/changepwd" }, method = RequestMethod.POST)
    public String submitChangePwd(HttpServletRequest request, HttpServletResponse response,
            final RedirectAttributes redirectAttributes, @ModelAttribute("changePwdVO") ChangePwdVO changePwdVO,
            BindingResult result) {

        try {
            logger.info("Submit Change Password Page...");
            validateChangePwdForm(changePwdVO, result);
            if (!result.hasErrors()) {
                if (changePwdVO.getOldPwd().equals(changePwdVO.getNewPwd())) {
                    result.rejectValue("newPwd", "same.pwd", "Current password and New Password can not be same.");
                    return "change-pass";
                }
                if (!result.hasErrors() && !changePwdVO.getNewPwd().equals(changePwdVO.getReTypeNewPwd())) {
                    result.rejectValue("reTypeNewPwd", "pwd.not.similar",
                            "New Password and Confirm Password can not be different.");
                    return "change-pass";
                }

                Boolean isValidOldPwd = this.dverUserService.verifyWithOldPassword(changePwdVO.getUserId(),
                        changePwdVO.getOldPwd());
                if (!isValidOldPwd) {
                    result.rejectValue("oldPwd", "wrong.old.pwd", "Please enter correct Current Password.");
                    return "change-pass";
                }

                if (!result.hasErrors()) {
                    this.dverUserService.changePassword(changePwdVO);
                    if (this.securityObj != null) {
                        request.getSession().removeAttribute("securityObj");
                    }

                    DverUserVO userVO = this.dverUserService.getUserById(securityObj.getUserid());
                    DverConfigVO configVO = this.dverUserService.getDverConfigById(securityObj.getUserid());

                    sendChangePwdEmail(userVO, configVO, changePwdVO.getNewPwd());

                    redirectAttributes.addFlashAttribute("successMsg", "Password updated successfully.");
                    return "redirect:/login";
                }
            } else {
                return "change-pass";
            }
            return "redirect:/login";
        } catch (Exception ex) {

            DVERUtil.sendExceptionEmails("submitChangePwd method of DverUserController \n " + ex);
            logger.error("Error in submitChangePwd()....." + ex);
            return "error";

        }

    }

    private void validateChangePwdForm(ChangePwdVO changePwdVO, BindingResult errors) {

        try {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "oldPwd", "required.oldPwd",
                    "Current Password can not be left blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "newPwd", "required.newPwd",
                    "New Password can not be left blank.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "reTypeNewPwd", "required.reTypeNewPwd",
                    "Confirm New Password can not be left blank.");
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("validateChangePwdForm method of DverUserController \n " + ex);
            logger.error("Error in validateChangePwdForm()....." + ex);
        }
    }

    @RequestMapping("/downloadDver/{dverDetailId}")
    @ResponseBody
    public byte[] getDverFile(@PathVariable("dverDetailId") Integer dverDetailId, HttpServletRequest request,
            HttpServletResponse response) throws IOException {

        try {
            logger.info("Perform download Dver File.....");
            DverFileVO dverFileVO = this.dverDetailsService.getDverFileFromDverDetail(dverDetailId);
            if (dverFileVO != null) {
                byte[] bytes = dverFileVO.getDverContent();
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"" + dverFileVO.getDverName() + ".pdf\"");
                response.setContentLength(bytes.length);
                response.setContentType("application/pdf");
                return bytes;
            } else {
                return null;
            }
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("getDverFile method of DverUserController \n " + ex);
            logger.error("Error in getDverFile()....." + ex);
            return null;
        }
    }

    @RequestMapping(value = "/getIepInfo/{iepdot}", method = RequestMethod.GET)
    public String setupIepInfoPage(final Model model, @ModelAttribute("configVO") DverConfigVO configVO,
            BindingResult result, @PathVariable("iepdot") String iepdot, HttpServletRequest request) {
        try {
            logger.info("on Iep Info Page.....");
            configVO = this.dverUserService.getDverConfigByDOT(iepdot);
            if (configVO != null) {
                model.addAttribute("configVO", configVO);
            } else {
                result.reject("no.iep.found",
                        "The Contact information for DOT: " + iepdot + " is currently not available.");
            }
            return "iep-info";
        } catch (Exception ex) {

            DVERUtil.sendExceptionEmails("setupIepInfoPage method of DverUserController \n " + ex);
            logger.error("Error in setupIepInfoPage()....." + ex);
            return "error";

        }

    }

    @RequestMapping(value = "/generateMergedPdf/{selectedDverDetailIds}")
    public @ResponseBody byte[] generateMergedPdf(
            @PathVariable("selectedDverDetailIds") String selectedDverDetailIds, HttpServletRequest request,
            HttpServletResponse response) throws IOException, DocumentException {

        byte[] mergedFileContent = null;

        try {
            logger.info("Perform generate & Merge Pdf.....");
            String[] dverDetailIds = selectedDverDetailIds.split(",");
            List<Integer> dverDetailIdLst = new ArrayList<Integer>();
            for (String dverDetailId : dverDetailIds) {
                dverDetailIdLst.add(Integer.parseInt(dverDetailId));
            }

            List<byte[]> dverFiles = this.dverDetailsService.getDverFilesFromDverDetailIds(dverDetailIdLst);

            List<InputStream> list = new ArrayList<InputStream>();

            for (byte[] bytes : dverFiles) {
                list.add(new ByteArrayInputStream(bytes));
            }

            ByteArrayOutputStream out = new ByteArrayOutputStream();

            DVERUtil.doMerge(list, out);

            mergedFileContent = out.toByteArray();

            response.setHeader("Content-Disposition", "attachment; filename=\"merged_report.pdf\"");
            response.setContentLength(mergedFileContent.length);
            response.setContentType("application/pdf");
        } catch (Exception ex) {

            DVERUtil.sendExceptionEmails("generateMergedPdf method of DverUserController \n " + ex);
            logger.error("Error in generateMergedPdf()....." + ex);

        }

        return mergedFileContent;
    }

    @RequestMapping(value = "/generateExcel")
    public void generateExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("Generate Excel report for searched DVERs...");
        try {
            DverSearchVO dverSearchVO = (DverSearchVO) request.getSession().getAttribute("searchDetails");
            HSSFSheet worksheet = this.dverSearchService.getAllSearchDversExcel(securityObj.getUserType(),
                    dverSearchVO);
            response.setHeader("Content-Disposition", "attachment; filename=\"DVER.xls\"");
            response.setContentType("application/vnd.ms-excel");
            write(response, worksheet);
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("generateExcel method of DverUserController \n " + ex);
            logger.error("Error in generateExcel():" + ex.toString());
        }
    }

    @RequestMapping(value = "/generateExcelSelected/{selectedDverDetailIds}")
    public void generateExcelForSelectedDver(@PathVariable("selectedDverDetailIds") String selectedDverDetailIds,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("Generate selected Excel report for searched DVERs...");
        try {
            String[] dverDetailIds = selectedDverDetailIds.split(",");
            List<Integer> dverSelectedIdList = new ArrayList<Integer>();
            for (String dverDetailId : dverDetailIds) {
                dverSelectedIdList.add(Integer.parseInt(dverDetailId));
            }

            DverSearchVO dverSearchVO = (DverSearchVO) request.getSession().getAttribute("searchDetails");
            HSSFSheet worksheet = this.dverSearchService.getSelectedSearchDversExcel(securityObj.getUserType(),
                    dverSearchVO, dverSelectedIdList);
            response.setHeader("Content-Disposition", "attachment; filename=\"DVER.xls\"");
            response.setContentType("application/vnd.ms-excel");
            write(response, worksheet);
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("generateExcel method of DverUserController \n " + ex);
            logger.error("Error in generateExcel():" + ex.toString());
        }
    }

    private void write(HttpServletResponse response, HSSFSheet worksheet) throws IOException {
        logger.info("Writing excel report to the response stream...");
        // Retrieve the output stream
        ServletOutputStream outputStream = response.getOutputStream();
        // Write to the output stream
        worksheet.getWorkbook().write(outputStream);
        // Flush the stream
        outputStream.flush();
    }

    private void sendChangePwdEmail(DverUserVO dverUser, DverConfigVO dverConfig, String newPwd)
            throws IOException, DocumentException, AddressException {

        try {
            PdfReader reader = new PdfReader(
                    servletContext.getResourceAsStream("/WEB-INF/email_templates/DVER_CHANGE_PWD_FORM.pdf"));

            File tempFile = File.createTempFile("DVER_CHANGE_PWD_" + securityObj.getUserName(), ".pdf");

            PdfStamper filledOutForm = new PdfStamper(reader, new FileOutputStream(tempFile));
            AcroFields form = filledOutForm.getAcroFields();
            DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
            Date date = new Date();

            form.setField("topmostSubform[0].Page1[0].notif_dt[0]", dateFormat.format(date));
            form.setField("topmostSubform[0].Page1[0].contact_nm[0]",
                    dverUser.getFirstName() + " " + dverUser.getLastName());
            form.setField("topmostSubform[0].Page1[0].company[0]", dverUser.getCompanyName());
            form.setField("topmostSubform[0].Page1[0].address[0]",
                    dverUser.getAddress1() + " " + dverUser.getAddress2());
            form.setField("topmostSubform[0].Page1[0].city[0]",
                    dverUser.getCity() + ", " + dverUser.getState() + " " + dverUser.getZipCode());

            form.setField("topmostSubform[0].Page1[0].scac[0]", dverUser.getScac());
            form.setField("topmostSubform[0].Page1[0].pwd[0]", newPwd);

            filledOutForm.setFormFlattening(Boolean.TRUE);
            filledOutForm.close();

            DVERUtil.sendEmailWithAttachments("admin@dver.intermodal.org", "DVER - Password Change Confirmation",
                    new InternetAddress[] { new InternetAddress(dverUser.getEmail()) },
                    "Please see attached to know about your changed password.", tempFile);

            if (!dverConfig.getEmail().equals(dverUser.getEmail())) {

                PdfReader reader1 = new PdfReader(
                        servletContext.getResourceAsStream("/WEB-INF/email_templates/DVER_CHANGE_PWD_FORM.pdf"));
                File tempFile1 = File.createTempFile("DVER_CHANGE_PWD_NOTIF_" + securityObj.getUserName(), ".pdf");

                PdfStamper filledOutForm1 = new PdfStamper(reader1, new FileOutputStream(tempFile1));
                AcroFields form1 = filledOutForm1.getAcroFields();

                form1.setField("topmostSubform[0].Page1[0].notif_dt[0]", dateFormat.format(date));
                form1.setField("topmostSubform[0].Page1[0].contact_nm[0]",
                        dverConfig.getFirstName() + " " + dverConfig.getLastName());
                form1.setField("topmostSubform[0].Page1[0].company[0]", dverUser.getCompanyName());
                form1.setField("topmostSubform[0].Page1[0].address[0]",
                        dverUser.getAddress1() + " " + dverUser.getAddress2());
                form1.setField("topmostSubform[0].Page1[0].city[0]",
                        dverUser.getCity() + ", " + dverUser.getState() + " " + dverUser.getZipCode());

                form1.setField("topmostSubform[0].Page1[0].scac[0]", dverUser.getScac());
                form1.setField("topmostSubform[0].Page1[0].pwd[0]", newPwd);

                filledOutForm1.setFormFlattening(Boolean.TRUE);
                filledOutForm1.close();

                DVERUtil.sendEmailWithAttachments("admin@dver.intermodal.org",
                        "DVER - Password Change Confirmation",
                        new InternetAddress[] { new InternetAddress(dverConfig.getEmail()) },
                        "Please see attached to know about your changed password.", tempFile1);
            }

            tempFile.deleteOnExit();

        } catch (Exception ex) {

            logger.error("Error in sendForgotPwdEmail....." + ex);

            DVERUtil.sendExceptionEmails("sendChangePwdEmail method of DverUserController \n " + ex);

        }
    }
}