Example usage for org.springframework.validation BindingResult getObjectName

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

Introduction

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

Prototype

String getObjectName();

Source Link

Document

Return the name of the bound root object.

Usage

From source file:org.easy.spring.web.ValidationSupport.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)//from w ww . jav a 2  s  .  c om
@ResponseBody
public ValidationError processValidationError(MethodArgumentNotValidException ex) {
    BindingResult errors = ex.getBindingResult();
    ValidationError result = new ValidationError(errors.getObjectName(), errors.getNestedPath(),
            errors.getErrorCount(), errors.getFieldErrors());

    return result;//processFieldErrors(fieldErrors);
}

From source file:org.easyj.rest.controller.GenericEntityController.java

public <T> void bindValidatorErrors(Set<ConstraintViolation<T>> violations, BindingResult result) {
    if (violations != null) {
        for (ConstraintViolation<T> violation : violations) {
            result.addError(new FieldError(result.getObjectName(), violation.getPropertyPath().toString(),
                    violation.getInvalidValue(), false, null, null, violation.getMessageTemplate()));
        }/*from  w  w  w  .j  a v a2s .c o m*/
    }
}

From source file:de.interseroh.report.controller.ParameterFormBinder.java

public void bind(final ParameterForm parameterForm, final MultiValueMap<String, String> requestParameters,
        BindingResult bindingResult) {

    final MutablePropertyValues mpvs = createPropertyValues(parameterForm, requestParameters);

    DataBinder dataBinder = new DataBinder(parameterForm, bindingResult.getObjectName());
    dataBinder.bind(mpvs);// www .  j ava 2s .c  om
    bindingResult.addAllErrors(dataBinder.getBindingResult());
}

From source file:net.solarnetwork.util.BindingResultSerializer.java

@Override
public Object serialize(Object data, String propertyName, Object propertyValue) {
    if (propertyValue == null) {
        return null;
    }/*from  w  w  w . j av  a  2 s. com*/
    if (!(propertyValue instanceof BindingResult)) {
        throw new IllegalArgumentException("Not a BindingResult: " + propertyValue.getClass());
    }
    BindingResult br = (BindingResult) propertyValue;
    if (!br.hasErrors()) {
        return null;
    }
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("objectName", br.getObjectName());
    map.put("errors", br.getAllErrors());
    map.put("globalErrors", br.getGlobalErrors());
    return map;
}

From source file:org.jdal.ui.bind.ControlBindingErrorProcessor.java

/** 
 * Add a ControlError instead FieldError to hold component that has failed.
 * @param control// w w  w .ja  va 2s  .  c  o  m
 * @param ex
 * @param bindingResult
 */
public void processPropertyAccessException(Object control, PropertyAccessException ex,
        BindingResult bindingResult) {
    // Create field error with the exceptions's code, e.g. "typeMismatch".
    String field = ex.getPropertyName();
    String[] codes = bindingResult.resolveMessageCodes(ex.getErrorCode(), field);
    Object[] arguments = getArgumentsForBindError(bindingResult.getObjectName(), field);
    Object rejectedValue = ex.getValue();
    if (rejectedValue != null && rejectedValue.getClass().isArray()) {
        rejectedValue = StringUtils.arrayToCommaDelimitedString(ObjectUtils.toObjectArray(rejectedValue));
    }
    bindingResult.addError(new ControlError(control, bindingResult.getObjectName(), field, rejectedValue, true,
            codes, arguments, ex.getLocalizedMessage()));
}

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

/**
 * //w w  w  .j  a v  a 2  s. c  o  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:utils.play.BugWorkaroundForm.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from w w w.  j  av  a 2s  .c  o m*/
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:net.nicholaswilliams.java.teamcity.plugin.buildNumber.TestSharedBuildNumberController.java

