Example usage for org.springframework.validation BindingResult getTarget

List of usage examples for org.springframework.validation BindingResult getTarget

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult getTarget.

Prototype

@Nullable
Object getTarget();

Source Link

Document

Return the wrapped target object, which may be a bean, an object with public fields, a Map - depending on the concrete binding strategy.

Usage

From source file:com.create.controller.BeanValidatorErrorHandler.java

private List<?> getTargets(BindingResult result) {
    final Object target = result.getTarget();
    return target instanceof List ? (List<?>) target : Collections.singletonList(target);
}

From source file:cn.powerdash.libsystem.common.exception.BindingResultExceptionHandler.java

/**
 * /*from w  ww.ja  v  a 2s.  co  m*/
 * Description: set the validation data.
 * 
 * @param bindingResults
 * @param handler
 * @param formId
 * @param error
 * @param locale
 */
@Override
protected void setValidationErrorData(final Exception ex, final Object handler, final String formId,
        ResultDto<List<ValidationResultDto>> error) {
    ValidateException vex = (ValidateException) ex;
    List<BindingResult> bindingResults = vex.getBindingResults(); // get those bindingResults
    final List<ValidationResultDto> errorData = error.getData();
    if (StringUtils.isNotEmpty(formId) && bindingResults != null && bindingResults.size() > 0
            && handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // method parameter arrays
        MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
        if (methodParameters != null && methodParameters.length > 0) {
            for (BindingResult bindingResult : bindingResults) {
                Class<?> doaminClass = bindingResult.getTarget().getClass();
                for (MethodParameter methodParameter : methodParameters) {
                    Class<?> dtoClass = methodParameter.getParameterType();
                    if (!dtoClass.equals(doaminClass)) {
                        continue;
                    } else if (doaminClass.equals(dtoClass)) {
                        setResultDto(bindingResult, errorData, formId, false);
                    }
                }
            }
        } else {
            for (BindingResult bindingResult : bindingResults) {
                setResultDto(bindingResult, errorData, formId, true);
            }
        }
    }
}

From source file:org.frat.common.exception.BindingResultExceptionHandler.java

/**
 * //from  w w w  .  j a va2 s . com
 * Description: set the validation data.
 * 
 * @param bindingResults
 * @param handler
 * @param formId
 * @param error
 * @param locale
 */
@Override
protected void setValidationErrorData(final Exception ex, final Object handler, final String formId,
        ResultDto error) {
    ValidateException vex = (ValidateException) ex;
    List<BindingResult> bindingResults = vex.getBindingResults();
    // get

    // those

    // bindingResults
    @SuppressWarnings("unchecked")
    final List<ValidationResultDto> errorData = (List<ValidationResultDto>) error.getData();
    if (StringUtils.isNotEmpty(formId) && bindingResults != null && bindingResults.size() > 0
            && handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // method parameter arrays
        MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
        if (methodParameters != null && methodParameters.length > 0) {
            for (BindingResult bindingResult : bindingResults) {
                Class<?> doaminClass = bindingResult.getTarget().getClass();
                for (MethodParameter methodParameter : methodParameters) {
                    Class<?> dtoClass = methodParameter.getParameterType();
                    if (!dtoClass.equals(doaminClass)) {
                        continue;
                    } else if (doaminClass.equals(dtoClass)) {
                        setResultDto(bindingResult, errorData, formId, false);
                    }
                }
            }
        } else {
            for (BindingResult bindingResult : bindingResults) {
                setResultDto(bindingResult, errorData, formId, true);
            }
        }
    }
}

From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.SharedBuildNumberController.java

