List of usage examples for org.springframework.validation BindingResult getTarget
@Nullable Object getTarget();
From source file:fragment.web.RegistrationControllerTest.java
@Test public void testRegisterBindingHasErrors() throws Exception { MockHttpServletRequest mockRequest = getRequestTemplate(HttpMethod.GET, "/portal/register"); mockRequest.setRemoteAddr("1.1.1.1"); User user = new User("test", "test", "testtest.com", "testuser", VALID_PASSWORD, VALID_PHONE, VALID_TIMEZONE, null, null, getRootUser()); user.setAddress(randomAddress());//from w w w . j av a 2 s . c o m Tenant newTenant = new Tenant("New Co", accountTypeDAO.getDefaultRegistrationAccountType(), null, randomAddress(), true, currencyValueService.locateBYCurrencyCode("USD"), null); UserRegistration registration = new UserRegistration(); registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null)); registration.setUser((com.citrix.cpbm.access.User) CustomProxy.newInstance(user)); registration.setTenant((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(newTenant)); registration.setDisposition(accountTypeDAO.getDefaultRegistrationAccountType()); BindingResult result = validate(registration); beforeRegisterCall(mockRequest, registration); String view = controller.register(registration, result, "abc", "abc", map, null, status, mockRequest); Assert.assertEquals("register.moreuserinfo", view); Assert.assertFalse(status.isComplete()); Assert.assertTrue(((UserRegistration) result.getTarget()).getUser().getObject().getId() == 0); Assert.assertTrue(((UserRegistration) result.getTarget()).getTenant().getId() == 0); }
From source file:utils.play.BugWorkaroundForm.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override//from w w w. j av a 2 s. c om public Form<T> bind(final Map<String, String> data, final String... allowedFields) { DataBinder dataBinder = null; Map<String, String> objectData = data; if (rootName == null) { dataBinder = new DataBinder(blankInstance()); } else { dataBinder = new DataBinder(blankInstance(), rootName); objectData = new HashMap<String, String>(); for (String key : data.keySet()) { if (key.startsWith(rootName + ".")) { objectData.put(key.substring(rootName.length() + 1), data.get(key)); } } } if (allowedFields.length > 0) { dataBinder.setAllowedFields(allowedFields); } SpringValidatorAdapter validator = new SpringValidatorAdapter(Validation.getValidator()); dataBinder.setValidator(validator); dataBinder.setConversionService(play.data.format.Formatters.conversion); dataBinder.setAutoGrowNestedPaths(true); dataBinder.bind(new MutablePropertyValues(objectData)); Set<ConstraintViolation<Object>> validationErrors = validator.validate(dataBinder.getTarget()); BindingResult result = dataBinder.getBindingResult(); for (ConstraintViolation<Object> violation : validationErrors) { String field = violation.getPropertyPath().toString(); FieldError fieldError = result.getFieldError(field); if (fieldError == null || !fieldError.isBindingFailure()) { try { result.rejectValue(field, violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(), getArgumentsForConstraint(result.getObjectName(), field, violation.getConstraintDescriptor()), violation.getMessage()); } catch (NotReadablePropertyException ex) { throw new IllegalStateException("JSR-303 validated property '" + field + "' does not have a corresponding accessor for data binding - " + "check your DataBinder's configuration (bean property versus direct field access)", ex); } } } if (result.hasErrors()) { Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>(); for (FieldError error : result.getFieldErrors()) { String key = error.getObjectName() + "." + error.getField(); System.out.println("Error field:" + key); if (key.startsWith("target.") && rootName == null) { key = key.substring(7); } List<Object> arguments = new ArrayList<>(); for (Object arg : error.getArguments()) { if (!(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) { arguments.add(arg); } } if (!errors.containsKey(key)) { errors.put(key, new ArrayList<ValidationError>()); } errors.get(key).add(new ValidationError(key, error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(), arguments)); } return new Form(rootName, backedType, data, errors, F.Option.None()); } else { Object globalError = null; if (result.getTarget() != null) { try { java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate"); globalError = v.invoke(result.getTarget()); } catch (NoSuchMethodException e) { } catch (Throwable e) { throw new RuntimeException(e); } } if (globalError != null) { Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>(); if (globalError instanceof String) { errors.put("", new ArrayList<ValidationError>()); errors.get("").add(new ValidationError("", (String) globalError, new ArrayList())); } else if (globalError instanceof List) { for (ValidationError error : (List<ValidationError>) globalError) { List<ValidationError> errorsForKey = errors.get(error.key()); if (errorsForKey == null) { errors.put(error.key(), errorsForKey = new ArrayList<ValidationError>()); } errorsForKey.add(error); } } else if (globalError instanceof Map) { errors = (Map<String, List<ValidationError>>) globalError; } if (result.getTarget() != null) { return new Form(rootName, backedType, data, errors, F.Option.Some((T) result.getTarget())); } else { return new Form(rootName, backedType, data, errors, F.Option.None()); } } return new Form(rootName, backedType, new HashMap<String, String>(data), new HashMap<String, List<ValidationError>>(errors), F.Option.Some((T) result.getTarget())); } }
From source file:de.hybris.platform.ytelcoacceleratorstorefront.controllers.pages.payment.SilentOrderPostMockController.java
@RequestMapping(value = "/handle-form-post", method = RequestMethod.POST) public String handleFormPost(@Valid final SopPaymentDetailsForm form, final BindingResult bindingResult, @RequestParam("targetArea") final String targetArea, @RequestParam("editMode") final Boolean editMode, @RequestParam("paymentInfoId") final String paymentInfoId, final RedirectAttributes redirectAttributes) { getSopPaymentDetailsValidator().validate(form, bindingResult); if (bindingResult.hasErrors()) { redirectAttributes.addFlashAttribute(GlobalMessages.ERROR_MESSAGES_HOLDER, Collections.singletonList("checkout.error.paymentmethod.formentry.invalid")); redirectAttributes.addFlashAttribute( "org.springframework.validation.BindingResult.sopPaymentDetailsForm", bindingResult); redirectAttributes.addFlashAttribute("sopPaymentDetailsForm", bindingResult.getTarget()); return Boolean.TRUE.equals(editMode) ? REDIRECT_URL_EDIT_PAYMENT_DETAILS + paymentInfoId : REDIRECT_URL_ADD_PAYMENT_METHOD + targetArea; } else {//from ww w . ja v a 2 s . c om final String authorizationRequestId = (String) getSessionService() .getAttribute("authorizationRequestId"); final String authorizationRequestToken = (String) getSessionService() .getAttribute("authorizationRequestToken"); try { if (BooleanUtils.isTrue(editMode)) { final CCPaymentInfoData ccPaymentInfoData = setupCCPaymentInfoData(form, paymentInfoId); if (null != ccPaymentInfoData) { final CCPaymentInfoData result = getSubscriptionFacade() .changePaymentMethod(ccPaymentInfoData, null, true, null); // enrich result data with form data, which is not provided from the facade call result.setId(paymentInfoId); result.getBillingAddress() .setTitleCode(ccPaymentInfoData.getBillingAddress().getTitleCode()); result.setStartMonth(ccPaymentInfoData.getStartMonth()); result.setStartYear(ccPaymentInfoData.getStartYear()); result.setIssueNumber(ccPaymentInfoData.getIssueNumber()); getUserFacade().updateCCPaymentInfo(result); if (form.getMakeAsDefault().booleanValue()) { getUserFacade().setDefaultPaymentInfo(result); } redirectAttributes.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER, Collections.singletonList("text.account.paymentDetails.editSuccessful")); } else { redirectAttributes.addFlashAttribute(GlobalMessages.ERROR_MESSAGES_HOLDER, Collections.singletonList("text.account.paymentDetails.nonExisting.error")); } } else { final SubscriptionPaymentData result = getSubscriptionFacade().finalizeTransaction( authorizationRequestId, authorizationRequestToken, createPaymentDetailsMap(form, targetArea)); final CCPaymentInfoData newPaymentSubscription = getSubscriptionFacade() .createPaymentSubscription(result.getParameters()); // enrich result data with form data, which is not provided from the facade call if (BooleanUtils.isNotTrue(form.getNewBillingAddress()) && null != getCheckoutFacade().getCheckoutCart() && null != getCheckoutFacade().getCheckoutCart().getDeliveryAddress()) { newPaymentSubscription.getBillingAddress().setTitleCode( getCheckoutFacade().getCheckoutCart().getDeliveryAddress().getTitleCode()); } else if (null != form.getBillingAddress()) { newPaymentSubscription.getBillingAddress() .setTitleCode(form.getBillingAddress().getTitleCode()); } newPaymentSubscription.setStartMonth(form.getStartMonth()); newPaymentSubscription.setStartYear(form.getStartYear()); newPaymentSubscription.setIssueNumber(form.getIssueNumber()); newPaymentSubscription.setSaved(true); getUserFacade().updateCCPaymentInfo(newPaymentSubscription); if (form.getMakeAsDefault().booleanValue()) { getUserFacade().setDefaultPaymentInfo(newPaymentSubscription); } getCheckoutFacade().setPaymentDetails(newPaymentSubscription.getId()); redirectAttributes.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER, Collections.singletonList("text.account.paymentDetails.addSuccessful")); } } catch (final SubscriptionFacadeException e) { LOG.error("Creating a new payment method failed", e); redirectAttributes.addFlashAttribute(GlobalMessages.ERROR_MESSAGES_HOLDER, Collections.singletonList("checkout.multi.paymentMethod.addPaymentDetails.incomplete")); return REDIRECT_URL_ADD_PAYMENT_METHOD + targetArea; } } if (StringUtils.equals(targetArea, "multiCheckoutArea")) { return REDIRECT_URL_SUMMARY; } return REDIRECT_URL_PAYMENT_INFO; }
From source file:org.gbif.portal.web.controller.registration.RegistrationController.java
/** * Saves the values for the data provider *///w w w. j a v a 2 s . c o m @SuppressWarnings("unchecked") public ModelAndView synchroniseProvider(HttpServletRequest request, HttpServletResponse response) throws Exception { ProviderDetail provider = new ProviderDetail(); ServletRequestDataBinder binder = createBinder(request, provider); initBinder(request, binder); binder.bind(request); BindingResult result = binder.getBindingResult(); validateDataProvider(provider, result); if (result.hasErrors()) { logger.info("Errors have occurred: " + result); Map<String, Object> data = new HashMap<String, Object>(); // put the errors in the request data.put(BindingResult.MODEL_KEY_PREFIX + RegistrationController.REQUEST_PROVIDER_DETAIL, result); data.put(RegistrationController.REQUEST_CONTACT_TYPES, ProviderDetail.ContactTypes.values()); data.put(RegistrationController.REQUEST_PROVIDER_DETAIL, result.getTarget()); data.putAll(referenceDataForProvider(request)); return new ModelAndView("registrationUpdateProviderDetail", data); } else { boolean success = synchroniseProvider(request, provider, result); if (!success) { return new ModelAndView("registrationUDDIFailure"); } // return showDataResources(request, response, provider); return new ModelAndView(new RedirectView(request.getContextPath() + "/register/viewDataProvider?" + REQUEST_BUSINESS_UDDI_KEY + "=" + provider.getBusinessKey())); } }
From source file:org.shept.org.springframework.web.servlet.mvc.delegation.ComponentUtils.java
/** * //from www.j a va2s . c o m * @param * @return * * @param modelAndView * @return */ public static SubCommandProvider getCommand(ModelAndView modelAndView) { String prefix = BindingResult.MODEL_KEY_PREFIX; if (modelAndView == null) { return null; } for (String name : modelAndView.getModel().keySet()) { if (name.startsWith(prefix)) { BindingResult res = BindingResultUtils.getBindingResult(modelAndView.getModel(), name.substring(prefix.length())); if (res != null && res.getTarget() instanceof SubCommandProvider) { return (SubCommandProvider) res.getTarget(); } } } return null; }
From source file:org.springframework.web.servlet.mvc.generic.GenericFormController.java
/** * Prepare model and view for the given form, including reference and errors, * adding a controller-specific control model. * <p>In session form mode: Re-puts the form object in the session when returning * to the form, as it has been removed by getCommand. * <p>Can be used in subclasses to redirect back to a specific form page. * @param request current HTTP request/*w w w .j av a2 s . c o m*/ * @param bindingResult validation errors holder * @return the prepared form view */ protected final ModelAndView showForm(HttpServletRequest request, BindingResult bindingResult) { // In session form mode, re-expose form object as HTTP session attribute. // Re-binding is necessary for proper state handling in a cluster, // to notify other nodes of changes in the form object. String formAttrName = getFormSessionAttributeName(request); if (logger.isDebugEnabled()) { logger.debug("Setting form session attribute [" + formAttrName + "] to: " + bindingResult.getTarget()); } request.getSession().setAttribute(formAttrName, bindingResult.getTarget()); // Fetch errors model as starting point, containing form object under // "formObjectName", and corresponding Errors instance under internal key. ModelMap model = new ModelMap().addAllAttributes(bindingResult.getModel()); // Merge reference data into model, if any. populateModel(request, model, bindingResult); // Trigger rendering of the specified view, using the final model. return new ModelAndView(getFormView(request), model); }