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

Java tutorial

Introduction

Here is the source code for com.iana.dver.controller.DverAdminController.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.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
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.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.iana.dver.service.DverDetailsService;
import com.iana.dver.service.DverRegistrationService;
import com.iana.dver.service.DverUserService;
import com.iana.dver.util.DVERUtil;
import com.iana.dver.vo.DverConfigVO;
import com.iana.dver.vo.DverDetailsVO;
import com.iana.dver.vo.DverSecurityObj;
import com.iana.dver.vo.DverUserVO;
import com.iana.dver.vo.RejectedDverVO;

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

    @Autowired
    private DverDetailsService dverDetailsService;

    @Autowired
    private DverRegistrationService dverRegistrationService;

    @Autowired
    private DverUserService dverUserService;

    @Autowired
    private DverSecurityObj securityObj;

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

    @RequestMapping(value = "/{userType}", method = RequestMethod.GET)
    public String setupDashboardPage(final ModelMap model, @PathVariable("userType") String userType,
            HttpServletRequest request) {
        try {
            logger.info("setupDashboardPage .....");
            if (userType.equalsIgnoreCase("admin")) {
                return "rejected";
            } else if (userType.equalsIgnoreCase("iep") || userType.equalsIgnoreCase("mc")) {
                return "redirect:/" + userType + "/search";
            } else {
                logger.error("Invalid User Role for Rejected Dver Display....");
                return "error";
            }

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

    }

    @RequestMapping(value = "/admin/rejected", produces = "application/json", method = RequestMethod.GET)
    public @ResponseBody String loadRejectedDvers(
            @RequestParam(value = "sEcho", required = false, defaultValue = "1") String sEcho,
            @RequestParam(value = "sSearch", required = false) String sSearch,
            @RequestParam(value = "sColumns", required = false) String sColumns,
            @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") String iDisplayStart,
            @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") String iDisplayLength,
            @RequestParam(value = "iColumns", required = false, defaultValue = "7") String iColumns)
            throws IOException {

        try {
            logger.info("Load Rejected Dvers.....");
            List<DverDetailsVO> rejectedDvers = this.dverDetailsService
                    .getAllRejectedDvers(Integer.parseInt(iDisplayStart), Integer.parseInt(iDisplayLength));

            if (CollectionUtils.isEmpty(rejectedDvers)) {
                rejectedDvers = new ArrayList<DverDetailsVO>();
            }

            int iTotalRecords = rejectedDvers.size();
            int iTotalDisplayRecords = this.dverDetailsService.getAllRejectedDversCount();

            JsonObject jsonResponse = new JsonObject();
            jsonResponse.addProperty("sEcho", sEcho);
            jsonResponse.addProperty("iTotalRecords", iTotalRecords);
            jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords);
            Gson gson = new Gson();
            jsonResponse.add("aaData", gson.toJsonTree(rejectedDvers));

            return jsonResponse.toString();

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

    @RequestMapping(value = "/admin/rejected/filter", produces = "application/json", method = RequestMethod.GET)
    public @ResponseBody String filterRejectedDversByScacOrDot(
            @RequestParam(value = "sEcho", required = false, defaultValue = "1") String sEcho,
            @RequestParam(value = "sSearch", required = false) String sSearch,
            @RequestParam(value = "sColumns", required = false) String sColumns,
            @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") String iDisplayStart,
            @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") String iDisplayLength,
            @RequestParam(value = "iColumns", required = false, defaultValue = "8") String iColumns,
            @RequestParam(value = "iepDotFilter", required = false, defaultValue = "") String iepDotFilter,
            @RequestParam(value = "mcDotFilter", required = false, defaultValue = "") String mcDotFilter,
            @RequestParam(value = "reportNoFilter", required = false, defaultValue = "") String reportNoFilter) {

        try {

            Map<String, String> filtermap = new HashMap<String, String>();

            if (StringUtils.hasLength(iepDotFilter)) {
                filtermap.put("iepDotFilter", iepDotFilter + "%");
            }
            if (StringUtils.hasLength(mcDotFilter)) {
                filtermap.put("mcDotFilter", mcDotFilter + "%");
            }
            if (StringUtils.hasLength(reportNoFilter)) {
                filtermap.put("reportNoFilter", reportNoFilter + "%");
            }

            List<DverDetailsVO> rejectedDvers = this.dverDetailsService.getFilteredRejectedDvers(filtermap,
                    Integer.parseInt(iDisplayStart), Integer.parseInt(iDisplayLength));

            if (CollectionUtils.isEmpty(rejectedDvers)) {
                rejectedDvers = new ArrayList<DverDetailsVO>();
            }

            int iTotalRecords = rejectedDvers.size();
            int iTotalDisplayRecords = this.dverDetailsService.countFilteredRejectedDvers(filtermap);

            JsonObject jsonResponse = new JsonObject();
            jsonResponse.addProperty("sEcho", sEcho);
            jsonResponse.addProperty("iTotalRecords", iTotalRecords);
            jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords);
            Gson gson = new Gson();
            jsonResponse.add("aaData", gson.toJsonTree(rejectedDvers));
            return jsonResponse.toString();

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

    @RequestMapping(value = "/admin/generateRejectedDVERExcel")
    public void generateRejectedDVERExcel(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        logger.info("Generate Rejected DVER Excel report...");
        try {
            HSSFSheet worksheet = this.dverDetailsService.getAllRejectedDversExcel();
            response.setHeader("Content-Disposition", "attachment; filename=\"REJECTED_DVER(s).xls\"");
            response.setContentType("application/vnd.ms-excel");
            write(response, worksheet);
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("generateRejectedDVERExcel method of DverAdminController \n " + ex);
            logger.error("Error in generateRejectedDVERExcel():" + ex.toString());
        }
    }

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

            HSSFSheet worksheet = this.dverDetailsService.getSelectedRejectedDversExcel(dverSelectedIdList);
            response.setHeader("Content-Disposition", "attachment; filename=\"REJECTED_DVER(s).xls\"");
            response.setContentType("application/vnd.ms-excel");
            write(response, worksheet);
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("generateRejectedDVERExcel method of DverAdminController \n " + ex);
            logger.error("Error in generateRejectedDVERExcel():" + 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();
    }

    @RequestMapping(value = "/admin/users", method = RequestMethod.GET)
    public String setupDverUsers(HttpServletRequest request) {
        try {
            return "dverUsers";
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("setupDverUsers method of DverAdminController \n " + ex);
            logger.error("Error in setupDverUsers....." + ex);
            return "error";
        }
    }

    @RequestMapping(value = "/admin/users/{userTypeId}", produces = "application/json", method = RequestMethod.GET)
    public @ResponseBody String loadUsersByType(@PathVariable("userTypeId") Integer userTypeId,
            @RequestParam(value = "sEcho", required = false, defaultValue = "1") String sEcho,
            @RequestParam(value = "sSearch", required = false) String sSearch,
            @RequestParam(value = "sColumns", required = false) String sColumns,
            @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") String iDisplayStart,
            @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") String iDisplayLength,
            @RequestParam(value = "iColumns", required = false, defaultValue = "9") String iColumns,
            @RequestParam(value = "iSortCol_0", required = false, defaultValue = "0") String sortColumnIndex,
            @RequestParam(value = "sSortDir_0", required = false, defaultValue = "asc") String sSortDirection) {

        try {
            List<DverUserVO> dverUsers = this.dverRegistrationService.getAllUsersByType(userTypeId,
                    Integer.parseInt(iDisplayStart), Integer.parseInt(iDisplayLength), sortColumnIndex,
                    sSortDirection);

            if (CollectionUtils.isEmpty(dverUsers)) {
                dverUsers = new ArrayList<DverUserVO>();
            }

            int iTotalRecords = dverUsers.size();
            int iTotalDisplayRecords = this.dverRegistrationService.countAllUsersByType(userTypeId);

            JsonObject jsonResponse = new JsonObject();
            jsonResponse.addProperty("sEcho", sEcho);
            jsonResponse.addProperty("iTotalRecords", iTotalRecords);
            jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords);
            Gson gson = new Gson();
            jsonResponse.add("aaData", gson.toJsonTree(dverUsers));
            return jsonResponse.toString();

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

    @RequestMapping(value = "/admin/generateUsersExcel")
    public void generateUsersExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            HSSFSheet worksheet = this.dverRegistrationService.getAllUsersForExcel();
            response.setHeader("Content-Disposition", "attachment; filename=\"DVER_USERS.xls\"");
            response.setContentType("application/vnd.ms-excel");
            write(response, worksheet);

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

    }

    @RequestMapping(value = "/admin/users/filter", produces = "application/json", method = RequestMethod.GET)
    public @ResponseBody String filterUsersByScacOrDot(
            @RequestParam(value = "sEcho", required = false, defaultValue = "1") String sEcho,
            @RequestParam(value = "sSearch", required = false) String sSearch,
            @RequestParam(value = "sColumns", required = false) String sColumns,
            @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") String iDisplayStart,
            @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") String iDisplayLength,
            @RequestParam(value = "iColumns", required = false, defaultValue = "9") String iColumns,
            @RequestParam(value = "iSortCol_0", required = false, defaultValue = "0") String sortColumnIndex,
            @RequestParam(value = "sSortDir_0", required = false, defaultValue = "asc") String sSortDirection,
            @RequestParam(value = "scacFilter", required = false, defaultValue = "") String scacFilter,
            @RequestParam(value = "dotFilter", required = false, defaultValue = "") String dotFilter,
            @RequestParam(value = "userTypeFilter", required = false, defaultValue = "All") String userTypeFilter,
            @RequestParam(value = "companyNameFilter", required = false, defaultValue = "") String companyNameFilter,
            @RequestParam(value = "firstNameFilter", required = false, defaultValue = "") String firstNameFilter,
            @RequestParam(value = "lastNameFilter", required = false, defaultValue = "") String lastNameFilter,
            @RequestParam(value = "emailFilter", required = false, defaultValue = "") String emailFilter) {

        try {
            Integer userTypeId = 0;

            Map<String, String> filtermap = new HashMap<String, String>();

            if (StringUtils.hasLength(userTypeFilter)) {
                if (userTypeFilter.equalsIgnoreCase("iep")) {
                    userTypeId = 2;
                } else if (userTypeFilter.equalsIgnoreCase("mc")) {
                    userTypeId = 3;
                } else {
                    userTypeId = 0;
                }
            }

            if (StringUtils.hasLength(scacFilter)) {
                filtermap.put("scacFilter", scacFilter + "%");
            }
            if (StringUtils.hasLength(dotFilter)) {
                filtermap.put("dotFilter", dotFilter + "%");
            }
            if (StringUtils.hasLength(companyNameFilter)) {
                filtermap.put("companyNameFilter", companyNameFilter + "%");
            }
            if (StringUtils.hasLength(firstNameFilter)) {
                filtermap.put("firstNameFilter", firstNameFilter + "%");
            }
            if (StringUtils.hasLength(lastNameFilter)) {
                filtermap.put("lastNameFilter", lastNameFilter + "%");
            }
            if (StringUtils.hasLength(emailFilter)) {
                filtermap.put("emailFilter", emailFilter + "%");
            }

            filtermap.put("sortColumnIndex", sortColumnIndex);
            filtermap.put("sSortDirection", sSortDirection);

            List<DverUserVO> dverUsers = this.dverRegistrationService.getFilteredUsersByScacOrDot(userTypeId,
                    filtermap, Integer.parseInt(iDisplayStart), Integer.parseInt(iDisplayLength));

            if (CollectionUtils.isEmpty(dverUsers)) {
                dverUsers = new ArrayList<DverUserVO>();
            }

            int iTotalRecords = dverUsers.size();
            int iTotalDisplayRecords = this.dverRegistrationService.countFilteredUsersByScacOrDot(userTypeId,
                    filtermap);

            JsonObject jsonResponse = new JsonObject();
            jsonResponse.addProperty("sEcho", sEcho);
            jsonResponse.addProperty("iTotalRecords", iTotalRecords);
            jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords);
            Gson gson = new Gson();
            jsonResponse.add("aaData", gson.toJsonTree(dverUsers));
            return jsonResponse.toString();

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

    @RequestMapping(value = "/admin/updateOwner/{dverDetailId}/{mcdot}/{iepdot}", method = RequestMethod.GET)
    public String setupUpdateDVEROwnerPage(final Model model, @PathVariable("dverDetailId") Integer dverDetailId,
            @PathVariable("mcdot") String mcdot, @PathVariable("iepdot") String iepdot,
            HttpServletRequest request) {

        try {
            logger.info("On DVER Owner Page ");
            RejectedDverVO rejectedDverVO = new RejectedDverVO();
            rejectedDverVO.setDverDetailId(dverDetailId);
            rejectedDverVO.setIepdot(iepdot);
            rejectedDverVO.setMcdot(mcdot);
            model.addAttribute("rejectedDverVO", rejectedDverVO);

            return "change-owner";

        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("setupUpdateDVEROwnerPage method of DverAdminController \n " + ex);
            logger.error("setupUpdateDVEROwnerPage method of DverAdminController \n " + ex);
            return "error";
        }
    }

    @RequestMapping(value = "/admin/updateOwner", method = RequestMethod.POST)
    public @ResponseBody String updateDVEROwner(HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("On Update DVER Owner Page ");
            StringBuilder errors = new StringBuilder();
            String mcdot = request.getParameter("mcdot");
            String iepdot = request.getParameter("iepdot");
            Integer dverDetailId = Integer.parseInt(request.getParameter("dverdetailid"));

            if (!StringUtils.hasText(mcdot) && !StringUtils.hasText(iepdot)) {
                errors.append("Please enter MC/IEP DOT value. <br/> ");
            }

            RejectedDverVO rejectedDverVO = null;
            if (errors.length() == 0) {
                rejectedDverVO = new RejectedDverVO();
                rejectedDverVO.setDverDetailId(dverDetailId);
                rejectedDverVO.setIepdot(iepdot);
                rejectedDverVO.setMcdot(mcdot);
                rejectedDverVO.setIepUserId(0);
                rejectedDverVO.setMcUserId(0);

                validateDOTFields(rejectedDverVO, errors);
            }

            if (errors.length() == 0 && rejectedDverVO != null) {
                this.dverDetailsService.moveRejectedDverToFound(rejectedDverVO, rejectedDverVO.getDverDetailId());
                return "success";
            } else {
                return errors.toString();
            }
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("updateDVEROwner method of DverAdminController \n " + ex);
            logger.error("Error in updateDVEROwner....." + ex);
            return "error";
        }
    }

    /**
     * Validates provided IEP and MC DOT's
     * 
     * @param rejectedDverVO
     * @param errors
     */
    private void validateDOTFields(RejectedDverVO rejectedDverVO, StringBuilder errors) {
        Boolean hasErrors = Boolean.TRUE;
        try {
            DverUserVO mcUserVO = StringUtils.hasText(rejectedDverVO.getMcdot())
                    ? this.dverRegistrationService.fetchUserWithDOTAndType(rejectedDverVO.getMcdot(), "MC")
                    : null;
            if (mcUserVO != null) {
                rejectedDverVO.setMcdot(mcUserVO.getUsDOT());
                rejectedDverVO.setMcscac(mcUserVO.getScac());
                rejectedDverVO.setMcUserId(mcUserVO.getDverUserId());
                hasErrors = Boolean.FALSE;
            }

            DverUserVO iepUserVO = StringUtils.hasText(rejectedDverVO.getIepdot())
                    ? this.dverRegistrationService.fetchUserWithDOTAndType(rejectedDverVO.getIepdot(), "IEP")
                    : null;
            if (iepUserVO != null) {
                rejectedDverVO.setIepdot(iepUserVO.getUsDOT());
                rejectedDverVO.setIepscac(iepUserVO.getScac());
                rejectedDverVO.setIepUserId(iepUserVO.getDverUserId());
                hasErrors = Boolean.FALSE;
            }

            if (hasErrors) {
                errors.append("User with provided IEP/MC DOT does not exist in system. <br/>");
            }

        } catch (Exception ex) {
            logger.error("validateDOTFields method of DverAdminController \n " + ex);
            DVERUtil.sendExceptionEmails("validateDOTFields method of DverAdminController \n " + ex);
        }
    }

    @RequestMapping(value = "/getDverConfig/{userId}", method = RequestMethod.GET)
    public String getDverContactDetails(final Model model, @ModelAttribute("configVO") DverConfigVO configVO,
            BindingResult result, @PathVariable("userId") Integer userId, HttpServletRequest request) {
        try {
            logger.info("on DVER Contact details.....");
            configVO = this.dverUserService.getDverConfigById(userId);
            if (configVO != null) {
                model.addAttribute("configVO", configVO);
            } else {
                result.reject("no.contact.details.found", "The Contact information for user with user id : "
                        + userId + " is currently not available.");
            }
            return "iep-info";
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("getDverContactDetails method of DverAdminController \n " + ex);
            logger.error("Error in getDverContactDetails()....." + ex);
            return "error";
        }
    }

    @RequestMapping(value = "/admin/updateUser/{userId}", method = RequestMethod.GET)
    public String setupEditCompanyForAdmin(HttpServletRequest request, HttpServletResponse response,
            final Model model, @PathVariable("userId") Integer userId) {
        try {
            logger.info("on setupEditCompanyForAdmin.... ");
            DverUserVO userVO = this.dverUserService.getUserById(userId);
            model.addAttribute("userVO", userVO);
            return "edit-company-admin";
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("setupEditCompanyForAdmin method of DverAdminController \n " + ex);
            logger.error("Error in setupEditCompanyForAdmin()....." + ex);
            return "error";
        }
    }

    @RequestMapping(value = "/admin/updateUser/{userId}", method = RequestMethod.POST)
    public String submitEditCompanyForAdmin(HttpServletRequest request, HttpServletResponse response,
            @PathVariable("userId") Integer userId, @ModelAttribute("userVO") DverUserVO userVO,
            BindingResult result) {
        try {
            logger.info("on submitEditCompanyForAdmin.... ");

            if (userVO.getRole().equalsIgnoreCase("mc")) {
                userVO.setUserType(3);
            }
            if (userVO.getRole().equalsIgnoreCase("iep")) {
                userVO.setUserType(2);
            }
            validateEditCompanyForAdmin(userVO, result);
            if (!result.hasErrors()) {
                String updatedBy = this.securityObj.getUserName();
                userVO.setUpdatedBy(updatedBy);
                this.dverUserService.updateDverUserDetails(userVO);
                return "redirect:/admin/users";
            } else {
                return "edit-company-admin";
            }
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("submitEditCompanyForAdmin method of DverAdminController \n " + ex);
            logger.error("Error in submitEditCompanyForAdmin()....." + ex);
            return "error";
        }
    }

    private void validateEditCompanyForAdmin(DverUserVO userVO, BindingResult errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "companyName", "required.companyName",
                "Company Name can not be blank.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "scac", "required.scac", "SCAC can not be blank.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "usDOT", "required.usDOT", "US DOT can not be blank.");
        if (!errors.hasErrors()) {
            validateScacAndDot(userVO, errors);
        }
    }

    private void validateScacAndDot(DverUserVO userVO, BindingResult errors) {
        DverUserVO dverUserVO = this.dverRegistrationService.fetchUserWithSCACAndType(userVO.getScac(),
                userVO.getRole().toUpperCase());
        if (dverUserVO != null) {
            if (!dverUserVO.getDverUserId().equals(userVO.getDverUserId())) {
                errors.rejectValue("scac", "scac.nonunique",
                        "The provided SCAC code already exists for " + dverUserVO.getRole() + " user.");
            }
        }

        dverUserVO = this.dverRegistrationService.fetchUserWithDOTAndType(userVO.getUsDOT(),
                userVO.getRole().toUpperCase());
        if (dverUserVO != null) {
            if (!dverUserVO.getDverUserId().equals(userVO.getDverUserId())) {
                errors.rejectValue("usDOT", "usdot.nonunique",
                        "The provided DOT code already exists for " + dverUserVO.getRole() + " user.");
            }
        }
    }

    @RequestMapping(value = "/admin/bulkChangeOwnerXLS", method = RequestMethod.POST)
    public @ResponseBody String performBulkChangeOwnerWithXLS(MultipartHttpServletRequest request,
            HttpServletResponse response) {
        Iterator<String> itr = request.getFileNames();
        if (!itr.hasNext()) {
            return "Please provide XLS file to process.";
        }
        MultipartFile bulkFile = request.getFile(itr.next());
        logger.info(bulkFile.getOriginalFilename() + " uploaded!");
        try {
            String extension = FilenameUtils.getExtension(bulkFile.getOriginalFilename());
            if (extension.equalsIgnoreCase("xls")) {
                if (bulkFile.getSize() == 0) {
                    return "Uploaded file should not be empty.";
                }

                if (bulkFile.getSize() > 2097152) {
                    return "Uploaded file should not exceed 2 MB";
                }
                Map<Integer, String[]> dversToBeProcessed = this.dverDetailsService
                        .findDversForBulkProcessing(bulkFile.getInputStream());

                if (dversToBeProcessed.isEmpty()) {
                    return "No DVER's found for 'Change Owner Bulk Processing'.";
                } else {
                    int successCount = 0;
                    int failCount = 0;
                    StringBuilder failDverDetails = new StringBuilder(
                            "DVER Bulk Change Owner XLS processed successfully. <br/>");
                    failDverDetails.append(
                            "Following is the list of DVER's which were not processed successfully for Bulk Change Owner: <br/>");

                    for (Integer dverDetailId : dversToBeProcessed.keySet()) {
                        String[] dots = dversToBeProcessed.get(dverDetailId);

                        RejectedDverVO rejectedDverVO = new RejectedDverVO();

                        rejectedDverVO.setDverDetailId(dverDetailId);

                        rejectedDverVO.setIepdot(dots[0] != null ? dots[0] : "");
                        rejectedDverVO.setMcdot(dots[1] != null ? dots[1] : "");

                        rejectedDverVO.setIepUserId(0);
                        rejectedDverVO.setMcUserId(0);

                        StringBuilder errors = new StringBuilder();
                        validateDOTFields(rejectedDverVO, errors);
                        if (errors.length() == 0) {
                            this.dverDetailsService.moveRejectedDverToFound(rejectedDverVO, dverDetailId);
                            successCount++;
                        } else {
                            failCount++;
                            failDverDetails.append("(" + failCount + ") &nbsp;");
                            failDverDetails.append("DverDetailId : " + dverDetailId + " <br/>");
                            failDverDetails.append("MC DOT: " + rejectedDverVO.getMcdot() + " <br/>");
                            failDverDetails.append("IEP DOT: " + rejectedDverVO.getMcdot() + " <br/>");
                            failDverDetails.append("Reason for failure: " + errors.toString() + " <br/>");
                        }
                    }

                    if (failCount > 0) {
                        logger.info("Fail DVER Notice :" + failDverDetails.toString());
                        DVERUtil.sendBulkUpdateFailureNotice(failDverDetails.toString());
                    }

                    return "Change Owner for " + successCount
                            + " DVER's completed successfully. Failed to complete " + failCount
                            + " DVER's due to wrong provided values of IEP/MC DOTs";
                }
            } else {
                return "The uploaded file type is not allowed.";
            }
        } catch (Exception e) {
            DVERUtil.sendExceptionEmails("upload method of DverAdminController \n " + e);
            logger.error("Error in submitEditCompanyForAdmin()....." + e);
            return "The uploaded file could not be processed!!";
        }
    }

    @RequestMapping(value = "/admin/bulkChangeOwnerWeb/{dverDetailIds}", method = RequestMethod.GET)
    public String setupBulkChangeOwnerWithWeb(final Model model,
            @PathVariable("dverDetailIds") String selectedDverDetailIds, HttpServletRequest request) {
        try {
            logger.info("setupBulkChangeOwnerWithWeb........");
            RejectedDverVO rejectedDverVO = new RejectedDverVO();
            rejectedDverVO.setSelectedDverDetailIds(selectedDverDetailIds);
            model.addAttribute("rejectedDverVO", rejectedDverVO);
            return "change-owner";
        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("setupBulkChangeOwnerWithWeb method of DverAdminController \n " + ex);
            logger.error("setupBulkChangeOwnerWithWeb method of DverAdminController \n " + ex);
            return "error";
        }
    }

    @RequestMapping(value = "/admin/bulkChangeOwnerWeb", method = RequestMethod.POST)
    public @ResponseBody String performBulkChangeOwnerWithWeb(
            @RequestParam(value = "mcdot", required = false, defaultValue = "") String mcdot,
            @RequestParam(value = "iepdot", required = false, defaultValue = "") String iepdot,
            @RequestParam(value = "selectedDverDetailIds", required = false, defaultValue = "") String selectedDverDetailIds) {
        try {
            StringBuilder errors = new StringBuilder();

            if (!StringUtils.hasText(mcdot) && !StringUtils.hasText(iepdot)) {
                errors.append("Please enter MC/IEP DOT value. <br/> ");
            }

            RejectedDverVO rejectedDverVO = null;
            if (errors.length() == 0) {
                rejectedDverVO = new RejectedDverVO();
                rejectedDverVO.setIepdot(iepdot);
                rejectedDverVO.setMcdot(mcdot);
                rejectedDverVO.setIepUserId(0);
                rejectedDverVO.setMcUserId(0);
                validateDOTFields(rejectedDverVO, errors);
            }

            if (errors.length() == 0 && rejectedDverVO != null) {
                String[] dverDetailIds = selectedDverDetailIds.split(",");
                for (String dverDetailId : dverDetailIds) {
                    this.dverDetailsService.moveRejectedDverToFound(rejectedDverVO, Integer.parseInt(dverDetailId));
                }
                return "success";
            } else {
                return errors.toString();
            }

        } catch (Exception ex) {
            DVERUtil.sendExceptionEmails("setupUpdateDVEROwnerPage method of DverAdminController \n " + ex);
            logger.error("setupUpdateDVEROwnerPage method of DverAdminController \n " + ex);
            return "error";
        }
    }

    public DverDetailsService getDverDetailsService() {
        return dverDetailsService;
    }

    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 dverRegistrationService
     */
    public DverRegistrationService getDverRegistrationService() {
        return dverRegistrationService;
    }

    /**
     * @param dverRegistrationService
     *          the dverRegistrationService to set
     */
    public void setDverRegistrationService(DverRegistrationService dverRegistrationService) {
        this.dverRegistrationService = dverRegistrationService;
    }
}