List of usage examples for org.springframework.validation FieldError FieldError
public FieldError(String objectName, String field, String defaultMessage)
From source file:com.virtusa.akura.reporting.controller.CustomStaffReportController.java
/** * Generate School Teacher List Report and School Section Head List Report request processing method. * * @param schoolStaffHeadList a model to bind values. * @param errors To bind errors.//from ww w . ja v a 2 s .c o m * @param response the servlet response. * @return The view name of the request handler. * @throws AkuraAppException throw exception if request processing fails. */ @RequestMapping(value = LIST_REPORTS, method = RequestMethod.POST) public String showTeacherListReport( @ModelAttribute(SCHOOL_TEACHER_AND_SECTION_HEAD_LIST) SchoolTeacherAndSectionHeadList schoolStaffHeadList, BindingResult errors, HttpServletResponse response) throws AkuraAppException { LOG.info(SCHOOL_TEACHER_LIST_LOG); JRBeanCollectionDataSource datasource; schoolTeacherListSectionHeadListValidator.validate(schoolStaffHeadList, errors); if (errors.hasErrors()) { return REPORTING_SCHOOL_TEACHER_LIST_AND_SECTION_HEAD_LIST; } Map<String, Object> parameterMap = new HashMap<String, Object>(); // if the list type is true then generate the Teacher List Report. if (schoolStaffHeadList.getListType() == AkuraConstant.PARAM_INDEX_ONE) { List<Staff> staffByCategoryList = null; if (schoolStaffHeadList.getCatogaryID() == -1) { staffByCategoryList = staffService.getAllAvailableStaffWithOutDeparture(); parameterMap.put(STAFF_CATEGORY_TYPE, ALL); } else { staffByCategoryList = staffService.getStaffListByCategory(schoolStaffHeadList.getCatogaryID()); parameterMap.put(STAFF_CATEGORY_TYPE, staffCommonService.getStaffCategory(schoolStaffHeadList.getCatogaryID()).getDescription()); } if (staffByCategoryList.isEmpty()) { errors.addError(new FieldError(SCHOOL_TEACHER_AND_SECTION_HEAD_LIST, LIST_TYPE, MEMBERS_ARE_NOT_ASSIGNED_ERROR_CATEGORY)); return REPORTING_SCHOOL_TEACHER_LIST_AND_SECTION_HEAD_LIST; } // Sort the staff List and Set to data source. datasource = new JRBeanCollectionDataSource(SortUtil.sortStaffList(staffByCategoryList)); parameterMap.put(TITLE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, STAFF_REPORT)); parameterMap.put(YEAR, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, YEAR_STRING)); parameterMap = populateParameterMap(parameterMap, datasource); ReportUtil.displayReportInPdfForm(response, datasource, parameterMap, STAFF_REPORTS); } else if (schoolStaffHeadList.getListType() == AkuraConstant.PARAM_INDEX_THREE) { List<ClassTeacher> classTeacherList = getClassTeacherListByGrade(schoolStaffHeadList.getGradeId()); if (classTeacherList.isEmpty()) { errors.addError(new FieldError(SCHOOL_TEACHER_AND_SECTION_HEAD_LIST, LIST_TYPE, TEACHERS_ARE_NOT_ASSIGNED_TO_THE_SELECTED_CLASS)); return REPORTING_SCHOOL_TEACHER_LIST_AND_SECTION_HEAD_LIST; } datasource = new JRBeanCollectionDataSource(SortUtil.sortClassTeacherList(classTeacherList)); parameterMap = populateParameterMap(parameterMap, datasource); parameterMap.put(CLASS_GRADE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, CLASS_GRADE_TITLE)); parameterMap.put(TITLE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, CLASS_TEACHERS)); parameterMap.put(GRADE_LOW, schoolStaffHeadList.getGradeDescription()); parameterMap.put(YEAR, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, YEAR_STRING)); parameterMap.put(CLASS, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, CLASS_TITLE)); ReportUtil.displayReportInPdfForm(response, datasource, parameterMap, CLASS_TEACHER_LIST); } else { List<SectionHead> sectionHeadList = getAllCurrrentSectionHeads( staffService.getCurrentSectionHeadList(new Date())); if (sectionHeadList.isEmpty()) { errors.addError(new FieldError(SCHOOL_TEACHER_AND_SECTION_HEAD_LIST, LIST_TYPE, SECTIONAL_HEADS_ARE_NOT_ASSIGNED)); return REPORTING_SCHOOL_TEACHER_LIST_AND_SECTION_HEAD_LIST; } datasource = new JRBeanCollectionDataSource(SortUtil.sortSectionHeadList(sectionHeadList)); parameterMap.put(TITLE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, SECTION_HEADS)); parameterMap.put(START_DATE2, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, START_DATE)); parameterMap.put(END_DATE2, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, END_DATE)); parameterMap.put(SECTION2, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, SECTION)); parameterMap = populateParameterMap(parameterMap, datasource); ReportUtil.displayReportInPdfForm(response, datasource, parameterMap, SECTION_HEADS_REPORT); } return null; }
From source file:com.devnexus.ting.web.controller.RegisterController.java
@RequestMapping(value = "/s/registerPageTwo", method = RequestMethod.POST) public String validateDetailsForm(HttpServletRequest request, Model model, @Valid RegistrationDetails registerForm, BindingResult result) { Event currentEvent = businessService.getCurrentEvent(); EventSignup eventSignup = businessService.getEventSignup(); PaymentMethod paymentMethod = PaymentMethod.PAYPAL; prepareHeader(currentEvent, model);// w w w. j a v a2 s .c om model.addAttribute("signupRegisterView", new SignupRegisterView(eventSignup)); model.addAttribute("registrationDetails", registerForm); registerForm.setFinalCost(getTotal(registerForm)); registerForm.setEvent(currentEvent); if (result.hasErrors()) { return "register2"; } for (int index = 0; index < registerForm.getOrderDetails().size(); index++) { TicketOrderDetail orderDetails = registerForm.getOrderDetails().get(index); TicketGroup ticketGroup = businessService.getTicketGroup(orderDetails.getTicketGroup()); if (!com.google.common.base.Strings.isNullOrEmpty(orderDetails.getCouponCode()) && ticketGroup.getCouponCodes() != null && ticketGroup.getCouponCodes().size() > 0) { if (!hasCode(ticketGroup.getCouponCodes(), orderDetails.getCouponCode())) { result.addError(new FieldError("registrationDetails", "orderDetails[" + index + "].couponCode", "Invalid Coupon Code.")); } } if (StringUtils.isEmpty(orderDetails.getFirstName())) { result.rejectValue("orderDetails[" + index + "].firstName", "firstName.isRequired", "First Name is required."); } if (StringUtils.isEmpty(orderDetails.getLastName())) { result.rejectValue("orderDetails[" + index + "].lastName", "lastName.isRequired", "Last Name is required."); } if (StringUtils.isEmpty(orderDetails.getEmailAddress())) { result.rejectValue("orderDetails[" + index + "].emailAddress", "emailAddress.isReq uired", "Email Address is required."); } if (StringUtils.isEmpty(orderDetails.getCity())) { result.rejectValue("orderDetails[" + index + "].city", "city.isRequired", "City is required."); } if (StringUtils.isEmpty(orderDetails.getState())) { result.rejectValue("orderDetails[" + index + "].state", "state.isRequired", "State is required."); } if (StringUtils.isEmpty(orderDetails.getCountry())) { result.rejectValue("orderDetails[" + index + "].country", "country.isRequired", "Country is required."); } if (StringUtils.isEmpty(orderDetails.getJobTitle())) { result.rejectValue("orderDetails[" + index + "].jobTitle", "jobTitle.isRequired", "Job Title is required."); } if (StringUtils.isEmpty(orderDetails.getCompany())) { result.rejectValue("orderDetails[" + index + "].company", "company.isRequired", "Company is required."); } } if (result.hasErrors()) { return "register2"; } for (TicketOrderDetail detail : registerForm.getOrderDetails()) { detail.setRegistration(registerForm); } switch (paymentMethod) { case INVOICE: registerForm.setPaymentState(RegistrationDetails.PaymentState.REQUIRES_INVOICE); registerForm.setFinalCost(getTotal(registerForm)); businessService.createPendingRegistrationForm(registerForm); return "index"; case PAYPAL: registerForm.setPaymentState(RegistrationDetails.PaymentState.PAYPAL_CREATED); registerForm.setFinalCost(getTotal(registerForm)); registerForm = businessService.createPendingRegistrationForm(registerForm); String baseUrl = String.format("%s://%s:%d/", request.getScheme(), request.getServerName(), request.getServerPort()); Payment createdPayment = runPayPal(registerForm, baseUrl); return "redirect:" + createdPayment.getLinks().stream().filter(link -> { return link.getRel().equals("approval_url"); }).findFirst().get().getHref(); default: throw new IllegalStateException("The system did not understand the payment type."); } }
From source file:org.duracloud.account.app.controller.UserController.java
@Transactional @RequestMapping(value = { "/change-password/{redemptionCode}" }, method = RequestMethod.POST) public String anonymousPasswordChange(@PathVariable String redemptionCode, @ModelAttribute(CHANGE_PASSWORD_FORM_KEY) @Valid AnonymousChangePasswordForm form, BindingResult result, Model model) throws Exception { UserInvitation invitation = checkRedemptionCode(redemptionCode, model); if (invitation == null) { return ANONYMOUS_CHANGE_PASSWORD_FAILURE_VIEW; }//from w w w .ja va 2 s . c om String username = invitation.getAdminUsername(); DuracloudUser user = this.userService.loadDuracloudUserByUsernameInternal(username); // check for errors if (!result.hasErrors()) { log.info("changing user password for {}", username); Long id = user.getId(); try { this.userService.changePasswordInternal(id, user.getPassword(), true, form.getPassword()); this.userService.redeemPasswordChangeRequest(user.getId(), redemptionCode); model.addAttribute("adminUrl", amaEndpoint.getUrl()); return "anonymous-change-password-success"; } catch (InvalidPasswordException e) { result.addError( new FieldError(CHANGE_PASSWORD_FORM_KEY, "oldPassword", "The old password is not correct")); } } return ANONYMOUS_CHANGE_PASSWORD_VIEW; }
From source file:com.devnexus.ting.web.controller.cfp.CallForPapersController.java
private CfpSpeakerImage processPicture(MultipartFile picture, BindingResult bindingResult) { CfpSpeakerImage cfpSpeakerImage = null; byte[] pictureData = null; try {/*from w w w. ja v a 2 s. c om*/ pictureData = picture.getBytes(); } catch (IOException e) { LOGGER.error("Error processing Image.", e); bindingResult .addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", "Error processing Image.")); return null; } if (pictureData != null && picture.getSize() > 0) { ByteArrayInputStream bais = new ByteArrayInputStream(pictureData); BufferedImage image; try { image = ImageIO.read(bais); } catch (IOException e) { LOGGER.error("Error processing Image.", e); bindingResult .addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", "Error processing Image.")); return null; } if (image == null) { //FIXME better way? final String fileSizeFormatted = FileUtils.byteCountToDisplaySize(picture.getSize()); LOGGER.warn(String.format("Cannot parse file '%s' (Content Type: %s; Size: %s) as image.", picture.getOriginalFilename(), picture.getContentType(), fileSizeFormatted)); bindingResult.addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", String.format( "Did you upload a valid image? We cannot parse file '%s' (Size: %s) as image file.", picture.getOriginalFilename(), fileSizeFormatted))); return null; } int imageHeight = image.getHeight(); int imageWidth = image.getWidth(); if (imageHeight < 360 && imageWidth < 360) { bindingResult.addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", String.format( "Your image '%s' (%sx%spx) is too small. Please provide an image of at least 360x360px.", picture.getOriginalFilename(), imageWidth, imageHeight))); } cfpSpeakerImage = new CfpSpeakerImage(); cfpSpeakerImage.setFileData(pictureData); cfpSpeakerImage.setFileModified(new Date()); cfpSpeakerImage.setFileSize(picture.getSize()); cfpSpeakerImage.setName(picture.getOriginalFilename()); cfpSpeakerImage.setType(picture.getContentType()); return cfpSpeakerImage; } return null; }
From source file:org.duracloud.account.app.controller.UserController.java
@Transactional @RequestMapping(value = { FORGOT_PASSWORD_MAPPING }, method = RequestMethod.POST) public String forgotPassword( @ModelAttribute(FORGOT_PASSWORD_FORM_KEY) @Valid ForgotPasswordForm forgotPasswordForm, BindingResult result, Model model, HttpServletRequest request) throws Exception { model.addAttribute(FORGOT_PASSWORD_FORM_KEY, forgotPasswordForm); if (!result.hasErrors()) { try {//from ww w .j a va 2 s. c om String username = forgotPasswordForm.getUsername(); if (StringUtils.isEmpty(forgotPasswordForm.getSecurityQuestion())) { DuracloudUser user = this.userService.loadDuracloudUserByUsernameInternal(username); forgotPasswordForm.setSecurityQuestion(user.getSecurityQuestion()); } if (StringUtils.isEmpty(forgotPasswordForm.getSecurityAnswer())) { return FORGOT_PASSWORD_VIEW; } this.userService.forgotPassword(username, forgotPasswordForm.getSecurityQuestion(), forgotPasswordForm.getSecurityAnswer()); } catch (DBNotFoundException e) { result.addError( new FieldError(FORGOT_PASSWORD_FORM_KEY, "username", "The username does not exist")); return FORGOT_PASSWORD_VIEW; } catch (InvalidPasswordException e) { result.addError(new FieldError(FORGOT_PASSWORD_FORM_KEY, "securityQuestion", "The security answer is not correct")); return FORGOT_PASSWORD_VIEW; } catch (UnsentEmailException ue) { result.addError(new ObjectError(FORGOT_PASSWORD_FORM_KEY, "Unable to send email to the address associated with the username")); return FORGOT_PASSWORD_VIEW; } return FORGOT_PASSWORD_SUCCESS_VIEW; } return FORGOT_PASSWORD_VIEW; }
From source file:com.devnexus.ting.web.controller.cfp.CallForPapersController.java
@RequestMapping(value = "/speaker/{cfpSubmissionSpeakerId}", method = RequestMethod.POST) public String editCfpSpeaker(@PathVariable("cfpSubmissionSpeakerId") Long cfpSubmissionSpeakerId, @Valid @ModelAttribute("cfpSubmissionSpeaker") CfpSubmissionSpeakerForm cfpSubmissionSpeaker, BindingResult bindingResult, ModelMap model, RedirectAttributes redirectAttributes, HttpServletRequest request) {/*from w w w . j ava2 s.c om*/ if (request.getParameter("cancel") != null) { return "redirect:/s/cfp/index"; } final User user = (User) userService.loadUserByUsername(securityFacade.getUsername()); final Event event = businessService.getCurrentEvent(); if (request.getParameter("delete") != null) { final List<CfpSubmission> cfpSubmissions = businessService .getCfpSubmissionsForUserAndEvent(user.getId(), event.getId()); boolean canDelete = true; for (CfpSubmission cfpSubmission : cfpSubmissions) { for (CfpSubmissionSpeaker speaker : cfpSubmission.getCfpSubmissionSpeakers()) { if (speaker.getId().equals(cfpSubmissionSpeakerId)) { canDelete = false; break; } } } if (canDelete) { businessService.deleteCfpSubmissionSpeakerForUser(cfpSubmissionSpeakerId, event.getId(), user.getId()); } else { bindingResult.addError(new ObjectError("cfpSubmissionSpeaker", "Cannot delete speaker. The speaker is still associated with an abstract.")); prepareReferenceData(model); return "/cfp/edit-cfp-speaker"; } redirectAttributes.addFlashAttribute("successMessage", String .format("The speaker '%s' was deleted successfully.", cfpSubmissionSpeaker.getFirstLastName())); return "redirect:/s/cfp/index"; } if (!cfpSubmissionSpeaker.isAvailableEntireEvent()) { int index = 0; for (CfpAvailabilityForm availabilityForm : cfpSubmissionSpeaker.getAvailabilityDays()) { if (availabilityForm.getAvailabilitySelection() == null) { bindingResult.addError(new FieldError("cfpSubmissionSpeaker", "availabilityDays[" + index++ + "].availabilitySelection", "Please make a selection regarding your availability.")); } if (CfpSpeakerAvailability.PARTIAL_AVAILABILITY .equals(availabilityForm.getAvailabilitySelection())) { if (availabilityForm.getStartTime() == null) { bindingResult.addError(new FieldError("cfpSubmissionSpeaker", "availabilityDays[" + index + "].startTime", "Please provide a start time.")); } if (availabilityForm.getEndTime() == null) { bindingResult.addError(new FieldError("cfpSubmissionSpeaker", "availabilityDays[" + index + "].endTime", "Please provide an end time.")); } if (availabilityForm.getStartTime() != null && availabilityForm.getEndTime() != null && !availabilityForm.getStartTime().isBefore(availabilityForm.getEndTime())) { bindingResult.addError( new FieldError("cfpSubmissionSpeaker", "availabilityDays[" + index + "].endTime", "Please ensure that the end time is after the start time.")); } } index++; } } if (bindingResult.hasErrors()) { prepareReferenceData(model); return "/cfp/edit-cfp-speaker"; } final MultipartFile picture = cfpSubmissionSpeaker.getPictureFile(); final CfpSpeakerImage cfpSpeakerImage = processPicture(picture, bindingResult); if (bindingResult.hasErrors()) { prepareReferenceData(model); return "/cfp/edit-cfp-speaker"; } //FIXME final CfpSubmissionSpeaker cfpSubmissionSpeakerFromDb = businessService .getCfpSubmissionSpeakerWithPicture(cfpSubmissionSpeakerId); cfpSubmissionSpeakerFromDb.setEmail(cfpSubmissionSpeaker.getEmail()); cfpSubmissionSpeakerFromDb.setCompany(cfpSubmissionSpeaker.getCompany()); cfpSubmissionSpeakerFromDb.setBio(cfpSubmissionSpeaker.getBio()); cfpSubmissionSpeakerFromDb.setFirstName(cfpSubmissionSpeaker.getFirstName()); cfpSubmissionSpeakerFromDb.setGithubId(cfpSubmissionSpeaker.getGithubId()); cfpSubmissionSpeakerFromDb.setGooglePlusId(cfpSubmissionSpeaker.getGooglePlusId()); cfpSubmissionSpeakerFromDb.setLanyrdId(cfpSubmissionSpeaker.getLanyrdId()); cfpSubmissionSpeakerFromDb.setLastName(cfpSubmissionSpeaker.getLastName()); cfpSubmissionSpeakerFromDb.setPhone(cfpSubmissionSpeaker.getPhone()); cfpSubmissionSpeakerFromDb.setLinkedInId(cfpSubmissionSpeaker.getLinkedInId()); cfpSubmissionSpeakerFromDb.setTwitterId(cfpSubmissionSpeaker.getTwitterId()); cfpSubmissionSpeakerFromDb.setLocation(cfpSubmissionSpeaker.getLocation()); cfpSubmissionSpeakerFromDb.setMustReimburseTravelCost(cfpSubmissionSpeaker.isMustReimburseTravelCost()); cfpSubmissionSpeakerFromDb.setTshirtSize(cfpSubmissionSpeaker.getTshirtSize()); final List<CfpSubmissionSpeakerConferenceDay> cfpSubmissionSpeakerConferenceDays = new ArrayList<>(); if (cfpSubmissionSpeaker.isAvailableEntireEvent()) { cfpSubmissionSpeakerFromDb.setAvailableEntireEvent(cfpSubmissionSpeaker.isAvailableEntireEvent()); } else { cfpSubmissionSpeakerFromDb.setAvailableEntireEvent(cfpSubmissionSpeaker.isAvailableEntireEvent()); final SortedSet<ConferenceDay> conferenceDays = event.getConferenceDays(); for (CfpAvailabilityForm availabilityForm : cfpSubmissionSpeaker.getAvailabilityDays()) { ConferenceDay conferenceDayToUse = null; for (ConferenceDay conferenceDay : conferenceDays) { if (conferenceDay.getId().equals(availabilityForm.getConferenceDay().getId())) { conferenceDayToUse = conferenceDay; } } if (conferenceDayToUse == null) { throw new IllegalStateException( "Did not find conference day for id " + availabilityForm.getConferenceDay().getId()); } System.out.println(conferenceDayToUse.getId()); final CfpSubmissionSpeakerConferenceDay conferenceDay = new CfpSubmissionSpeakerConferenceDay(); conferenceDay.setConferenceDay(conferenceDayToUse); conferenceDay.setCfpSubmissionSpeaker(cfpSubmissionSpeakerFromDb); if (CfpSpeakerAvailability.ANY_TIME.equals(availabilityForm.getAvailabilitySelection())) { conferenceDay.setCfpSpeakerAvailability(CfpSpeakerAvailability.ANY_TIME); } else if (CfpSpeakerAvailability.NO_AVAILABILITY .equals(availabilityForm.getAvailabilitySelection())) { conferenceDay.setCfpSpeakerAvailability(CfpSpeakerAvailability.NO_AVAILABILITY); } else if (CfpSpeakerAvailability.PARTIAL_AVAILABILITY .equals(availabilityForm.getAvailabilitySelection())) { conferenceDay.setCfpSpeakerAvailability(CfpSpeakerAvailability.PARTIAL_AVAILABILITY); conferenceDay.setStartTime(availabilityForm.getStartTime()); conferenceDay.setEndTime(availabilityForm.getEndTime()); } cfpSubmissionSpeakerConferenceDays.add(conferenceDay); } } if (cfpSpeakerImage != null) { cfpSubmissionSpeakerFromDb.setCfpSpeakerImage(cfpSpeakerImage); } businessService.saveCfpSubmissionSpeaker(cfpSubmissionSpeakerFromDb, cfpSubmissionSpeakerConferenceDays); redirectAttributes.addFlashAttribute("successMessage", String.format( "The speaker '%s' was edited successfully.", cfpSubmissionSpeakerFromDb.getFirstLastName())); return "redirect:/s/cfp/index"; }
From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.checkout.SingleStepCheckoutController.java
@RequestMapping(value = "/placeOrder") @RequireHardLogIn//w w w . j a va2 s. c om public String placeOrder(final Model model, @Valid final PlaceOrderForm placeOrderForm, final BindingResult bindingResult) throws CMSItemNotFoundException, InvalidCartException, ParseException { // validate the cart final CartData cartData = getCheckoutFlowFacade().getCheckoutCart(); final boolean isAccountPaymentType = CheckoutPaymentType.ACCOUNT.getCode() .equals(cartData.getPaymentType().getCode()); final String securityCode = placeOrderForm.getSecurityCode(); final boolean termsChecked = placeOrderForm.isTermsCheck(); if (!termsChecked) { GlobalMessages.addErrorMessage(model, "checkout.error.terms.not.accepted"); } if (validateOrderform(placeOrderForm, model, cartData)) { placeOrderForm.setTermsCheck(false); model.addAttribute(placeOrderForm); return checkoutSummary(model); } if (!isAccountPaymentType && !getCheckoutFlowFacade().authorizePayment(securityCode)) { return checkoutSummary(model); } // validate quote negotiation if (placeOrderForm.isNegotiateQuote()) { if (StringUtils.isBlank(placeOrderForm.getQuoteRequestDescription())) { GlobalMessages.addErrorMessage(model, "checkout.error.noQuoteDescription"); return checkoutSummary(model); } else { getCheckoutFlowFacade().setQuoteRequestDescription( XSSFilterUtil.filter(placeOrderForm.getQuoteRequestDescription())); } } if (!termsChecked) { return checkoutSummary(model); } // validate replenishment if (placeOrderForm.isReplenishmentOrder()) { if (placeOrderForm.getReplenishmentStartDate() == null) { bindingResult.addError( new FieldError(placeOrderForm.getClass().getSimpleName(), "replenishmentStartDate", "")); GlobalMessages.addErrorMessage(model, "checkout.error.replenishment.noStartDate"); return checkoutSummary(model); } if (B2BReplenishmentRecurrenceEnum.WEEKLY.equals(placeOrderForm.getReplenishmentRecurrence())) { if (CollectionUtils.isEmpty(placeOrderForm.getnDaysOfWeek())) { GlobalMessages.addErrorMessage(model, "checkout.error.replenishment.no.Frequency"); return checkoutSummary(model); } } final TriggerData triggerData = new TriggerData(); populateTriggerDataFromPlaceOrderForm(placeOrderForm, triggerData); final ScheduledCartData scheduledCartData = getCheckoutFlowFacade().scheduleOrder(triggerData); return REDIRECT_PREFIX + "/checkout/replenishmentConfirmation/" + scheduledCartData.getJobCode(); } final OrderData orderData; try { orderData = getCheckoutFlowFacade().placeOrder(); } catch (final Exception e) { GlobalMessages.addErrorMessage(model, "checkout.placeOrder.failed"); placeOrderForm.setNegotiateQuote(true); model.addAttribute(placeOrderForm); return checkoutSummary(model); } if (placeOrderForm.isNegotiateQuote()) { return REDIRECT_PREFIX + "/checkout/quoteOrderConfirmation/" + orderData.getCode(); } else { return REDIRECT_PREFIX + "/checkout/orderConfirmation/" + orderData.getCode(); } }
From source file:fragment.web.TenantsControllerTest.java
@Test public void testTenantCreationNegative() throws Exception { AccountType type = accountTypeDAO.find(4L); Tenant tenant = new Tenant("Acme Corp " + random.nextInt(), type, getRootUser(), randomAddress(), true, currencyValueService.locateBYCurrencyCode("USD"), getPortalUser()); List<Country> countryList = countryDAO.findAll(null); Profile profile = profileDAO.find(8L); User user = new User("firstName", "lastName", "nageswarareddy.poli@citrix.com", "username14", "Portal123#", "91-9885098850", "GMT", null, profile, getRootUser()); user.setAddress(randomAddress());//from w w w . j a va 2 s . co m tenant.setOwner(user); com.citrix.cpbm.access.User newUser = (com.citrix.cpbm.access.User) CustomProxy.newInstance(user); com.citrix.cpbm.access.Tenant newTenant = (com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(tenant); TenantForm form = new TenantForm(); form.setAccountTypeId("4"); form.setUser(newUser); form.setTenant(newTenant); form.setCountryList(countryList); BeanPropertyBindingResult result = new BeanPropertyBindingResult(form, "validation"); result.addError(new FieldError("Error", "Error", "Error")); String tenantCreation = controller.create(form, result, map, status, request); logger.debug("RESULT------------------------" + tenantCreation); Assert.assertFalse("verifying the form has zero error", tenantCreation.contains("0 errors")); }
From source file:com.ms.commons.summer.web.handler.DataBinderUtil.java
/** * ?// ww w. jav a 2s .c o m * * @param method * @param model * @param request * @param response * @param c * @return */ @SuppressWarnings("unchecked") public static Object[] getArgs(Method method, Map<String, Object> model, HttpServletRequest request, HttpServletResponse response, Class<?> c) { Class<?>[] paramTypes = method.getParameterTypes(); Object[] args = new Object[paramTypes.length]; Map<String, Object> argMap = new HashMap<String, Object>(args.length); Map<String, String> pathValues = null; PathPattern pathPattern = method.getAnnotation(PathPattern.class); if (pathPattern != null) { String path = request.getRequestURI(); int index = path.lastIndexOf('.'); if (index != -1) { path = path.substring(0, index); String[] patterns = pathPattern.patterns(); pathValues = getPathValues(patterns, path); } } MapBindingResult errors = new MapBindingResult(argMap, ""); ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); for (int i = 0; i < paramTypes.length; i++) { Class<?> paramType = paramTypes[i]; MethodParameter methodParam = new MethodParameter(method, i); methodParam.initParameterNameDiscovery(parameterNameDiscoverer); GenericTypeResolver.resolveParameterType(methodParam, c.getClass()); String paramName = methodParam.getParameterName(); // map if (Map.class.isAssignableFrom(paramType)) { args[i] = model; } // HttpServletRequest else if (HttpServletRequest.class.isAssignableFrom(paramType)) { args[i] = request; } // HttpServletResponse else if (HttpServletResponse.class.isAssignableFrom(paramType)) { args[i] = response; } // HttpSession else if (HttpSession.class.isAssignableFrom(paramType)) { args[i] = request.getSession(); } // Errors else if (Errors.class.isAssignableFrom(paramType)) { args[i] = errors; } // MultipartFile else if (MultipartFile.class.isAssignableFrom(paramType)) { MultipartFile[] files = resolveMultipartFiles(request, errors, paramName); if (files != null && files.length > 0) { args[i] = files[0]; } } // MultipartFile[] else if (MultipartFile[].class.isAssignableFrom(paramType)) { args[i] = resolveMultipartFiles(request, errors, paramName); } else { // ?? if (BeanUtils.isSimpleProperty(paramType)) { SimpleTypeConverter converter = new SimpleTypeConverter(); Object value; // ? if (paramType.isArray()) { value = request.getParameterValues(paramName); } else { Object[] parameterAnnotations = methodParam.getParameterAnnotations(); value = null; if (parameterAnnotations != null && parameterAnnotations.length > 0) { if (pathValues != null && pathValues.size() > 0) { for (Object object : parameterAnnotations) { if (PathVariable.class.isInstance(object)) { PathVariable pv = (PathVariable) object; if (StringUtils.isEmpty(pv.value())) { value = pathValues.get(paramName); } else { value = pathValues.get(pv.value()); } break; } } } } else { value = request.getParameter(paramName); } } try { args[i] = converter.convertIfNecessary(value, paramType, methodParam); model.put(paramName, args[i]); } catch (TypeMismatchException e) { errors.addError(new FieldError(paramName, paramName, e.getMessage())); } } else { // ???POJO if (paramType.isArray()) { ObjectArrayDataBinder binder = new ObjectArrayDataBinder(paramType.getComponentType(), paramName); args[i] = binder.bind(request); model.put(paramName, args[i]); } else { Object bindObject = BeanUtils.instantiateClass(paramType); SummerServletRequestDataBinder binder = new SummerServletRequestDataBinder(bindObject, paramName); binder.bind(request); BindException be = new BindException(binder.getBindingResult()); List<FieldError> fieldErrors = be.getFieldErrors(); for (FieldError fieldError : fieldErrors) { errors.addError(fieldError); } args[i] = binder.getTarget(); model.put(paramName, args[i]); } } } } return args; }
From source file:com.ms.commons.summer.web.handler.ObjectArrayDataBinder.java
@SuppressWarnings("unchecked") private int initParamAndValues(HttpServletRequest request, String name, Map<String, String[]> paramAndValues) { int size = -1; boolean checkPrefix = false; if (StringUtils.isNotEmpty(name)) { checkPrefix = true;//from w w w .ja v a 2 s .co m } for (Enumeration<String> parameterNames = request.getParameterNames(); parameterNames.hasMoreElements();) { String parameterName = parameterNames.nextElement(); if (checkPrefix && parameterName.startsWith(name + ".")) { String[] values = request.getParameterValues(parameterName); if (values != null && values.length > 0) { paramAndValues.put(parameterName.substring(name.length() + 1), values); if (size == -1) { size = values.length; } else if (size != values.length) { fieldError = new FieldError(name, name, "?"); return -1; } } } } return size; }