@Test
public void testDoHandleAddBuildNumberPost02() throws IOException, ServletException {
    this.setUpSecurity();

    expect(this.request.getParameter("action")).andReturn("add");
    expect(this.request.getMethod()).andReturn("POST");
    expect(this.request.getParameter("name")).andReturn("Hello");
    expect(this.request.getParameter("description")).andReturn("This is a description.");
    expect(this.request.getParameter("format")).andReturn("1.0.0.{D}");
    expect(this.request.getParameter("dateFormat")).andReturn("Ym");
    expect(this.request.getParameter("counter")).andReturn("-16");

    replay(this.service, this.request, this.response);

    ModelAndView modelAndView = this.controller.doHandle(this.request, this.response);

    assertNotNull("The model and view should not be null.", modelAndView);
    assertEquals("The view is not correct.", "/plugin/" + testNum + "/jsp/addBuildNumber.jsp",
            modelAndView.getViewName());

    Map<String, Object> model = modelAndView.getModel();
    assertNotNull("The model should not be null.", model);

    Object object = model.get(BindingResult.MODEL_KEY_PREFIX + "sharedBuildNumberForm");
    assertNotNull("The binding result attribute should not be null.", object);
    assertTrue("The binding result attribute should be a binding result object.",
            object instanceof BindingResult);

    BindingResult result = (BindingResult) object;
    assertEquals("The binding result object name is not correct.", "sharedBuildNumberForm",
            result.getObjectName());
    assertTrue("The binding result should have errors.", result.hasErrors());
    assertEquals("The binding result should have 2 errors.", 2, result.getErrorCount());

    List<FieldError> errors = result.getFieldErrors();
    assertNotNull("The list of errors should not be null.", errors);
    assertEquals("The list length is not correct.", 2, errors.size());
    assertEquals("The first error is not correct.", "counter", errors.get(0).getField());
    assertEquals("The first error has the wrong message.", "The counter must be a positive integer.",
            errors.get(0).getDefaultMessage());
    assertEquals("The second error is not correct.", "dateFormat", errors.get(1).getField());
    assertEquals("The second error has the wrong message.",
            "The date format must be at least 3 characters long.", errors.get(1).getDefaultMessage());

    object = model.get("sharedBuildNumberForm");
    assertNotNull("sharedBuildNumberForm should not be null.", object);
    assertTrue("sharedBuildNumberForm should be a SharedBuildNumber.", object instanceof SharedBuildNumber);

    SharedBuildNumber form = (SharedBuildNumber) object;
    assertEquals("The name is not correct.", "Hello", form.getName());
    assertEquals("The description is not correct.", "This is a description.", form.getDescription());
    assertEquals("The format is not correct.", "1.0.0.{D}", form.getFormat());
    assertEquals("The date format is not correct.", "Ym", form.getDateFormat());
    assertEquals("The counter is not correct.", 1, form.getCounter());
}

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

@Test
public void testDoHandleAddBuildNumberPost01() throws IOException, ServletException {
    this.setUpSecurity();

    expect(this.request.getParameter("action")).andReturn("add");
    expect(this.request.getMethod()).andReturn("POST");
    expect(this.request.getParameter("name")).andReturn("help");
    expect(this.request.getParameter("description")).andReturn("");
    expect(this.request.getParameter("format")).andReturn("{0");
    expect(this.request.getParameter("dateFormat")).andReturn("Ym");
    expect(this.request.getParameter("counter")).andReturn("15.1");

    replay(this.service, this.request, this.response);

    ModelAndView modelAndView = this.controller.doHandle(this.request, this.response);

    assertNotNull("The model and view should not be null.", modelAndView);
    assertEquals("The view is not correct.", "/plugin/" + testNum + "/jsp/addBuildNumber.jsp",
            modelAndView.getViewName());

    Map<String, Object> model = modelAndView.getModel();
    assertNotNull("The model should not be null.", model);

    Object object = model.get(BindingResult.MODEL_KEY_PREFIX + "sharedBuildNumberForm");
    assertNotNull("The binding result attribute should not be null.", object);
    assertTrue("The binding result attribute should be a binding result object.",
            object instanceof BindingResult);

    BindingResult result = (BindingResult) object;
    assertEquals("The binding result object name is not correct.", "sharedBuildNumberForm",
            result.getObjectName());
    assertTrue("The binding result should have errors.", result.hasErrors());
    assertEquals("The binding result should have 3 errors.", 3, result.getErrorCount());

    List<FieldError> errors = result.getFieldErrors();
    assertNotNull("The list of errors should not be null.", errors);
    assertEquals("The list length is not correct.", 3, errors.size());
    assertEquals("The first error is not correct.", "counter", errors.get(0).getField());
    assertEquals("The first error has the wrong message.", "The counter must be a positive integer.",
            errors.get(0).getDefaultMessage());
    assertEquals("The second error is not correct.", "name", errors.get(1).getField());
    assertEquals("The second error has the wrong message.",
            "The name must be between 5 and 60 characters long.", errors.get(1).getDefaultMessage());
    assertEquals("The third error is not correct.", "format", errors.get(2).getField());
    assertEquals("The third error has the wrong message.",
            "The build number format must be at least 3 characters long.", errors.get(2).getDefaultMessage());

    object = model.get("sharedBuildNumberForm");
    assertNotNull("sharedBuildNumberForm should not be null.", object);
    assertTrue("sharedBuildNumberForm should be a SharedBuildNumber.", object instanceof SharedBuildNumber);

    SharedBuildNumber form = (SharedBuildNumber) object;
    assertEquals("The name is not correct.", "help", form.getName());
    assertEquals("The description is not correct.", "", form.getDescription());
    assertEquals("The format is not correct.", "{0", form.getFormat());
    assertEquals("The date format is not correct.", "Ym", form.getDateFormat());
    assertEquals("The counter is not correct.", 1, form.getCounter());
}

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

