Example usage for org.springframework.validation FieldError getObjectName

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

Introduction

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

Prototype

public String getObjectName() 

Source Link

Document

Return the name of the affected object.

Usage

From source file:de.extra.client.core.util.impl.ExtraValidator.java

private String convertToString(final Errors errors) {
    final List<FieldError> fieldErrors = errors.getFieldErrors();
    final StringBuilder stringBuilder = new StringBuilder(fieldErrors.size() + " Konfigurationsfehler: ");
    final String sep = ";";
    for (final FieldError fieldError : fieldErrors) {
        stringBuilder.append(fieldError.getObjectName());
        stringBuilder.append(".").append(fieldError.getField());
        stringBuilder.append(" ").append(fieldError.getDefaultMessage());
        stringBuilder.append(sep);/*ww w .  jav  a2 s .c  o m*/
    }
    return stringBuilder.toString();
}

From source file:com.sra.biotech.submittool.persistence.client.SubmitExceptionHandler.java

@ExceptionHandler({ InvalidRequestException.class })
protected ResponseEntity<Object> handleInvalidRequest(RuntimeException e, WebRequest request) {
    InvalidRequestException ire = (InvalidRequestException) e;
    List<FieldErrorResource> fieldErrorResources = new ArrayList<>();

    List<FieldError> fieldErrors = ire.getErrors().getFieldErrors();
    for (FieldError fieldError : fieldErrors) {
        FieldErrorResource fieldErrorResource = new FieldErrorResource();
        fieldErrorResource.setResource(fieldError.getObjectName());
        fieldErrorResource.setField(fieldError.getField());
        fieldErrorResource.setCode(fieldError.getCode());
        fieldErrorResource.setMessage(fieldError.getDefaultMessage());
        fieldErrorResources.add(fieldErrorResource);
    }/*from  w ww .  ja  va2 s .  c  o m*/

    ErrorResource error = new ErrorResource("InvalidRequest", ire.getMessage());
    error.setFieldErrors(fieldErrorResources);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    return handleExceptionInternal(e, error, headers, HttpStatus.UNPROCESSABLE_ENTITY, request);
}

From source file:th.co.geniustree.dental.controller.ValidationExceptionHandler.java

private Map<String, ValidationErrorMessage> extractError(MethodArgumentNotValidException ex) {
    Map<String, ValidationErrorMessage> returnError = new HashMap<>();
    List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();

    for (ObjectError error : allErrors) {
        if (error instanceof FieldError) {
            FieldError fieldError = (FieldError) error;
            ValidationErrorMessage msg = new ValidationErrorMessage();
            msg.setMessage(fieldError.getDefaultMessage());
            msg.setType(fieldError.getObjectName());
            returnError.put(fieldError.getField(), msg);
        }//from ww  w .jav a2 s  .c  om
    }
    return returnError;
}

From source file:by.creepid.docgeneration.validation.RegValidator.java

@Override
public void validate(FacesContext context, UIComponent component, Object value) {

    Locale locale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale();

    WebUtils.clearFacesMessages(context);
    FirmReg firmReg = (FirmReg) WebUtils.findBean("reg");

    System.out.println(firmReg.toString());

    Errors errors = new BeanPropertyBindingResult(firmReg, "reg");
    firmRegValidator.validate(firmReg, errors);

    if (errors != null && errors.hasErrors()) {
        String message = messageSource.getMessage("error.validation", null, locale);

        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));

        List<FieldError> fieldErrors = errors.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            message = messageSource.getMessage(fieldError, locale);
            System.out.println(/*from  w  ww .j  a  v a  2 s  .com*/
                    fieldError.getField() + "   " + fieldError.getCode() + " " + fieldError.getObjectName());

            context.addMessage(fieldError.getField(),
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message));
        }
    }
}

