List of usage examples for org.springframework.validation BindingResult rejectValue
void rejectValue(@Nullable String field, String errorCode, String defaultMessage);
From source file:org.training.storefront.controllers.pages.checkout.MultiStepCheckoutController.java
@RequestMapping(value = "/sop-response", method = RequestMethod.POST) @RequireHardLogIn/* w w w . j a va 2 s.c o m*/ public String doHandleSopResponse(final HttpServletRequest request, @Valid final SopPaymentDetailsForm sopPaymentDetailsForm, final BindingResult bindingResult, final Model model) throws CMSItemNotFoundException { final Map<String, String> resultMap = getRequestParameterMap(request); final boolean savePaymentInfo = sopPaymentDetailsForm.isSavePaymentInfo() || getCheckoutCustomerStrategy().isAnonymousCheckout(); final PaymentSubscriptionResultData paymentSubscriptionResultData = this.getPaymentFacade() .completeSopCreateSubscription(resultMap, savePaymentInfo); if (paymentSubscriptionResultData.isSuccess() && paymentSubscriptionResultData.getStoredCard() != null && StringUtils.isNotBlank(paymentSubscriptionResultData.getStoredCard().getSubscriptionId())) { final CCPaymentInfoData newPaymentSubscription = paymentSubscriptionResultData.getStoredCard(); if (getUserFacade().getCCPaymentInfos(true).size() <= 1) { getUserFacade().setDefaultPaymentInfo(newPaymentSubscription); } getCheckoutFacade().setPaymentDetails(newPaymentSubscription.getId()); } else if ((paymentSubscriptionResultData.getDecision() != null && paymentSubscriptionResultData.getDecision().equalsIgnoreCase("error")) || (paymentSubscriptionResultData.getErrors() != null && !paymentSubscriptionResultData.getErrors().isEmpty())) { // Have SOP errors that we can display if (!hasValidCart()) { LOG.info("Missing, empty or unsupported cart"); return REDIRECT_URL_CART; } setupAddPaymentPage(model); // Build up the SOP form data and render page containing form try { setupSilentOrderPostPage(sopPaymentDetailsForm, model); } catch (final Exception e) { LOG.error("Failed to build beginCreateSubscription request", e); GlobalMessages.addErrorMessage(model, "checkout.multi.paymentMethod.addPaymentDetails.generalError"); return doAddPaymentMethod(model); } if (paymentSubscriptionResultData.getErrors() != null && !paymentSubscriptionResultData.getErrors().isEmpty()) { GlobalMessages.addErrorMessage(model, "checkout.error.paymentethod.formentry.invalid"); // Add in specific errors for invalid fields for (final PaymentErrorField paymentErrorField : paymentSubscriptionResultData.getErrors() .values()) { if (paymentErrorField.isMissing()) { bindingResult.rejectValue(paymentErrorField.getName(), "checkout.error.paymentethod.formentry.sop.missing." + paymentErrorField.getName(), "Please enter a value for this field"); } if (paymentErrorField.isInvalid()) { bindingResult.rejectValue(paymentErrorField.getName(), "checkout.error.paymentethod.formentry.sop.invalid." + paymentErrorField.getName(), "This value is invalid for this field"); } } } else if (paymentSubscriptionResultData.getDecision() != null && paymentSubscriptionResultData.getDecision().equalsIgnoreCase("error")) { LOG.error( "Failed to create subscription. Error occurred while contacting external payment services."); GlobalMessages.addErrorMessage(model, "checkout.multi.paymentMethod.addPaymentDetails.generalError"); } return ControllerConstants.Views.Pages.MultiStepCheckout.SilentOrderPostPage; } else { // SOP ERROR! LOG.error("Failed to create subscription. Please check the log files for more information"); return REDIRECT_URL_ERROR + "/?decision=" + paymentSubscriptionResultData.getDecision() + "&reasonCode=" + paymentSubscriptionResultData.getResultCode(); } return REDIRECT_URL_SUMMARY; }
From source file:de.hybris.platform.storefront.controllers.pages.checkout.MultiStepCheckoutController.java
@RequestMapping(value = "/sop-response", method = RequestMethod.POST) @RequireHardLogIn//w w w. ja va 2 s. c om public String doHandleSopResponse(final HttpServletRequest request, @Valid final SopPaymentDetailsForm sopPaymentDetailsForm, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException { final Map<String, String> resultMap = getRequestParameterMap(request); final boolean savePaymentInfo = sopPaymentDetailsForm.isSavePaymentInfo() || getCheckoutCustomerStrategy().isAnonymousCheckout(); final PaymentSubscriptionResultData paymentSubscriptionResultData = this.getPaymentFacade() .completeSopCreateSubscription(resultMap, savePaymentInfo); if (paymentSubscriptionResultData.isSuccess() && paymentSubscriptionResultData.getStoredCard() != null && StringUtils.isNotBlank(paymentSubscriptionResultData.getStoredCard().getSubscriptionId())) { final CCPaymentInfoData newPaymentSubscription = paymentSubscriptionResultData.getStoredCard(); if (getUserFacade().getCCPaymentInfos(true).size() <= 1) { getUserFacade().setDefaultPaymentInfo(newPaymentSubscription); } getCheckoutFacade().setPaymentDetails(newPaymentSubscription.getId()); } else if ((paymentSubscriptionResultData.getDecision() != null && paymentSubscriptionResultData.getDecision().equalsIgnoreCase("error")) || (paymentSubscriptionResultData.getErrors() != null && !paymentSubscriptionResultData.getErrors().isEmpty())) { // Have SOP errors that we can display if (!hasValidCart()) { LOG.info("Missing, empty or unsupported cart"); return REDIRECT_URL_CART; } setupAddPaymentPage(model); // Build up the SOP form data and render page containing form try { setupSilentOrderPostPage(sopPaymentDetailsForm, model); } catch (final Exception e) { LOG.error("Failed to build beginCreateSubscription request", e); GlobalMessages.addErrorMessage(model, "checkout.multi.paymentMethod.addPaymentDetails.generalError"); return doAddPaymentMethod(model, redirectAttributes); } if (paymentSubscriptionResultData.getErrors() != null && !paymentSubscriptionResultData.getErrors().isEmpty()) { GlobalMessages.addErrorMessage(model, "checkout.error.paymentethod.formentry.invalid"); // Add in specific errors for invalid fields for (final PaymentErrorField paymentErrorField : paymentSubscriptionResultData.getErrors() .values()) { if (paymentErrorField.isMissing()) { bindingResult.rejectValue(paymentErrorField.getName(), "checkout.error.paymentethod.formentry.sop.missing." + paymentErrorField.getName(), "Please enter a value for this field"); } if (paymentErrorField.isInvalid()) { bindingResult.rejectValue(paymentErrorField.getName(), "checkout.error.paymentethod.formentry.sop.invalid." + paymentErrorField.getName(), "This value is invalid for this field"); } } } else if (paymentSubscriptionResultData.getDecision() != null && paymentSubscriptionResultData.getDecision().equalsIgnoreCase("error")) { LOG.error( "Failed to create subscription. Error occurred while contacting external payment services."); GlobalMessages.addErrorMessage(model, "checkout.multi.paymentMethod.addPaymentDetails.generalError"); } return ControllerConstants.Views.Pages.MultiStepCheckout.SilentOrderPostPage; } else { // SOP ERROR! LOG.error("Failed to create subscription. Please check the log files for more information"); return REDIRECT_URL_ERROR + "/?decision=" + paymentSubscriptionResultData.getDecision() + "&reasonCode=" + paymentSubscriptionResultData.getResultCode(); } return REDIRECT_URL_SUMMARY; }
From source file:eu.europa.ec.eci.oct.admin.controller.SettingsController.java
@Override protected String _doPost(Model model, SettingsBean bean, BindingResult result, SessionStatus status, HttpServletRequest request, HttpServletResponse response) throws OCTException { if (request.getParameter("saveSettings") != null) { ConfigurationParameter param;//from w w w . j av a2s. c om // custom logo settings if (bean.isDeleteLogo()) { param = configurationService.getConfigurationParameter(Parameter.LOGO_PATH); // delete file from disk final String storagePath = systemManager.getSystemPreferences().getFileStoragePath(); final File destFolder = new File(storagePath, "/custom"); final File dest = new File(destFolder, param.getValue()); dest.delete(); // update db param.setValue(Parameter.LOGO_PATH.getDefaultValue()); configurationService.updateParameter(param); } else { final CommonsMultipartFile file = bean.getLogoFile(); if (file != null && !"".equals(file.getOriginalFilename())) { if (logger.isDebugEnabled()) { logger.debug( "Uploaded new logo file: " + file.getFileItem().getName() + " / " + file.getSize()); } // validate uploaded logo file final Map<MultipartFileValidator.RejectReason, String> rejectDetailsMap = new HashMap<MultipartFileValidator.RejectReason, String>(); rejectDetailsMap.put(RejectReason.EMPTY_CONTENT, "oct.settings.error.logo.missing"); rejectDetailsMap.put(RejectReason.EMPTY_NAME, "oct.settings.error.logo.missing"); rejectDetailsMap.put(RejectReason.BAD_EXTENSION, "oct.settings.error.logo.badExtension"); rejectDetailsMap.put(RejectReason.MAX_SIZE_EXCEEDED, "oct.settings.error.logo.toobig"); final Validator validator = new MultipartFileValidator(getCurrentMessageBundle(request), "oct.settings.error.logo.upload", rejectDetailsMap, uploadExtensionWhitelist, 150000); validator.validate(file, result); if (result.hasErrors()) { return doGet(model, request, response); } // validation passed, save file to needed location and // update the db final String storagePath = systemManager.getSystemPreferences().getFileStoragePath(); final File destFolder = new File(storagePath, "/custom"); if (!destFolder.exists()) { boolean dirCreated = destFolder.mkdirs(); if (logger.isDebugEnabled()) { logger.debug( "Storage directory \"" + destFolder.getPath() + "\" created? => " + dirCreated); } } final String extension = file.getOriginalFilename() .substring(file.getOriginalFilename().lastIndexOf('.')); final String fileName = new StringBuilder().append("customlogo") .append(System.currentTimeMillis()).append(extension).toString(); final File dest = new File(destFolder, fileName); try { file.transferTo(dest); if (logger.isDebugEnabled()) { logger.debug("Uploaded logo file successfully transfered to the local file " + dest.getAbsolutePath()); } } catch (IllegalStateException e) { logger.error("illegal state error while uploading logo", e); result.reject("oct.settings.error.logo.upload", "Error uploading logo"); return doGet(model, request, response); } catch (IOException e) { logger.error("input/output error while uploading logo", e); result.reject("oct.settings.error.logo.upload", e.getMessage()); return doGet(model, request, response); } param = new ConfigurationParameter(); param.setParam(Parameter.LOGO_PATH.getKey()); param.setValue(fileName); configurationService.updateParameter(param); } } // callback url final String callbackUrl = bean.getCallbackUrl(); if (callbackUrl != null && !"".equals(callbackUrl)) { // validate url UrlValidator validator = UrlValidator.getInstance(); if (!validator.isValid(callbackUrl)) { result.rejectValue("callbackUrl", "oct.settings.error.callback.invalidurl", "An invalid URL has been specified."); return doGet(model, request, response); } } param = new ConfigurationParameter(); param.setParam(Parameter.CALLBACK_URL.getKey()); param.setValue(callbackUrl); configurationService.updateParameter(param); // optional validation param = new ConfigurationParameter(); param.setParam(Parameter.OPTIONAL_VALIDATION.getKey()); param.setValue(new Boolean(bean.getOptionalValidation()).toString()); configurationService.updateParameter(param); // distribution map param = new ConfigurationParameter(); param.setParam(Parameter.SHOW_DISTRIBUTION_MAP.getKey()); param.setValue(new Boolean(bean.getDisplayMap()).toString()); configurationService.updateParameter(param); } return "redirect:settings.do"; }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractRegistrationController.java
/** * This method is used for Register.//from w ww. j a va2 s. c om * * @param registration * @param result * @param captchaChallenge * @param captchaResponse * @param map * @param channelParam * @param sessionStatus * @param request * @return String */ @RequestMapping(value = "/register", method = RequestMethod.POST) public String register(@Valid @ModelAttribute("registration") final UserRegistration registration, final BindingResult result, @RequestParam(value = "recaptcha_challenge_field", required = false) String captchaChallenge, @RequestParam(value = "recaptcha_response_field", required = false) String captchaResponse, final ModelMap map, @ModelAttribute("channelParam") final String channelParam, SessionStatus sessionStatus, HttpServletRequest request) { logger.debug("###Entering in register( method @POST"); map.addAttribute("page", Page.HOME); map.addAttribute("registration", registration); addFraudProfilingHostToSession(map); IPtoCountry iPtoCountry = super.getGeoIpToCountry(request); List<Country> filteredCountryList = getFilteredCountryList(registration.getCountryList()); map.addAttribute("filteredCountryList", filteredCountryList); if (registration.getUser().getAddress().getCountry().length() > 0) { map.addAttribute("ipToCountryCode", registration.getUser().getAddress().getCountry()); } else { map.addAttribute("ipToCountryCode", iPtoCountry.getCountryCode()); } map.addAttribute(Page.HOME.getLevel1().name(), "on"); map.addAttribute("allowSecondaryCheckBox", registration.getTenant().getAccountType().isEnableSecondaryAddress()); if (!registration.getPhoneVerificationEnabled() && !Boolean.valueOf(config.getValue(Names.com_citrix_cpbm_use_intranet_only))) { try { verifyCaptcha(captchaChallenge, captchaResponse, getRemoteUserIp(request), captchaService); } catch (CaptchaFailureException ex) { map.addAttribute("registrationError", "captcha.error"); map.addAttribute("recaptchaPublicKey", config.getRecaptchaPublicKey()); map.addAttribute("showCaptcha", true); result.reject("errors.registration.captcha", null, null); map.addAttribute("allowSecondaryCheckBox", registration.getTenant().getAccountType().isEnableSecondaryAddress()); return "register.moreuserinfo"; } } registration.getUser().setPhone(registration.getUser().getPhone().replaceAll(PHONE_NUMBER_REGEX, "")); TelephoneVerificationService telephoneVerificationService = (TelephoneVerificationService) connectorManagementService .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION); if (telephoneVerificationService != null && telephoneVerificationService.isEnabled()) { String generatedPhoneVerificationPin = request.getSession().getAttribute("phoneVerificationPin") .toString(); String actualPhoneNumber = request.getSession().getAttribute("phoneNumber").toString(); if (!registration.getUserEnteredPhoneVerificationPin().equals(generatedPhoneVerificationPin) || !areDigitsInPhoneNosEqual(registration.getUser().getPhone(), actualPhoneNumber)) { map.addAttribute("registrationError", "phoneVerfication.error"); result.reject("errors.registration.user.phone", null, null); return "register.phoneverification"; } } if (result.hasErrors()) { displayErrors(result); parseResult(result, map); return "register.userinfo"; } // Device intelligence and fraud detection ReviewStatus fraudStatus = null; DeviceFraudDetectionAudit log = null; DeviceFraudDetectionService deviceFraudDetectionService = (DeviceFraudDetectionService) connectorManagementService .getOssServiceInstancebycategory(ConnectorType.DEVICE_FRAUD_CONTROL); if (deviceFraudDetectionService != null && deviceFraudDetectionService.isEnabled()) { fraudStatus = assessAccountCreationRisk(registration, request); if (fraudStatus == ReviewStatus.FAIL) { return "register.fail"; } log = ((DeviceFraudDetectionService) connectorManagementService .getOssServiceInstancebycategory(ConnectorType.DEVICE_FRAUD_CONTROL)) .getLastLog(request.getSession().getId(), registration.getUser().getUsername()); String message = "device.fraud"; Tenant tenant = tenantService.getSystemTenant(); String messageArguments = registration.getUser().getUsername(); Event event = null; switch (fraudStatus) { case REJECT: context.publishEvent(new PortalEvent("Device Fraud Detection Event", actorService.getActor(), new DeviceFraudDetectionEvent(log, registration.getUser().getUsername(), registration.getUser().getEmail(), registration.getUser().getPhone(), registration.getUser().getFirstName(), registration.getUser().getLastName()))); event = new Event(new Date(), message, messageArguments, tenant, Source.PORTAL, Scope.ACCOUNT, Category.ACCOUNT, Severity.CRITICAL, true); eventService.createEvent(event, false); return "register.fail"; case REVIEW: // account to be manual activated registration.getTenant().setIsManualActivation(true); context.publishEvent(new PortalEvent("Device Fraud Detection Event", actorService.getActor(), new DeviceFraudDetectionEvent(log, registration.getUser().getUsername(), registration.getUser().getEmail(), registration.getUser().getPhone(), registration.getUser().getFirstName(), registration.getUser().getLastName()))); event = new Event(new Date(), message, messageArguments, tenant, Source.PORTAL, Scope.ACCOUNT, Category.ACCOUNT, Severity.ALERT, true); eventService.createEvent(event, false); // Model should know fraud has been detected map.put("deviceFraudDetected", true); default: break; } } // This checks whether the trial code is valid or not map.addAttribute("supportEmail", config.getValue(Names.com_citrix_cpbm_portal_addressbook_helpDeskEmail)); map.addAttribute("supportPhone", config.getValue(Names.com_citrix_cpbm_portal_settings_helpdesk_phone)); // post processing for trial code if (!StringUtils.isEmpty(registration.getTrialCode())) { String promoCode = registration.getTrialCode(); String channelCode = channelService.getChannel(channelParam).getCode(); if (!promotionService.isValidPromotion(promoCode, channelCode)) { logger.debug("Invalid promo code " + promoCode + " for channel code " + channelCode); return "register.fail"; } // preempt trial account type creation if NOT supported [TA10428] CampaignPromotion cp = promotionService.locatePromotionByToken(promoCode); AccountType requestedAccountType = registrationService .getAccountTypeById(registration.getAccountTypeId()); if (requestedAccountType.equals(registrationService.getTrialAccountType()) && !cp.isTrial()) { logger.debug("Invalid promo code " + promoCode + " for account type " + requestedAccountType); return "register.fail"; } } registration.getTenant().setAddress(registration.getUser().getAddress()); if (!registration.isAllowSecondary()) { registration.getTenant().setSecondaryAddress(null); } else { registration.getTenant().setSecondaryAddress(registration.getSecondaryAddress()); } registration.getTenant().setSyncBillingAddress(true); // to store error messages List<String> errorMsgList = new ArrayList<String>(); try { final com.citrix.cpbm.access.User owner = registration.getUser(); if (registration.getCountryCode() == null || registration.getCountryCode().equals("")) { Country country = countryService .locateCountryByCode(registration.getUser().getAddress().getCountry()); registration.setCountryName(country.getName()); registration.setCountryCode(country.getIsdCode()); } String phoneNo = registration.getCountryCode().replaceAll(PHONE_NUMBER_REGEX, "") + COUNTRY_CODE_TO_PHONE_NUMBER_SEPERATOR + owner.getPhone().replaceAll(PHONE_NUMBER_REGEX, ""); // Set the phone number owner.setPhone(phoneNo); owner.setLocale(registration.getUser().getLocale()); registration.getTenant().setRemoteAddress(getRemoteUserIp(request)); // set currency for (CurrencyValue cv : registration.getCurrencyValueList()) { if (cv.getCurrencyCode().equals(registration.getCurrency())) { registration.getTenant().setCurrency(cv); break; } } privilegeService.runAsPortal(new PrivilegedAction<Void>() { @Override public Void run() { AccountType requestedAccountType = registrationService .getAccountTypeById(registration.getAccountTypeId()); if (requestedAccountType.equals(registrationService.getTrialAccountType())) { TrialAccount account = null; try { account = registrationService.registerTrialAccount(registration.getTrialCode(), registration.getTenant(), owner, channelParam); } catch (TrialCodeInvalidException e) { logger.debug("Invalid Trial Code", e); } catch (ConnectorManagementServiceException e) { logger.debug("Cannot find service instance", e); } map.addAttribute("trial", account); return null; } else { try { registrationService.registerTenant(registration.getTenant(), owner, channelParam, registration.getTrialCode(), result); } catch (ConnectorManagementServiceException e) { logger.debug("Cannot find service instance", e); } } if (!result.hasErrors()) { Tenant t = tenantService.get(registration.getTenant().getUuid()); t.setAccountType(registrationService.getAccountTypeById(registration.getAccountTypeId())); t.getTenantExtraInformation() .setPaymentMode(requestedAccountType.getSupportedPaymentModes().get(0)); tenantService.save(t); registration.setTenant((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(t)); } return null; } }); if (deviceFraudDetectionService != null && deviceFraudDetectionService.isEnabled()) { log.setUserId(registration.getTenant().getOwner().getId()); } map.addAttribute("tenant", registration.getTenant()); String homeUrl = config.getValue(Names.com_citrix_cpbm_portal_marketing_home_url); String cloudmktgUrl = config.getValue(Names.com_citrix_cpbm_portal_marketing_marketing_url); if (homeUrl != null) { map.addAttribute("homeUrl", homeUrl); } if (cloudmktgUrl != null) { map.addAttribute("cloudmktgUrl", cloudmktgUrl); } } catch (DataAccessException ex) { logger.error(ex); result.reject("errors.registration", new Object[] { ex.getMessage() }, null); errorMsgList.add("You must accept the terms and conditions to use this service"); } catch (TrialCodeInvalidException ex) { result.rejectValue("trialCode", "errors.registration.invalid_trial_code", null); map.addAttribute("trialCode", "errors.registration.invalid_trial_code"); logger.debug("registrationError " + ex.getMessage()); } catch (TrialMaxAccountReachedException ex) { result.rejectValue("trialCode", "errors.registration.max_trial_reached", null); map.addAttribute("trialCode", "errors.registration.max_trial_reached"); logger.debug("registrationError " + ex.getMessage()); } catch (Exception ex) { logger.error("registrationError ", ex); return "redirect:/portal/errors/error"; } if (result.hasErrors()) { displayErrors(result); parseResult(result, map); registration.reset(); registration.setCurrency(config.getValue(Names.com_citrix_cpbm_portal_settings_default_currency)); if (errorMsgList.size() > 0) { map.addAttribute("errorMsgList", errorMsgList); map.addAttribute("errormsg", true); } logger.debug("###Exiting register(registration,result,captchaChallenge,,captchaResponse," + "map,sessionStatus,request) method @POST"); map.addAttribute("allowSecondaryCheckBox", registration.getTenant().getAccountType().isEnableSecondaryAddress()); if (!Boolean.valueOf(config.getValue(Names.com_citrix_cpbm_use_intranet_only))) { map.addAttribute("recaptchaPublicKey", config.getRecaptchaPublicKey()); map.addAttribute("showCaptcha", true); } return "register.moreuserinfo"; } else { sessionStatus.setComplete(); // clean up parameters in session. logger.debug("###Exiting register(registration,result,captchaChallenge,,captchaResponse," + "map,sessionStatus,request) method @POST"); map.addAttribute("user", registration.getUser()); return "register.registration_success"; } }
From source file:com.pedra.storefront.controllers.pages.checkout.MultiStepCheckoutController.java
@RequestMapping(value = "/sop-response", method = RequestMethod.POST) @RequireHardLogIn// w ww.java2 s . co m public String doHandleSopResponse(final HttpServletRequest request, @Valid final SopPaymentDetailsForm sopPaymentDetailsForm, final BindingResult bindingResult, final Model model) throws CMSItemNotFoundException { final Map<String, String> resultMap = getRequestParameterMap(request); final boolean savePaymentInfo = "on".equals(resultMap.get("_savePaymentInfo")) || getCheckoutCustomerStrategy().isAnonymousCheckout(); final PaymentSubscriptionResultData paymentSubscriptionResultData = this.getPaymentFacade() .completeSopCreateSubscription(resultMap, savePaymentInfo); if (paymentSubscriptionResultData.isSuccess() && paymentSubscriptionResultData.getStoredCard() != null && StringUtils.isNotBlank(paymentSubscriptionResultData.getStoredCard().getSubscriptionId())) { final CCPaymentInfoData newPaymentSubscription = paymentSubscriptionResultData.getStoredCard(); if (getUserFacade().getCCPaymentInfos(true).size() <= 1) { getUserFacade().setDefaultPaymentInfo(newPaymentSubscription); } getCheckoutFacade().setPaymentDetails(newPaymentSubscription.getId()); } else if ((paymentSubscriptionResultData.getDecision() != null && paymentSubscriptionResultData.getDecision().equalsIgnoreCase("error")) || (paymentSubscriptionResultData.getErrors() != null && !paymentSubscriptionResultData.getErrors().isEmpty())) { // Have SOP errors that we can display if (!hasValidCart()) { LOG.info("Missing, empty or unsupported cart"); return REDIRECT_URL_CART; } setupAddPaymentPage(model); // Build up the SOP form data and render page containing form try { setupSilentOrderPostPage(sopPaymentDetailsForm, model); } catch (final Exception e) { LOG.error("Failed to build beginCreateSubscription request", e); GlobalMessages.addErrorMessage(model, "checkout.multi.paymentMethod.addPaymentDetails.generalError"); return doChoosePaymentMethod(model); } if (paymentSubscriptionResultData.getErrors() != null && !paymentSubscriptionResultData.getErrors().isEmpty()) { GlobalMessages.addErrorMessage(model, "checkout.error.paymentethod.formentry.invalid"); // Add in specific errors for invalid fields for (final PaymentErrorField paymentErrorField : paymentSubscriptionResultData.getErrors() .values()) { if (paymentErrorField.isMissing()) { bindingResult.rejectValue(paymentErrorField.getName(), "checkout.error.paymentethod.formentry.sop.missing." + paymentErrorField.getName(), "Please enter a value for this field"); } if (paymentErrorField.isInvalid()) { bindingResult.rejectValue(paymentErrorField.getName(), "checkout.error.paymentethod.formentry.sop.invalid." + paymentErrorField.getName(), "This value is invalid for this field"); } } } else if (paymentSubscriptionResultData.getDecision().equalsIgnoreCase("error")) { LOG.error( "Failed to create subscription. Error occurred while contacting external payment services."); GlobalMessages.addErrorMessage(model, "checkout.multi.paymentMethod.addPaymentDetails.generalError"); } model.addAttribute("regionsForCountries", getI18NFacade().getRegionsForAllCountries()); return ControllerConstants.Views.Pages.MultiStepCheckout.SilentOrderPostPage; } else { // SOP ERROR! LOG.error("Failed to create subscription. Please check the log files for more information"); return REDIRECT_URL_ERROR + "/?decision=" + paymentSubscriptionResultData.getDecision() + "&reasonCode=" + paymentSubscriptionResultData.getResultCode(); } return REDIRECT_URL_SUMMARY; }
From source file:de.hybris.platform.chinaaccelerator.storefront.checkout.controllers.pages.checkout.MultiStepCheckoutController.java
@RequestMapping(value = "/sop-response", method = RequestMethod.POST) @RequireHardLogIn//from w w w . j a v a 2 s . com public String doHandleSopResponse(final HttpServletRequest request, @Valid final SopPaymentDetailsForm sopPaymentDetailsForm, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException { final Map<String, String> resultMap = getRequestParameterMap(request); final boolean savePaymentInfo = sopPaymentDetailsForm.isSavePaymentInfo() || getCheckoutCustomerStrategy().isAnonymousCheckout(); final PaymentSubscriptionResultData paymentSubscriptionResultData = this.getPaymentFacade() .completeSopCreateSubscription(resultMap, savePaymentInfo); if (paymentSubscriptionResultData.isSuccess() && paymentSubscriptionResultData.getStoredCard() != null && StringUtils.isNotBlank(paymentSubscriptionResultData.getStoredCard().getSubscriptionId())) { final CCPaymentInfoData newPaymentSubscription = paymentSubscriptionResultData.getStoredCard(); if (getUserFacade().getCCPaymentInfos(true).size() <= 1) { getUserFacade().setDefaultPaymentInfo(newPaymentSubscription); } getCheckoutFacade().setPaymentDetails(newPaymentSubscription.getId()); } else if ((paymentSubscriptionResultData.getDecision() != null && paymentSubscriptionResultData.getDecision().equalsIgnoreCase("error")) || (paymentSubscriptionResultData.getErrors() != null && !paymentSubscriptionResultData.getErrors().isEmpty())) { // Have SOP errors that we can display if (!getCheckoutFlowFacade().hasValidCart()) { LOG.info("Missing, empty or unsupported cart"); return REDIRECT_URL_CART; } setupAddPaymentPage(model); // Build up the SOP form data and render page containing form try { setupSilentOrderPostPage(sopPaymentDetailsForm, model); } catch (final Exception e) { LOG.error("Failed to build beginCreateSubscription request", e); GlobalMessages.addErrorMessage(model, "checkout.multi.paymentMethod.addPaymentDetails.generalError"); return doAddPaymentMethod(model, redirectAttributes); } if (paymentSubscriptionResultData.getErrors() != null && !paymentSubscriptionResultData.getErrors().isEmpty()) { GlobalMessages.addErrorMessage(model, "checkout.error.paymentethod.formentry.invalid"); // Add in specific errors for invalid fields for (final PaymentErrorField paymentErrorField : paymentSubscriptionResultData.getErrors() .values()) { if (paymentErrorField.isMissing()) { bindingResult.rejectValue(paymentErrorField.getName(), "checkout.error.paymentethod.formentry.sop.missing." + paymentErrorField.getName(), "Please enter a value for this field"); } if (paymentErrorField.isInvalid()) { bindingResult.rejectValue(paymentErrorField.getName(), "checkout.error.paymentethod.formentry.sop.invalid." + paymentErrorField.getName(), "This value is invalid for this field"); } } } else if (paymentSubscriptionResultData.getDecision() != null && paymentSubscriptionResultData.getDecision().equalsIgnoreCase("error")) { LOG.error( "Failed to create subscription. Error occurred while contacting external payment services."); GlobalMessages.addErrorMessage(model, "checkout.multi.paymentMethod.addPaymentDetails.generalError"); } return ControllerConstants.Views.Pages.MultiStepCheckout.SilentOrderPostPage; } else { // SOP ERROR! LOG.error("Failed to create subscription. Please check the log files for more information"); return REDIRECT_URL_ERROR + "/?decision=" + paymentSubscriptionResultData.getDecision() + "&reasonCode=" + paymentSubscriptionResultData.getResultCode(); } return REDIRECT_URL_SUMMARY; }
From source file:org.egov.wtms.application.service.NewConnectionService.java
public void validatePropertyIDForDataEntry(final WaterConnectionDetails waterConnectionDetails, final BindingResult errors) { if (waterConnectionDetails.getConnection() != null && waterConnectionDetails.getConnection().getPropertyIdentifier() != null && !"".equals(waterConnectionDetails.getConnection().getPropertyIdentifier())) { String errorMessage = checkValidPropertyForDataEntry( waterConnectionDetails.getConnection().getPropertyIdentifier()); if (errorMessage != null && !"".equals(errorMessage)) errors.rejectValue(CONNECTION_PROPERTYID, errorMessage, errorMessage); if (waterConnectionDetails.getId() == null && waterConnectionDetails.getApplicationType().getCode().equalsIgnoreCase(NEWCONNECTION)) errorMessage = checkConnectionPresentForProperty( waterConnectionDetails.getConnection().getPropertyIdentifier()); if (errorMessage != null && !"".equals(errorMessage)) errors.rejectValue(CONNECTION_PROPERTYID, errorMessage, errorMessage); }// w w w. j a v a 2s.c o m }
From source file:org.egov.wtms.application.service.NewConnectionService.java
public void validatePropertyID(final WaterConnectionDetails waterConnectionDetails, final BindingResult errors) { if (waterConnectionDetails.getConnection() != null && isNotBlank(waterConnectionDetails.getConnection().getPropertyIdentifier())) { String errorMessage = checkValidPropertyAssessmentNumber( waterConnectionDetails.getConnection().getPropertyIdentifier()); if (isNotBlank(errorMessage)) errors.rejectValue(CONNECTION_PROPERTYID, errorMessage, errorMessage); else {/* ww w . j av a 2s .co m*/ errorMessage = checkConnectionPresentForProperty( waterConnectionDetails.getConnection().getPropertyIdentifier()); if (isNotBlank(errorMessage)) errors.rejectValue(CONNECTION_PROPERTYID, errorMessage, errorMessage); } } }
From source file:org.egov.wtms.application.service.WaterConnectionDetailsService.java
public void validateConnectionCategory(final WaterConnectionDetails waterConnectionDetails, final BindingResult errors, HttpServletRequest request) { if (Arrays.asList(NEWCONNECTION, ADDNLCONNECTION) .contains(waterConnectionDetails.getApplicationType().getCode())) { AssessmentDetails assessmentDetails = getPropertyDetails( waterConnectionDetails.getConnection().getPropertyIdentifier(), request); if (waterConnectionDetails.getCategory().getName().equalsIgnoreCase(CATEGORY_BPL)) { if (assessmentDetails.getPropertyDetails().getCurrentTax().compareTo(new BigDecimal(500)) > 0) { String errorMessage = wcmsMessageSource.getMessage("msg.propertytax.nonBPLcategory", new String[] {}, Locale.getDefault()); errors.rejectValue("category", errorMessage, errorMessage); }//from w ww . j av a 2 s . c om } else { if (assessmentDetails.getPropertyDetails().getCurrentTax().compareTo(new BigDecimal(500)) <= 0) { String errorMessage = wcmsMessageSource.getMessage("msg.propertytax.BPLcategory", new String[] {}, Locale.getDefault()); errors.rejectValue("category", errorMessage, errorMessage); } } } }
From source file:org.egov.wtms.web.controller.application.NewConnectionController.java
@PostMapping(value = "/newConnection-create") public String createNewConnection(@Valid @ModelAttribute WaterConnectionDetails waterConnectionDetails, BindingResult resultBinder, HttpServletRequest request, Model model, @RequestParam String workFlowAction, @RequestParam("files") MultipartFile... files) { User currentUser = securityUtils.getCurrentUser(); boolean loggedUserIsMeesevaUser = waterTaxUtils.isMeesevaUser(currentUser); boolean isCSCOperator = waterTaxUtils.isCSCoperator(currentUser); boolean citizenPortalUser = waterTaxUtils.isCitizenPortalUser(currentUser); model.addAttribute("citizenPortalUser", citizenPortalUser); boolean isAnonymousUser = waterTaxUtils.isAnonymousUser(currentUser); model.addAttribute("isAnonymousUser", isAnonymousUser); if (!isCSCOperator && !citizenPortalUser && !loggedUserIsMeesevaUser && !isAnonymousUser && !waterTaxUtils.isLoggedInUserJuniorOrSeniorAssistant(currentUser.getId())) { throw new ValidationException("err.creator.application"); }//from w ww . j a v a 2s .c om newConnectionService.validatePropertyID(waterConnectionDetails, resultBinder); if (ConnectionType.NON_METERED.equals(waterConnectionDetails.getConnectionType())) { waterConnectionDtlsService.validateWaterRateAndDonationHeader(waterConnectionDetails); } List<ApplicationDocuments> applicationDocs = new ArrayList<>(); int i = 0; String documentRequired = waterTaxUtils.documentRequiredForBPLCategory(); if (!waterConnectionDetails.getApplicationDocs().isEmpty()) for (ApplicationDocuments applicationDocument : waterConnectionDetails.getApplicationDocs()) { newConnectionService.validateDocuments(applicationDocs, applicationDocument, i, resultBinder, waterConnectionDetails.getCategory().getId(), documentRequired); i++; } if (waterConnectionDetails.getState() == null) { waterConnectionDetails.setStatus(waterTaxUtils.getStatusByCodeAndModuleType( WaterTaxConstants.APPLICATION_STATUS_CREATED, WaterTaxConstants.MODULETYPE)); } if (resultBinder.hasErrors()) { waterConnectionDetails.setApplicationDate(new Date()); boolean sewerageTaxenabled = moduleService.getModuleByName(SEWERAGE_TAX_MANAGEMENT).isEnabled(); model.addAttribute("sewerageTaxenabled", sewerageTaxenabled); //sewerage module integration if (sewerageTaxenabled) { waterConnectionDtlsService.prepareNewForm(model, waterConnectionDetails); } model.addAttribute(VALIDIFPTDUEEXISTS, waterTaxUtils.isNewConnectionAllowedIfPTDuePresent()); WorkflowContainer workflowContainer = new WorkflowContainer(); workflowContainer.setAdditionalRule(waterConnectionDetails.getApplicationType().getCode()); prepareWorkflow(model, waterConnectionDetails, workflowContainer); model.addAttribute(ADDITIONALRULE, waterConnectionDetails.getApplicationType().getCode()); model.addAttribute(CURRENTUSER, waterTaxUtils.getCurrentUserRole(currentUser)); model.addAttribute("approvalPosOnValidate", request.getParameter(APPROVALPOSITION)); model.addAttribute(TYPE_OF_CONNECTION, NEWCONNECTION); model.addAttribute(STATETYPE, waterConnectionDetails.getClass().getSimpleName()); model.addAttribute("documentName", waterTaxUtils.documentRequiredForBPLCategory()); model.addAttribute("isCSCOperator", waterTaxUtils.isCSCoperator(currentUser)); model.addAttribute("citizenPortalUser", waterTaxUtils.isCitizenPortalUser(currentUser)); model.addAttribute("isAnonymousUser", waterTaxUtils.isAnonymousUser(currentUser)); return NEWCONNECTION_FORM; } waterConnectionDetails.getApplicationDocs().clear(); waterConnectionDetails.setApplicationDocs(applicationDocs); processAndStoreApplicationDocuments(waterConnectionDetails); Long approvalPosition = 0l; String approvalComent = ""; boolean applicationByOthers = waterTaxUtils.getCurrentUserRole(currentUser); if (request.getParameter("approvalComent") != null) approvalComent = request.getParameter("approvalComent"); if (request.getParameter("workFlowAction") != null) workFlowAction = request.getParameter("workFlowAction"); if (request.getParameter(APPROVALPOSITION) != null && !request.getParameter(APPROVALPOSITION).isEmpty()) approvalPosition = Long.valueOf(request.getParameter(APPROVALPOSITION)); if (applicationByOthers || citizenPortalUser || isAnonymousUser) { Position userPosition = waterTaxUtils.getZonalLevelClerkForLoggedInUser( waterConnectionDetails.getConnection().getPropertyIdentifier()); if (userPosition != null) approvalPosition = userPosition.getId(); else { model.addAttribute(VALIDIFPTDUEEXISTS, waterTaxUtils.isNewConnectionAllowedIfPTDuePresent()); WorkflowContainer workflowContainer = new WorkflowContainer(); workflowContainer.setAdditionalRule(waterConnectionDetails.getApplicationType().getCode()); prepareWorkflow(model, waterConnectionDetails, workflowContainer); model.addAttribute(ADDITIONALRULE, waterConnectionDetails.getApplicationType().getCode()); model.addAttribute("approvalPosOnValidate", request.getParameter(APPROVALPOSITION)); model.addAttribute(CURRENTUSER, waterTaxUtils.getCurrentUserRole(securityUtils.getCurrentUser())); model.addAttribute(TYPE_OF_CONNECTION, NEWCONNECTION); model.addAttribute(STATETYPE, waterConnectionDetails.getClass().getSimpleName()); resultBinder.rejectValue(CONNECTION_PROPERTYID, "err.validate.connection.user.mapping", "err.validate.connection.user.mapping"); model.addAttribute("noJAORSAMessage", "No JA/SA exists to forward the application."); return NEWCONNECTION_FORM; } } if (isAnonymousUser) waterConnectionDetails.setSource(ONLINE); else if (isCSCOperator) waterConnectionDetails.setSource(CSC); else if (citizenPortalUser && (waterConnectionDetails.getSource() == null || isBlank(waterConnectionDetails.getSource().toString()))) waterConnectionDetails.setSource(waterTaxUtils.setSourceOfConnection(securityUtils.getCurrentUser())); else if (loggedUserIsMeesevaUser) { waterConnectionDetails.setSource(MEESEVA); if (waterConnectionDetails.getMeesevaApplicationNumber() != null) waterConnectionDetails.setApplicationNumber(waterConnectionDetails.getMeesevaApplicationNumber()); } else waterConnectionDetails.setSource(SYSTEM); boolean isSewerageChecked = request.getParameter("sewerageApplication") == null ? false : true; //sewerage integration SewerageApplicationDetails sewerageDetails = new SewerageApplicationDetails(); if (moduleService.getModuleByName(SEWERAGE_TAX_MANAGEMENT).isEnabled() && isSewerageChecked) { if (isCSCOperator) { sewerageDetails.setSource(CSC.toString()); } if (isAnonymousUser) { sewerageDetails.setSource(ONLINE.toString()); } sewerageIntegration(waterConnectionDetails, resultBinder, sewerageDetails); sewerageApplicationCreate(waterConnectionDetails, request, workFlowAction, files, sewerageDetails, approvalPosition, approvalComent); } waterConnectionDtlsService.createNewWaterConnection(waterConnectionDetails, approvalPosition, approvalComent, waterConnectionDetails.getApplicationType().getCode(), workFlowAction); if (LOG.isDebugEnabled()) LOG.debug("createNewWaterConnection is completed "); String sewerageAppnumber = sewerageDetails.getApplicationNumber() == null ? " " : sewerageDetails.getApplicationNumber(); if (loggedUserIsMeesevaUser) return "redirect:/application/generate-meesevareceipt?transactionServiceNumber=" + waterConnectionDetails.getApplicationNumber(); else return "redirect:/application/citizeenAcknowledgement?pathVars=" + waterConnectionDetails.getApplicationNumber() + "&sewerageAppNo=" + sewerageAppnumber; }