@Test
public void testDoHandleEditBuildNumberPost03() throws IOException, ServletException {
    this.setUpSecurity();

    SharedBuildNumber originalNumber = new SharedBuildNumber(26);

    expect(this.request.getParameter("action")).andReturn("edit");
    expect(this.request.getMethod()).andReturn("POST");
    expect(this.request.getParameter("id")).andReturn("26");
    expect(this.service.getSharedBuildNumber(26)).andReturn(originalNumber);
    expect(this.request.getParameter("name")).andReturn("Hello");
    expect(this.request.getParameter("description")).andReturn("This is a description.");
    expect(this.request.getParameter("format")).andReturn("1.0.0.{D}");
    expect(this.request.getParameter("dateFormat")).andReturn("Ym");
    expect(this.request.getParameter("counter")).andReturn("-16");

    replay(this.service, this.request, this.response);

    ModelAndView modelAndView = this.controller.doHandle(this.request, this.response);

    assertNotNull("The model and view should not be null.", modelAndView);
    assertEquals("The view is not correct.", "/plugin/" + testNum + "/jsp/editBuildNumber.jsp",
            modelAndView.getViewName());

    Map<String, Object> model = modelAndView.getModel();
    assertNotNull("The model should not be null.", model);
    assertEquals("sbnParameterPrefix is not correct.", BuildNumberPropertiesProvider.PARAMETER_PREFIX,
            model.get("sbnParameterPrefix"));

    Object object = model.get(BindingResult.MODEL_KEY_PREFIX + "sharedBuildNumberForm");
    assertNotNull("The binding result attribute should not be null.", object);
    assertTrue("The binding result attribute should be a binding result object.",
            object instanceof BindingResult);

    BindingResult result = (BindingResult) object;
    assertEquals("The binding result object name is not correct.", "sharedBuildNumberForm",
            result.getObjectName());
    assertTrue("The binding result should have errors.", result.hasErrors());
    assertEquals("The binding result should have 2 errors.", 2, result.getErrorCount());

    List<FieldError> errors = result.getFieldErrors();
    assertNotNull("The list of errors should not be null.", errors);
    assertEquals("The list length is not correct.", 2, errors.size());
    assertEquals("The first error is not correct.", "counter", errors.get(0).getField());
    assertEquals("The first error has the wrong message.", "The counter must be a positive integer.",
            errors.get(0).getDefaultMessage());
    assertEquals("The second error is not correct.", "dateFormat", errors.get(1).getField());
    assertEquals("The second error has the wrong message.",
            "The date format must be at least 3 characters long.", errors.get(1).getDefaultMessage());

    object = model.get("sharedBuildNumberForm");
    assertNotNull("sharedBuildNumberForm should not be null.", object);
    assertTrue("sharedBuildNumberForm should be a SharedBuildNumber.", object instanceof SharedBuildNumber);

    SharedBuildNumber form = (SharedBuildNumber) object;
    assertEquals("The name is not correct.", "Hello", form.getName());
    assertEquals("The description is not correct.", "This is a description.", form.getDescription());
    assertEquals("The format is not correct.", "1.0.0.{D}", form.getFormat());
    assertEquals("The date format is not correct.", "Ym", form.getDateFormat());
    assertEquals("The counter is not correct.", 1, form.getCounter());
}