Java tutorial
/* * 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.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; 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.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.util.WebUtils; import com.iana.dver.controller.validators.RegistrationValidator; import com.iana.dver.domain.DverUsers; import com.iana.dver.service.DverRegistrationService; import com.iana.dver.util.DVERUtil; import com.iana.dver.vo.DverConfigVO; import com.iana.dver.vo.DverRegistrationVO; import com.iana.dver.vo.DverUserLoginVO; 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 03-Sep-2013 * */ @Controller @RequestMapping("/register") @SessionAttributes({ "registrationVO" }) public class RegistrationController { @Autowired private DverRegistrationService dverRegistrationService; @Autowired private RegistrationValidator registrationValidator; @Autowired private ServletContext servletContext; private static final Logger logger = Logger.getLogger(RegistrationController.class); @RequestMapping(method = RequestMethod.GET) public String setupRegistrationProcess(final ModelMap model) { logger.info("Start Registration Process...."); try { DverRegistrationVO registrationVO = DverRegistrationVO.resetOrPrepareNew(); registrationVO.setDverUserVO(new DverUserVO()); registrationVO.setDverUserLoginVO(new DverUserLoginVO()); registrationVO.setDverConfigVO(new DverConfigVO()); model.addAttribute("registrationVO", registrationVO); return "step1"; } catch (Exception ex) { DVERUtil.sendExceptionEmails("setupRegistrationProcess method of RegistrationController \n " + ex); logger.error("Error in setupRegistrationProcess....." + ex); return "error"; } } @RequestMapping(method = RequestMethod.POST) public String completeDverRegistration(HttpServletRequest request, HttpServletResponse response, final RedirectAttributes redirectAttributes, @ModelAttribute("registrationVO") DverRegistrationVO registrationVO, BindingResult result, SessionStatus status, @RequestParam("_page") int currentPage, Model model) throws IOException, DocumentException, AddressException { logger.info("Complete Registration Process...."); try { Map<Integer, String> registerationPages = new HashMap<Integer, String>(); request.getSession().getAttribute("registrationVO"); registerationPages.put(0, "step1"); registerationPages.put(1, "step2"); registerationPages.put(2, "step3"); if (request.getParameter("_cancel") != null) { registrationVO = DverRegistrationVO.resetOrPrepareNew(); redirectAttributes.addFlashAttribute("error", "DVER Registration Cancelled by User."); return "redirect:/login"; } else if (request.getParameter("_finish") != null) { this.registrationValidator.validate(registrationVO, result); if (!result.hasErrors()) { String country = this.countries().get(registrationVO.getDverUserVO().getCountryId()); registrationVO.getDverUserVO().setCountry(country); DverUsers dverUser = dverRegistrationService.saveRegistrationDetails(registrationVO); if (dverUser != null) { sendRegDetailEmail(registrationVO.getDverUserVO(), registrationVO.getDverUserLoginVO(), registrationVO.getDverConfigVO()); } redirectAttributes.addFlashAttribute("successMsg", "DVER Registration completed successfully."); status.setComplete(); return "redirect:/login"; } else { return registerationPages.get(currentPage); } } else { int targetPage = WebUtils.getTargetPage(request, "_target", currentPage); if (targetPage > currentPage) { switch (currentPage) { case 0: this.registrationValidator.validateStep1(registrationVO.getDverUserVO(), result); break; case 1: this.registrationValidator.validateStep2(registrationVO.getDverUserLoginVO(), result); break; case 2: this.registrationValidator.validateStep3(registrationVO.getDverConfigVO(), result); break; } if (result.hasErrors()) { return registerationPages.get(currentPage); } else { if (targetPage == 2) { logger.info("copying the values from First Screen.. :-P"); DverConfigVO configVO = new DverConfigVO(); configVO.setFirstName(registrationVO.getDverUserVO().getFirstName()); configVO.setLastName(registrationVO.getDverUserVO().getLastName()); configVO.setEmail(registrationVO.getDverUserVO().getEmail()); configVO.setTitle(registrationVO.getDverUserVO().getTitle()); configVO.setPhone(registrationVO.getDverUserVO().getPhone()); configVO.setFax(registrationVO.getDverUserVO().getFax()); registrationVO.setDverConfigVO(configVO); } return registerationPages.get(targetPage); } } else { return registerationPages.get(targetPage); } } } catch (Exception ex) { DVERUtil.sendExceptionEmails("completeDverRegistration method of RegistrationController \n " + ex); logger.error("Error in completeDverRegistration....." + ex); return "error"; } } private void sendRegDetailEmail(DverUserVO dverUserVO, DverUserLoginVO dverUserLoginVO, DverConfigVO dverConfigVO) throws IOException, DocumentException, AddressException { logger.info("Send Registration Email....."); try { PdfReader reader = new PdfReader( servletContext.getResourceAsStream("/WEB-INF/email_templates/DVER_REGISTRATION_FORM.pdf")); File tempFile = File.createTempFile("DVER_REGISTRATION_" + dverUserVO.getUsDOT(), ".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]", dverUserVO.getFirstName() + " " + dverUserVO.getLastName()); form.setField("topmostSubform[0].Page1[0].company[0]", dverUserVO.getCompanyName()); form.setField("topmostSubform[0].Page1[0].address[0]", dverUserVO.getAddress1() + " " + dverUserVO.getAddress2()); form.setField("topmostSubform[0].Page1[0].city[0]", dverUserVO.getCity() + ", " + dverUserVO.getState() + " " + dverUserVO.getZipCode()); form.setField("topmostSubform[0].Page1[0].scac[0]", dverUserVO.getScac()); form.setField("topmostSubform[0].Page1[0].pwd[0]", dverUserLoginVO.getPassword()); filledOutForm.setFormFlattening(Boolean.TRUE); filledOutForm.close(); DVERUtil.sendEmailWithAttachments("admin@dver.intermodal.org", "DVER Registration Confirmation", new InternetAddress[] { new InternetAddress(dverUserVO.getEmail()) }, "Please see attached for your registration details.", tempFile); if (!dverUserVO.getEmail().equals(dverConfigVO.getEmail())) { PdfReader reader1 = new PdfReader( servletContext.getResourceAsStream("/WEB-INF/email_templates/DVER_REGISTRATION_FORM.pdf")); File tempFile1 = File.createTempFile("DVER_REGISTRATION_NOTIF_" + dverUserVO.getUsDOT(), ".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]", dverConfigVO.getFirstName() + " " + dverConfigVO.getLastName()); form1.setField("topmostSubform[0].Page1[0].company[0]", dverUserVO.getCompanyName()); form1.setField("topmostSubform[0].Page1[0].address[0]", dverUserVO.getAddress1() + " " + dverUserVO.getAddress2()); form1.setField("topmostSubform[0].Page1[0].city[0]", dverUserVO.getCity() + ", " + dverUserVO.getState() + " " + dverUserVO.getZipCode()); form1.setField("topmostSubform[0].Page1[0].scac[0]", dverUserVO.getScac()); form1.setField("topmostSubform[0].Page1[0].pwd[0]", dverUserLoginVO.getPassword()); filledOutForm1.setFormFlattening(Boolean.TRUE); filledOutForm1.close(); DVERUtil.sendEmailWithAttachments("admin@dver.intermodal.org", "DVER Registration Confirmation", new InternetAddress[] { new InternetAddress(dverConfigVO.getEmail()) }, "Please see attached for your registration details.", tempFile1); } tempFile.deleteOnExit(); } catch (Exception ex) { logger.error("Error in sendRegDetailEmail....." + ex); DVERUtil.sendExceptionEmails("sendRegDetailEmail method of RegistrationController \n " + ex); } } @ModelAttribute("userTypes") public Map<Integer, String> userType() { Map<Integer, String> userTypes = new HashMap<Integer, String>(); userTypes.put(0, "Select User Type"); userTypes.put(2, "IEP"); userTypes.put(3, "MC"); return userTypes; } @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 = "/verifyUsDot", method = RequestMethod.GET) public @ResponseBody String verifyUsDot(@RequestParam("usdot") String usdot, @RequestParam("userType") String userType, @ModelAttribute("registrationVO") DverRegistrationVO registrationVO, BindingResult result) { try { if (usdot == null || usdot.equalsIgnoreCase("")) { return "USDOT can not be blank."; } else if (userType.equalsIgnoreCase("Select User Type")) { return "Please select USER TYPE first."; } else { if (this.registrationValidator.isUsDotExists(usdot, userType)) { return "The provided DOT code already exists for " + userType + " user."; } } return "success"; } catch (Exception ex) { logger.error("Error in verifyUsDot....." + ex); DVERUtil.sendExceptionEmails("verifyUsDot method of RegistrationController \n " + ex); return "error"; } } @RequestMapping(value = "/verifyScac", method = RequestMethod.GET) public @ResponseBody String verifyScac(@RequestParam("scac") String scac, @RequestParam("userType") String userType, @ModelAttribute("registrationVO") DverRegistrationVO registrationVO, BindingResult result) { try { if (scac == null || scac.equalsIgnoreCase("")) { return "SCAC Code can not be blank."; } else if (userType.equalsIgnoreCase("Select User Type")) { return "Please select USER TYPE first."; } else { if (this.registrationValidator.isScacExists(scac, userType)) { return "The provided SCAC code already exists for " + userType + " user."; } } return "success"; } catch (Exception ex) { logger.error("Error in verifyScac....." + ex); DVERUtil.sendExceptionEmails("verifyScac method of RegistrationController \n " + ex); return "error"; } } @RequestMapping(value = "/verifyEmail", method = RequestMethod.GET) public @ResponseBody String verifyEmail(@RequestParam("email") String email, @ModelAttribute("registrationVO") DverRegistrationVO registrationVO, BindingResult result) { try { if (email == null || email.equalsIgnoreCase("")) { return "Email can not be blank."; } else { if (this.registrationValidator.isEmailExists(email)) { return "The provided Email address already exists"; } } return "success"; } catch (Exception ex) { DVERUtil.sendExceptionEmails("verifyEmail method of RegistrationController \n " + ex); logger.error("Error in verifyEmail....." + ex); return "error"; } } @RequestMapping(value = "/verifyUserName", method = RequestMethod.GET) public @ResponseBody String verifyUserName(@RequestParam("userName") String userName, @ModelAttribute("registrationVO") DverRegistrationVO registrationVO, BindingResult result) { try { if (userName == null || userName.equalsIgnoreCase("")) { return "User Name can not be blank."; } else { if (this.registrationValidator.isUserNameExists(userName)) { return "The provided User Name is already taken."; } } return "success"; } catch (Exception ex) { DVERUtil.sendExceptionEmails("verifyUserName method of RegistrationController \n " + ex); logger.error("Error in verifyUserName....." + ex); return "error"; } } @RequestMapping(value = "/verifyConfigEmail", method = RequestMethod.GET) public @ResponseBody String verifyConfigEmail(@RequestParam("email") String email, @ModelAttribute("registrationVO") DverRegistrationVO registrationVO, BindingResult result) { try { if (email == null || email.equalsIgnoreCase("")) { return "Email can not be blank."; } else { if (this.registrationValidator.isConfigEmailExists(email)) { return "The provided Email address already exists"; } } return "success"; } catch (Exception ex) { DVERUtil.sendExceptionEmails("verifyConfigEmail method of RegistrationController \n " + ex); logger.error("Error in verifyConfigEmail....." + ex); return "error"; } } public DverRegistrationService getDverRegistrationService() { return dverRegistrationService; } public void setDverRegistrationService(DverRegistrationService dverRegistrationService) { this.dverRegistrationService = dverRegistrationService; } public RegistrationValidator getRegistrationValidator() { return registrationValidator; } public void setRegistrationValidator(RegistrationValidator registrationValidator) { this.registrationValidator = registrationValidator; } }