private void bindAndValidateForm(HttpServletRequest request, BindingResult result) {
    SharedBuildNumber form = (SharedBuildNumber) result.getTarget();

    form.setName(request.getParameter("name"));
    form.setDescription(request.getParameter("description"));
    form.setFormat(request.getParameter("format"));
    form.setDateFormat(request.getParameter("dateFormat"));

    String counterString = request.getParameter("counter");
    if (NumberUtils.isDigits(counterString)) {
        form.setCounter(Integer.parseInt(counterString));
        if (form.getCounter() < 1)
            form.setCounter(1);//from w  ww  .ja  v a2s. c  o m
    } else {
        result.rejectValue("counter", "counter.not.integer", "The counter must be a positive integer.");
    }

    if (form.getName() == null || form.getName().trim().length() < 5 || form.getName().trim().length() > 60) {
        result.rejectValue("name", "name.length", "The name must be between 5 and 60 characters long.");
    }

    if (form.getFormat() == null || form.getFormat().trim().length() < 3) {
        result.rejectValue("format", "format.length",
                "The build number format must be at least 3 characters long.");
    } else if (form.getFormat().toLowerCase().contains("{d}")
            && (form.getDateFormat() == null || form.getDateFormat().trim().length() < 3)) {
        result.rejectValue("dateFormat", "dateFormat.length",
                "The date format must be at least 3 characters long.");
    }
}

From source file:org.frat.common.exception.BindingResultExceptionHandler.java

/**
 * /*  w  w  w .  j a  v  a 2  s .co  m*/
 * Description: set the result dto.
 * 
 * @param locale
 * 
 * @param constraintViolation
 * @throws NoSuchFieldException
 */
private void setResultDto(BindingResult bindingResult, List<ValidationResultDto> errorData, String formId,
        boolean notManually) {
    List<FieldError> fieldErros = bindingResult.getFieldErrors();
    String beanName = bindingResult.getObjectName();
    Object rootObject = bindingResult.getTarget();
    Class<?> rootClass = rootObject.getClass();
    if (fieldErros != null && fieldErros.size() > 0) {
        for (FieldError fieldError : fieldErros) {
            final String fieldName = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            final String errorCode = fieldError.getCode();
            if (StringUtils.isEmpty(message)) {
                message = MessageUtil.getMessage(StringUtils.isNotEmpty(errorCode) ? errorCode : message);
            }
            setFieldErrorMap(fieldName, beanName, rootClass, errorData, message, formId, notManually);
        }
    }
}

From source file:org.gvnix.web.json.BindingResultSerializer.java

/**
 * {@inheritDoc}/*from   w  ww.  ja v  a 2  s .  co m*/
 */
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {

    try {
        // Cast to BindingResult
        BindingResult result = (BindingResult) value;

        // Create the result map
        Map<String, Object> allErrorsMessages = new HashMap<String, Object>();

        // Get field errors
        List<FieldError> fieldErrors = result.getFieldErrors();
        if (fieldErrors.isEmpty()) {
            // Nothing to do
            jgen.writeNull();
            return;
        }

        // Check if target type is an array or a bean
        @SuppressWarnings("rawtypes")
        Class targetClass = result.getTarget().getClass();
        if (targetClass.isArray() || Collection.class.isAssignableFrom(targetClass)) {
            loadListErrors(result.getFieldErrors(), allErrorsMessages);
        } else {
            loadObjectErrors(result.getFieldErrors(), allErrorsMessages);
        }

        jgen.writeObject(allErrorsMessages);
    } catch (JsonProcessingException e) {
        LOGGER.warn(ERROR_WRITTING_BINDING, e);
        throw e;
    } catch (IOException e) {
        LOGGER.warn(ERROR_WRITTING_BINDING, e);
        throw e;
    } catch (Exception e) {
        LOGGER.warn(ERROR_WRITTING_BINDING, e);
        throw new IOException(ERROR_WRITTING_BINDING, e);
    }

}

From source file:com.epam.training.storefront.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 w  w w  .ja v  a2 s. c  o  m
        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
                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.agatom.springatom.cmp.wizards.core.AbstractWizardProcessor.java