From source file:utils.play.BugWorkaroundForm.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from ww w  .  jav  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:org.apereo.openlrs.controllers.xapi.XAPIExceptionHandlerAdvice.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody//  ww w . jav  a2  s .  c o m
public XAPIErrorInfo handleMethodArgumentNotValidException(final HttpServletRequest request,
        MethodArgumentNotValidException e) {
    final List<String> errorMessages = new ArrayList<String>();
    for (ObjectError oe : e.getBindingResult().getAllErrors()) {
        if (oe instanceof FieldError) {
            final FieldError fe = (FieldError) oe;
            final String msg = String.format("Field error in object '%s' on field '%s': rejected value [%s].",
                    fe.getObjectName(), fe.getField(), fe.getRejectedValue());
            errorMessages.add(msg);
        } else {
            errorMessages.add(oe.toString());
        }
    }
    final XAPIErrorInfo result = new XAPIErrorInfo(HttpStatus.BAD_REQUEST, request, errorMessages);
    this.logException(e);
    this.logError(result);
    return result;
}

From source file:jp.terasoluna.batch.functionsample.b009.SkipValidationErrorHandler.java

/**
 * ?O?W.<br>//w w w.  ja va 2 s. c om
 * @param dataValueObject DataValueObject
 * @param errors Errors
 * @return ?O
 */
protected String logEdit(DataValueObject dataValueObject, Errors errors) {
    StringBuilder sb = new StringBuilder();
    List<FieldError> fel = getFieldErrorList(errors);

    for (FieldError fe : fel) {
        sb.setLength(0);
        sb.append("ValidationError");
        sb.append(" dataCount:[");
        if (dataValueObject != null) {
            sb.append(dataValueObject.getDataCount());
        }
        sb.append("]");
        sb.append(" code:[");
        sb.append(fe.getCode());
        sb.append("]");
        sb.append(" objectName:[");
        sb.append(fe.getObjectName());
        sb.append("]");
        sb.append(" field:[");
        sb.append(fe.getField());
        sb.append("]");
        sb.append(" rejectedValue:[");
        sb.append(fe.getRejectedValue());
        sb.append("]");
    }
    return sb.toString();
}

From source file:org.opentestsystem.delivery.testreg.rest.FileUploadDataController.java

private void filterErrorRecords(final FormatType formatType, final List<Integer> ignoredRows,
        final List<TestRegistrationBase> recordList, final List<FieldError> fieldErrors) {
    final List<TestRegistrationBase> errorRecords = new ArrayList<>();
    for (final FieldError fieldError : fieldErrors) {
        if (FormatType.valueOf(fieldError.getObjectName()).equals(formatType)) {
            /*/*w w w.j  a va 2  s.  co m*/
             * Each field error has a metadata about where the error occurred in the upload file. Get the row number
             * and adjust that with the row offset value. Find all error records in the original collection this
             * way.
             */
            // HEADER ROW + ARRAYLIST ROW INDEX OFFSET + TOTAL IGNORED ROWS
            final int ROW_OFFSET = 2;
            final int ignoredRowsSize = ignoredRows.isEmpty() ? 0 : ignoredRows.size();
            final int recordRowNumber = ((RowMetadata) fieldError.getArguments()[0]).getRowNum();

            if (!CollectionUtils.isEmpty(ignoredRows) && recordRowNumber < ignoredRows.get(0)) {
                errorRecords.add(recordList.get(recordRowNumber - ROW_OFFSET));
            } else {
                errorRecords.add(recordList.get(recordRowNumber - (ROW_OFFSET + ignoredRowsSize)));
            }
        }
    }
    recordList.removeAll(errorRecords);
}

From source file:org.springframework.data.rest.webmvc.support.RepositoryConstraintViolationExceptionMessage.java

/**
 * Creates a new {@link RepositoryConstraintViolationExceptionMessage} for the given
 * {@link RepositoryConstraintViolationException} and {@link MessageSourceAccessor}.
 * //from  w  w  w .java 2  s .  c  om
 * @param exception must not be {@literal null}.
 * @param accessor must not be {@literal null}.
 */
public RepositoryConstraintViolationExceptionMessage(RepositoryConstraintViolationException exception,
        MessageSourceAccessor accessor) {

    Assert.notNull(exception, "RepositoryConstraintViolationException must not be null!");
    Assert.notNull(accessor, "MessageSourceAccessor must not be null!");

    for (FieldError fieldError : exception.getErrors().getFieldErrors()) {
        this.errors.add(ValidationError.of(fieldError.getObjectName(), fieldError.getField(),
                fieldError.getRejectedValue(), accessor.getMessage(fieldError)));
    }
}