Java tutorial
package com.abm.mainet.water.ui.model; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.map.ObjectMapper; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.abm.mainet.common.constant.CFCConstants; import com.abm.mainet.common.constant.MainetConstants; import com.abm.mainet.common.domain.ApplicationPortalMaster; import com.abm.mainet.common.domain.PortalService; import com.abm.mainet.common.dto.ApplicantDetailDTO; import com.abm.mainet.common.dto.ChargeDetailDTO; import com.abm.mainet.common.dto.CheckListModel; import com.abm.mainet.common.dto.CommonChallanDTO; import com.abm.mainet.common.dto.DocumentDetailsVO; import com.abm.mainet.common.exception.FrameworkException; import com.abm.mainet.common.service.IPortalServiceMasterService; import com.abm.mainet.common.ui.model.AbstractFormModel; import com.abm.mainet.common.ui.validator.CommonOfflineMasterValidator; import com.abm.mainet.common.util.ApplicationSession; import com.abm.mainet.common.util.UserSession; import com.abm.mainet.common.util.Utility; import com.abm.mainet.common.utility.CommonMasterUtility; import com.abm.mainet.common.utility.LookUp; import com.abm.mainet.dms.utility.FileUploadUtility; import com.abm.mainet.integration.ws.JersyCall; import com.abm.mainet.integration.ws.dto.WSRequestDTO; import com.abm.mainet.integration.ws.dto.WSResponseDTO; import com.abm.mainet.payment.dto.PaymentRequestDTO; import com.abm.mainet.payment.service.IChallanService; import com.abm.mainet.smsemail.dto.SMSAndEmailDTO; import com.abm.mainet.smsemail.service.ISMSAndEmailService; import com.abm.mainet.water.dto.PlumberExperienceDTO; import com.abm.mainet.water.dto.PlumberLicenseRequestDTO; import com.abm.mainet.water.dto.PlumberLicenseResponseDTO; import com.abm.mainet.water.dto.PlumberQualificationDTO; import com.abm.mainet.water.dto.WaterRateMaster; import com.abm.mainet.water.service.IChangeOfOwnershipService; import com.abm.mainet.water.service.PlumberLicenseFormServiceImpl; @Component @Scope("session") public class PlumberLicenseFormModel extends AbstractFormModel implements Serializable { private static final long serialVersionUID = 323258174303895439L; @Resource private transient IChangeOfOwnershipService changeOfOwnerShipService; @Autowired private IPortalServiceMasterService iPortalService; @Autowired private IChallanService iChallanService; @Autowired private ISMSAndEmailService ismsAndEmailService; private static final Logger LOGGER = LoggerFactory.getLogger(PlumberLicenseFormModel.class); private FileUploadUtility fileupload; private JersyCall jersyCall; private PlumberLicenseRequestDTO plumberLicenseReqDTO; private List<PlumberQualificationDTO> plumberQualificationDTOList = new ArrayList<PlumberQualificationDTO>(); private List<PlumberExperienceDTO> plumberExperienceDTOList = new ArrayList<PlumberExperienceDTO>(); private Long deptId; private List<DocumentDetailsVO> checkList; private String isFree; private double amountToPay; private String checkListNCharges; private String plumberImage; private double totalExp; /** * This method is used for getting checklist and charges. */ public void findApplicableCheckListAndCharges(long serviceId, long orgId) { // [START] BRMS call initialize model WSRequestDTO dto = new WSRequestDTO(); dto.setModelName("ChecklistModel|WaterRateMaster"); WSResponseDTO response = JersyCall.callBRMS(dto, "/BRMS/getInitializedModel"); if (MainetConstants.WebServiceStatus.SUCCESS.equalsIgnoreCase(response.getWsStatus())) { List<Object> checklistModel = JersyCall.castResponse(response, CheckListModel.class, 0); List<Object> waterRateMasterList = JersyCall.castResponse(response, WaterRateMaster.class, 1); CheckListModel checkListModel2 = (CheckListModel) checklistModel.get(0); WaterRateMaster WaterRateMaster = (WaterRateMaster) waterRateMasterList.get(0); checkListModel2.setOrgId(orgId); checkListModel2.setServiceCode(MainetConstants.ServiceShortCode.PlUMBER_LICENSE); checkListModel2.setIsBPL(this.getApplicantDetailDto().getIsBPL()); dto.setDataModel(checkListModel2); response = JersyCall.callBRMS(dto, "/BRMS/getCheckList"); if (MainetConstants.WebServiceStatus.SUCCESS.equalsIgnoreCase(response.getWsStatus())) { List<?> docs = JersyCall.castResponse(response, DocumentDetailsVO.class); this.setCheckList((List<DocumentDetailsVO>) docs); //checklist done WaterRateMaster.setOrgId(orgId); WaterRateMaster.setServiceCode(MainetConstants.ServiceShortCode.PlUMBER_LICENSE); WaterRateMaster.setChargeApplicableAt( Long.toString(CommonMasterUtility.getValueFromPrefixLookUp("APL", "CAA").getLookUpId())); dto.setDataModel(WaterRateMaster); WSResponseDTO res = JersyCall.callBRMS(dto, "/WaterServiceCharge/initializeOtherFieldsForTaxes"); if (MainetConstants.WebServiceStatus.SUCCESS.equalsIgnoreCase(res.getWsStatus())) { if (!res.isFree()) { List<?> rates = JersyCall.castResponse(res, WaterRateMaster.class); List<WaterRateMaster> requiredCHarges = new ArrayList<WaterRateMaster>(); for (Object rate : rates) { WaterRateMaster master1 = (WaterRateMaster) rate; master1.setOrgId(orgId); master1.setServiceCode(MainetConstants.ServiceShortCode.PlUMBER_LICENSE); master1.setIsBPL(this.getApplicantDetailDto().getIsBPL()); requiredCHarges.add(master1); } dto.setDataModel(requiredCHarges); WSResponseDTO output = JersyCall.callBRMS(dto, "/WaterServiceCharge/serviceCharge"); List<ChargeDetailDTO> detailDTOs = output.getCharges(); this.setChargesInfo(detailDTOs); this.setAmountToPay(chargesToPay(detailDTOs)); this.setIsFree("N"); this.getOfflineDTO().setAmountToShow(this.getAmountToPay()); } else { this.setIsFree(MainetConstants.Common_Constant.FREE); } } else { throw new FrameworkException( "Problem while checking Application level charges applicable or not."); } } else { throw new FrameworkException( "Problem while checking Application level charges and Checklist applicable or not."); } } else { throw new FrameworkException( "Problem while checking Application level charges and Checklist applicable or not."); } // [END] } private double chargesToPay(List<ChargeDetailDTO> charges) { double amountSum = 0.0; for (ChargeDetailDTO charge : charges) { amountSum = amountSum + charge.getChargeAmount(); } return amountSum; } /** * This method is used for validating saving data */ @Override @SuppressWarnings({ "unchecked", "static-access" }) public boolean saveForm() { try { ApplicantDetailDTO applicantDetailDTO = this.getApplicantDetailDto(); PlumberLicenseRequestDTO requestDTO = this.getPlumberLicenseReqDTO(); requestDTO.setPlumberFName(applicantDetailDTO.getApplicantFirstName()); requestDTO.setPlumberMName(applicantDetailDTO.getApplicantMiddleName()); requestDTO.setPlumberLName(applicantDetailDTO.getApplicantLastName()); requestDTO.setPlumSex(applicantDetailDTO.getGender()); requestDTO.setPlumAppDate(new Date()); List<DocumentDetailsVO> docs = this.getCheckList(); docs = setFileUploadMethod(docs); requestDTO.setDocumentList(docs); boolean result = validateInputs(requestDTO, this.getPlumberImage()); CommonChallanDTO offline = this.getOfflineDTO(); String modeDesc = getNonHierarchicalLookUpObject(offline.getOflPaymentMode()).getLookUpCode(); offline.setOfflinePaymentText(modeDesc); if (offline.getOnlineOfflineCheck() == null || offline.getOnlineOfflineCheck().isEmpty()) { validateBean(offline, CommonOfflineMasterValidator.class); } if (hasValidationErrors() || result) { return false; } setUpdateFields(requestDTO); requestDTO.setDocumentList(this.getCheckList()); requestDTO.setServiceId(this.getServiceId()); requestDTO.setDeptId(this.getDeptId()); requestDTO.setApplicant(this.getApplicantDetailDto()); requestDTO.setPlumberExperienceDTOList(this.getPlumberExperienceDTOList()); requestDTO.setPlumberQualificationDTOList(this.getPlumberQualificationDTOList()); LinkedHashMap<Long, Object> responseVo = (LinkedHashMap<Long, Object>) jersyCall .callRestTemplateClient(requestDTO, "PlumberLicense/savePlumberLicenseData"); String response = new JSONObject(responseVo).toString(); PlumberLicenseResponseDTO outPutObject = new ObjectMapper().readValue(response, PlumberLicenseResponseDTO.class); if (outPutObject.getApplicationId() != null) { if (this.getAmountToPay() > 0d) { ApplicationPortalMaster applicationMaster = null; requestDTO.setApplicationId(outPutObject.getApplicationId()); try { applicationMaster = saveApplcationMaster(this.getServiceId(), outPutObject.getApplicationId(), FileUploadUtility.getCurrent().getFileMap().entrySet().size()); } catch (Exception e) { logger.error("Exception occured in Water Reconnection save form:", e); } iPortalService.saveApplicationMaster(applicationMaster, this.getAmountToPay(), FileUploadUtility.getCurrent().getFileMap().entrySet().size()); if (offline.getOnlineOfflineCheck() != null && offline.getOnlineOfflineCheck().equals(CFCConstants.PAYMENT_TYPE.OFFLINE)) { setChallanDToandSaveChallanData(offline, this.getApplicantDetailDto(), outPutObject); } this.setSuccessMessage("Your application no:" + outPutObject.getApplicationId() + " for Plumber License has been saved successfully."); sendMailAndSms(outPutObject); } else { logger.error("Exception occured while saving application"); this.setSuccessMessage( "Sorry,Your application for Plumber has not been saved due to some technical problem."); } } } catch (IOException e) { logger.error("Exception occured in Plumber License save form:", e); return false; } return true; } public ApplicationPortalMaster saveApplcationMaster(Long serviceId, Long applicationNo, int documentListSize) throws Exception { PortalService appealMaster = iPortalService.getService(serviceId, UserSession.getCurrent().getOrganisation().getOrgid()); ApplicationPortalMaster applicationMaster = new ApplicationPortalMaster(); calculateDate(appealMaster, applicationMaster, documentListSize); applicationMaster.setPamApplicationId(applicationNo); applicationMaster.setSmServiceId(serviceId); applicationMaster.setPamApplicationDate(new Date()); applicationMaster.updateAuditFields(); return applicationMaster; } public ApplicationPortalMaster calculateDate(PortalService portalService, ApplicationPortalMaster applicationMaster, int documentListSize) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); if (documentListSize > 0) { applicationMaster.setPamChecklistApp(MainetConstants.Common_Constant.YES); // Y } else { applicationMaster.setPamChecklistApp(MainetConstants.Common_Constant.NO); // N calendar.add(Calendar.DATE, 0); String output1 = sdf.format(calendar.getTime()); applicationMaster.setPamDocVerificationDate(sdf.parse(output1)); calendar.setTime(sdf.parse(output1)); calendar.add(Calendar.DATE, Integer.parseInt(portalService.getSlaDays().toString())); String output2 = sdf.format(calendar.getTime()); applicationMaster.setPamSlaDate(sdf.parse(output2)); calendar.setTime(sdf.parse(output2)); calendar.add(Calendar.DATE, Integer.parseInt(portalService.getFirstAppealDuration().toString())); String output3 = sdf.format(calendar.getTime()); applicationMaster.setPamFirstAppealDate(sdf.parse(output3)); calendar.setTime(sdf.parse(output3)); calendar.add(Calendar.DATE, Integer.parseInt(portalService.getSecondAppealDuration().toString())); String output4 = sdf.format(calendar.getTime()); applicationMaster.setPamSecondAppealDate(sdf.parse(output4)); } return applicationMaster; } /** * This method is used for generating byte code for uploaded files * * @param docs * is list of uploaded file * @return uploaded file name and byte code */ @SuppressWarnings("static-access") private List<DocumentDetailsVO> setFileUploadMethod(List<DocumentDetailsVO> docs) { Map<Long, String> listOfString = new HashMap<Long, String>(); Map<Long, String> fileName = new HashMap<Long, String>(); if (fileupload.getCurrent().getFileMap() != null && !fileupload.getCurrent().getFileMap().isEmpty()) { for (Iterator<Entry<Long, Set<File>>> it = FileUploadUtility.getCurrent().getFileMap().entrySet() .iterator(); it.hasNext();) { Entry<Long, Set<File>> entry = it.next(); if (entry.getKey().longValue() == 0) { it.remove(); break; } } for (Map.Entry<Long, Set<File>> entry : fileupload.getCurrent().getFileMap().entrySet()) { List<File> list = new ArrayList<File>(entry.getValue()); for (File file : list) { try { Base64 base64 = new Base64(); String bytestring = base64.encodeToString(FileUtils.readFileToByteArray(file)); fileName.put(entry.getKey(), file.getName()); listOfString.put(entry.getKey(), bytestring); } catch (IOException e) { logger.error("Exception has been occurred in file byte to string conversions", e); } } } } if (!docs.isEmpty() && !listOfString.isEmpty()) { for (DocumentDetailsVO d : docs) { long count = d.getDocumentSerialNo(); if (listOfString.containsKey(count) && fileName.containsKey(count)) { d.setDocumentByteCode(listOfString.get(count)); d.setDocumentName(fileName.get(count)); } } } return docs; } /** * This method is used for set common field */ private void setUpdateFields(PlumberLicenseRequestDTO plumberDTO) { UserSession session = UserSession.getCurrent(); plumberDTO.setUserId(session.getEmployee().getEmpId()); plumberDTO.setLangId((long) session.getLanguageId()); plumberDTO.setOrgId(session.getOrganisation().getOrgid()); plumberDTO.setLgIpMac(Utility.getMacAddress()); } /** * This is method used to save challan details. * * @param offline * is offline details * @param applicantDetailDto * is applicant details * @param outPutObject * is application related details */ private void setChallanDToandSaveChallanData(CommonChallanDTO offline, ApplicantDetailDTO applicantDetailDto, PlumberLicenseResponseDTO outPutObject) { offline.setApplNo(outPutObject.getApplicationId()); offline.setAmountToPay(String.valueOf(this.getAmountToPay())); offline.setUserId(UserSession.getCurrent().getEmployee().getEmpId()); offline.setOrgId(UserSession.getCurrent().getOrganisation().getOrgid()); offline.setLangId(UserSession.getCurrent().getLanguageId()); offline.setLgIpMac(Utility.getMacAddress()); offline.setEmailId(applicantDetailDto.getEmailId()); offline.setApplicantName(applicantDetailDto.getApplicantFirstName()); offline.setMobileNumber(applicantDetailDto.getMobileNo()); offline.setChallanServiceType(CFCConstants.CHALLAN_RECEIPT_TYPE.NON_REVENUE_BASED); offline.setServiceId(this.getServiceId()); if (outPutObject.getUploadedDocSize() > 0) { offline.setDocumentUploaded(true); } else { offline.setDocumentUploaded(false); } for (ChargeDetailDTO charges : this.getChargesInfo()) { offline.getFeeIds().put(charges.getChargeCode(), charges.getChargeAmount()); } offline.setDeptId(this.getDeptId()); offline.setOfflinePaymentText(CommonMasterUtility.getNonHierarchicalLookUpObject( offline.getOflPaymentMode(), UserSession.getCurrent().getOrganisation()).getLookUpCode()); if (offline.getOnlineOfflineCheck() != null && offline.getOnlineOfflineCheck().equals(CFCConstants.PAYMENT_TYPE.OFFLINE)) { offline = iChallanService.generateChallanNumber(offline); } this.setOfflineDTO(offline); } /** * This method is used for Online Payment PayU parameter. */ @Override public void redirectToPayDetails(HttpServletRequest httpServletRequest, PaymentRequestDTO payURequestDTO) { PlumberLicenseRequestDTO dto = this.getPlumberLicenseReqDTO(); ApplicantDetailDTO applicant = this.getApplicantDetailDto(); String userName = (applicant.getApplicantFirstName() == null ? "" : applicant.getApplicantFirstName() + " "); userName += applicant.getApplicantMiddleName() == null ? "" : applicant.getApplicantMiddleName() + " "; userName += applicant.getApplicantLastName() == null ? "" : applicant.getApplicantLastName(); PortalService portalServiceMaster = iPortalService.getService(dto.getServiceId(), UserSession.getCurrent().getOrganisation().getOrgid()); payURequestDTO.setUdf3("CitizenHome.html"); payURequestDTO.setUdf5(portalServiceMaster.getShortName()); payURequestDTO.setUdf7(String.valueOf(dto.getApplicationId())); payURequestDTO.setServiceId(portalServiceMaster.getServiceId()); payURequestDTO.setUdf6(applicant.getCfcCitizenId()); payURequestDTO.setApplicationId(dto.getApplicationId()); payURequestDTO.setDueAmt(this.getAmountToPay()); payURequestDTO.setEmail(applicant.getEmailId()); payURequestDTO.setMobNo(applicant.getMobileNo()); payURequestDTO.setApplicantName(userName); if (portalServiceMaster != null) { payURequestDTO.setUdf10(String.valueOf(portalServiceMaster.getPsmDpDeptid())); if (UserSession.getCurrent().getLanguageId() == MainetConstants.ENGLISH) { payURequestDTO.setServiceName(portalServiceMaster.getServiceName()); } else { payURequestDTO.setServiceName(portalServiceMaster.getServiceNameReg()); } } this.loadQualifire(PlumberLicenseFormServiceImpl.class); } /** * This method is used for validate User Details */ private boolean validateInputs(PlumberLicenseRequestDTO dto, String plumberPhoto) { boolean flag = false; if (dto.getDocumentList() != null && !dto.getDocumentList().isEmpty()) { for (DocumentDetailsVO doc : dto.getDocumentList()) { if (doc.getCheckkMANDATORY().equals("Y")) { if (doc.getDocumentByteCode() == null) { addValidationError(ApplicationSession.getInstance() .getMessage("water.plumberLicense.valMsg.uploadDocument")); flag = true; break; } } } } if (plumberPhoto == null || MainetConstants.BLANK.equals(plumberPhoto)) { addValidationError( ApplicationSession.getInstance().getMessage("water.plumberLicense.valMsg.uploadPlumberPhoto")); flag = true; } return flag; } /** * This method is used for send SMS and Email to Applicant. */ private void sendMailAndSms(PlumberLicenseResponseDTO response) { SMSAndEmailDTO dto = new SMSAndEmailDTO(); dto.setAppNo(String.valueOf(response.getApplicationId())); dto.setEmail(this.getApplicantDetailDto().getEmailId()); dto.setMobnumber(this.getApplicantDetailDto().getMobileNo()); dto.setAppName(applicantFullName()); dto.setAppAmount(Double.toString(getAmountToPay())); dto.setV_muncipality_name(UserSession.getCurrent().getLanguageId() == 1 ? UserSession.getCurrent().getOrganisation().getONlsOrgname() : UserSession.getCurrent().getOrganisation().getONlsOrgnameMar()); dto.setLangId(UserSession.getCurrent().getLanguageId()); dto.setDeptShortCode("WT"); dto.setServiceUrl("PlumberLicenseForm.html"); if (this.getAmountToPay() == 0.0d) { dto.setTemplateType(this.getCheckList().size() == 0 ? "N" : "C"); dto.setTransactionType("N"); } else { dto.setTemplateType("N"); dto.setTransactionType("Y"); } try { ismsAndEmailService.sendEmailAndSMS(dto, UserSession.getCurrent().getOrganisation().getOrgid()); } catch (Exception e) { LOGGER.error("Mail and SMS sending failed:", e); } } private String applicantFullName() { StringBuilder builder = new StringBuilder(); builder.append(titleDesc(getApplicantDetailDto().getApplicantTitle())); builder.append(" "); builder.append(getApplicantDetailDto().getApplicantFirstName() == null ? "" : getApplicantDetailDto().getApplicantFirstName()); builder.append(" "); builder.append(getApplicantDetailDto().getApplicantMiddleName() == null ? "" : getApplicantDetailDto().getApplicantMiddleName()); builder.append(" "); builder.append(getApplicantDetailDto().getApplicantLastName() == null ? "" : getApplicantDetailDto().getApplicantLastName()); return builder.toString(); } private String titleDesc(long title) { String titleDesc = StringUtils.EMPTY; List<LookUp> lookUps = CommonMasterUtility.getLookUps("TTL", UserSession.getCurrent().getOrganisation()); for (LookUp lookUp : lookUps) { if (lookUp.getLookUpId() == title) { titleDesc = lookUp.getLookUpDesc(); break; } } return titleDesc; } public List<PlumberExperienceDTO> getPlumberExperienceDTOList() { return plumberExperienceDTOList; } public void setPlumberExperienceDTOList(List<PlumberExperienceDTO> plumberExperienceDTOList) { this.plumberExperienceDTOList = plumberExperienceDTOList; } public List<PlumberQualificationDTO> getPlumberQualificationDTOList() { return plumberQualificationDTOList; } public void setPlumberQualificationDTOList(List<PlumberQualificationDTO> plumberQualificationDTOList) { this.plumberQualificationDTOList = plumberQualificationDTOList; } public Long getDeptId() { return deptId; } public void setDeptId(Long deptId) { this.deptId = deptId; } public List<DocumentDetailsVO> getCheckList() { return checkList; } public void setCheckList(List<DocumentDetailsVO> checkList) { this.checkList = checkList; } public String getIsFree() { return isFree; } public void setIsFree(String isFree) { this.isFree = isFree; } public double getAmountToPay() { return amountToPay; } public void setAmountToPay(double amountToPay) { this.amountToPay = amountToPay; } public String getCheckListNCharges() { return checkListNCharges; } public void setCheckListNCharges(String checkListNCharges) { this.checkListNCharges = checkListNCharges; } public PlumberLicenseRequestDTO getPlumberLicenseReqDTO() { return plumberLicenseReqDTO; } public void setPlumberLicenseReqDTO(PlumberLicenseRequestDTO plumberLicenseReqDTO) { this.plumberLicenseReqDTO = plumberLicenseReqDTO; } public String getPlumberImage() { return plumberImage; } public void setPlumberImage(String plumberImage) { this.plumberImage = plumberImage; } /** * @return the totalExp */ public double getTotalExp() { return totalExp; } /** * @param totalExp * the totalExp to set */ public void setTotalExp(double totalExp) { this.totalExp = totalExp; } }