@SuppressWarnings("UnusedAssignment")
private void doValidate(final WizardResult result, final DataBinder binder, String step,
        final Map<String, Object> formData, final Locale locale) throws Exception {

    final Object target = binder.getTarget();

    if (!StringUtils.hasText(step)) {
        // Wizard submission, because step is null
        step = this.stepHelperDelegate.getLastStep();
        if (!this.stepHelperDelegate.isValidationEnabled(step)) {
            // reset the step again
            step = null;/*  w  w w . j  ava2s  .c  om*/
        }
    }

    try {
        final BindingResult bindingResult = binder.getBindingResult();
        boolean alreadyValidate = false;

        if (this.localValidator != null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(String.format("Validating via Validator instance=%s", this.localValidator));
            }
            this.validationService.validate(this.localValidator, bindingResult, result);
            alreadyValidate = true;
        }

        if (!alreadyValidate) {
            final ValidationBean bean = new ValidationBean();

            bean.setPartialResult(result);
            bean.setStepId(step);
            bean.setCommandBean(bindingResult.getTarget());
            bean.setCommandBeanName(this.getContextObjectName());
            bean.setFormData(formData);
            bean.setBindingModel(formData);

            if (this.validationService.canValidate(bean)) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            String.format("Validating via validation service for validationBean=%s", bean));
                }
                this.validationService.validate(bean);
                alreadyValidate = true;
            }
        }

        /* Will validate only if not yet validated it is not step submission and wizard is allowed to validate
         * This a last opportunity to validate however unlike validation via
         * - localValidator
         * - validationService
         * this validation will be run only if
         * - not yet validated
         * - current (or last) step has validation flag set
         * - entire wizard has validation flag set
         */
        if (!alreadyValidate && this.isValidationEnabledForStep(step) && this.isValidationEnabled()) {
            LOGGER.debug(String.format(
                    "Not yet validated (tried localValidator and via validationService), assuming that is wizard submission due to step===null, validating through binder"));
            final Validator validator = binder.getValidator();
            if (validator != null) {

                final long startTime = System.nanoTime();
                validator.validate(target, bindingResult);
                final long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);

                result.addDebugData(WizardDebugDataKeys.VALIDATION_TIME, endTime);
                result.addDebugData(WizardDebugDataKeys.VALIDATOR,
                        ClassUtils.getShortName(validator.getClass()));

            }
        }

        if (LOGGER.isDebugEnabled()) {
            final Set<Message> messages = result.getValidationMessages();
            final short count = (short) (messages == null ? 0 : messages.size());
            LOGGER.debug(String.format("Validation completed, found %d validation errors", count));
        }
    } catch (Exception exp) {
        // Catch any validation exception and add it as an error
        LOGGER.error("Validation failed either via [localValidator,validationService,binder#validator", exp);
        result.addError(exp);
        result.addFeedbackMessage(FeedbackMessage.newError()
                .setTitle(this.messageSource.getMessage("sa.wiz.validationError.title", locale))
                .setMessage(this.messageSource.getMessage("sa.wiz.validationError.msg",
                        new Object[] { target.toString() }, locale)));
    }

}

From source file:org.easyj.rest.test.controller.TestEntityControllerTest.java

@Test
public void whenPUTWithWrongParams_returnBadRequest() throws Exception {
    BindingResult bindingResult;
    MvcResult result;//from  ww w  . j a  v  a 2 s  .  co  m

    result = mvc.perform(put("/entity/1")
            //Not posting firstName a @NotNull param
            .param(lastName, lastName).param(testDateKey, testDate)).andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    //Missing params should be binded to its own field name
    assertThat(bindingResult.getFieldError(firstName), notNullValue());

    result = mvc.perform(put("/entity/1").param(firstName, firstName)
            //Not posting lastName a different @NotNull param
            .param(testDateKey, testDate)).andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    //Missing params should be binded to its own field name
    assertThat(bindingResult.getFieldError(lastName), notNullValue());
}

From source file:org.easyj.rest.test.controller.TestEntityControllerTest.java

@Test
public void whenPOSTWithWrongParams_returnBadRequest() throws Exception {
    BindingResult bindingResult;
    MvcResult result;/*from   w ww.  j ava2  s .  c o  m*/

    result = mvc.perform(post("/entity").param("id", "1")//@Id should be null on POSTs
            .param(firstName, firstName).param(lastName, lastName).param(testDateKey, testDate))
            .andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    assertThat(bindingResult.getFieldError("id"), notNullValue());

    result = mvc.perform(post("/entity")
            //Not posting firstName a @NotNull param
            .param(lastName, lastName).param(testDateKey, testDate)).andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    //Missing params should be binded to its own field name
    assertThat(bindingResult.getFieldError(firstName), notNullValue());

    result = mvc.perform(post("/entity").param(firstName, firstName)
            //Not posting lastName a different @NotNull param
            .param(testDateKey, testDate)).andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    //Missing params should be binded to its own field name
    assertThat(bindingResult.getFieldError(lastName), notNullValue());
}