Example usage for org.springframework.validation FieldError getField

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

Introduction

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

Prototype

public String getField() 

Source Link

Document

Return the affected field of the object.

Usage

From source file:org.codehaus.groovy.grails.web.binding.DataBindingUtils.java

/**
 * Binds the given source object to the given target object performing type conversion if necessary
 *
 * @param domain The GrailsDomainClass instance
 * @param object The object to bind to//from  www.  j a v a 2  s . c o  m
 * @param source The source object
 * @param include The list of properties to include
 * @param exclude The list of properties to exclud
 * @param filter The prefix to filter by
 *
 * @see org.codehaus.groovy.grails.commons.GrailsDomainClass
 *
 * @return A BindingResult or null if it wasn't successful
 */
@SuppressWarnings("unchecked")
public static BindingResult bindObjectToDomainInstance(GrailsDomainClass domain, Object object, Object source,
        List include, List exclude, String filter) {
    BindingResult bindingResult = null;
    boolean useSpringBinder = false;
    GrailsApplication grailsApplication = null;
    if (domain != null) {
        grailsApplication = domain.getGrailsApplication();
    }
    if (grailsApplication == null) {
        grailsApplication = GrailsWebRequest.lookupApplication();
    }
    if (grailsApplication != null) {
        if (Boolean.TRUE.equals(grailsApplication.getFlatConfig().get("grails.databinding.useSpringBinder"))) {
            useSpringBinder = true;
        }
    }
    if (!useSpringBinder) {
        try {
            final DataBindingSource bindingSource = createDataBindingSource(grailsApplication,
                    object.getClass(), source);
            final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication);
            grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude);
        } catch (InvalidRequestBodyException e) {
            String messageCode = "invalidRequestBody";
            Class objectType = object.getClass();
            String defaultMessage = "An error occurred parsing the body of the request";
            String[] codes = getMessageCodes(messageCode, objectType);
            bindingResult = new BeanPropertyBindingResult(object, objectType.getName());
            bindingResult.addError(new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage));
        } catch (Exception e) {
            bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName());
            bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage()));
        }
    } else {
        if (source instanceof GrailsParameterMap) {
            GrailsParameterMap parameterMap = (GrailsParameterMap) source;
            HttpServletRequest request = parameterMap.getRequest();
            GrailsDataBinder dataBinder = createDataBinder(object, include, exclude, request);
            dataBinder.bind(parameterMap, filter);
            bindingResult = dataBinder.getBindingResult();
        } else if (source instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) source;
            GrailsDataBinder dataBinder = createDataBinder(object, include, exclude, request);
            performBindFromRequest(dataBinder, request, filter);
            bindingResult = dataBinder.getBindingResult();
        } else if (source instanceof Map) {
            Map propertyMap = convertPotentialGStrings((Map) source);
            GrailsDataBinder binder = createDataBinder(object, include, exclude, null);
            performBindFromPropertyValues(binder, new MutablePropertyValues(propertyMap), filter);
            bindingResult = binder.getBindingResult();
        }

        else {
            GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
            if (webRequest != null) {
                GrailsDataBinder binder = createDataBinder(object, include, exclude,
                        webRequest.getCurrentRequest());
                HttpServletRequest request = webRequest.getCurrentRequest();
                performBindFromRequest(binder, request, filter);
            }
        }
    }

    if (domain != null && bindingResult != null) {
        BindingResult newResult = new ValidationErrors(object);
        for (Object error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                final boolean isBlank = BLANK.equals(fieldError.getRejectedValue());
                if (!isBlank) {
                    newResult.addError(fieldError);
                } else if (domain.hasPersistentProperty(fieldError.getField())) {
                    final boolean isOptional = domain.getPropertyByName(fieldError.getField()).isOptional();
                    if (!isOptional) {
                        newResult.addError(fieldError);
                    }
                } else {
                    newResult.addError(fieldError);
                }
            } else {
                newResult.addError((ObjectError) error);
            }
        }
        bindingResult = newResult;
    }
    MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass());
    if (mc.hasProperty(object, "errors") != null && bindingResult != null) {
        ValidationErrors errors = new ValidationErrors(object);
        errors.addAllErrors(bindingResult);
        mc.setProperty(object, "errors", errors);
    }
    return bindingResult;
}

From source file:org.craftercms.commons.validation.rest.ValidationAwareRestExceptionHandlers.java

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {
    ValidationResult result = new ValidationResult();

    for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
        result.addError(fieldError.getField(),
                ValidationUtils.getErrorMessage(errorMessageBundle, FIELD_MISSING_ERROR_CODE));
    }//from   w ww.jav a 2  s.co  m

    return handleExceptionInternal(ex, result, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}

From source file:org.egov.api.controller.RestEventController.java

@PostMapping(path = "/event/interested", produces = APPLICATION_JSON_VALUE)
public ResponseEntity<String> saveUserEvent(@Valid @RequestBody UserEventRequest userEventRequest,
        BindingResult errors) {//  www .  j  a v  a 2 s  .co  m
    ApiResponse res = ApiResponse.newInstance();

    if (errors.hasErrors()) {
        String errorMessage = EMPTY;
        for (FieldError fieldError : errors.getFieldErrors())
            errorMessage = errorMessage.concat(
                    fieldError.getField().concat(" ").concat(fieldError.getDefaultMessage()).concat(" <br>"));
        return res.error(errorMessage);
    }

    UserEvent userEvent = userEventService.saveUserEvent(userEventRequest.getUserid(),
            userEventRequest.getEventid());
    if (userEvent == null)
        return res.error(getMessage("user.event.already.exists"));
    else {
        Long interestedCount = userEventService.countUsereventByEventId(userEvent.getEvent().getId());
        return res.setDataAdapter(new InterestedCountAdapter()).success(interestedCount);
    }
}

From source file:org.egov.api.controller.RestPushBoxController.java

@PostMapping(path = UPDATE_USER_TOKEN, consumes = APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<String> updateToken(@Valid @RequestBody UserTokenRequest userTokenRequest,
        BindingResult errors) {/*from   w ww. j  a  va2s. c o  m*/
    ApiResponse res = ApiResponse.newInstance();

    if (errors.hasErrors()) {
        String errorMessage = EMPTY;
        for (FieldError fieldError : errors.getFieldErrors())
            errorMessage = errorMessage.concat(
                    fieldError.getField().concat(" ").concat(fieldError.getDefaultMessage()).concat(" <br>"));
        return res.error(errorMessage);
    }

    UserFcmDevice responseObject = notificationService.saveUserDevice(userTokenRequest);
    return res.setDataAdapter(new UserDeviceAdapter()).success(responseObject,
            getMessage("msg.userdevice.update.success"));
}

From source file:org.hoteia.qalingo.core.web.mvc.controller.AbstractQalingoController.java

protected void addMessageError(BindingResult result, Exception e, String formKey, String fieldKey,
        String errorMessage) {/*from  w w w .j a v a  2s .c o  m*/
    if (StringUtils.isEmpty(errorMessage)) {
        errorMessage = ""; // EMPTY VALUE TO EVENT VELOCITY MethodInvocationException
    }
    FieldError error = new FieldError(formKey, fieldKey, errorMessage);
    result.addError(error);
    result.rejectValue(error.getField(), "");
    if (e != null) {
        logger.error(errorMessage, e);
    } else {
        logger.warn(errorMessage);
    }
}

From source file:org.jasig.ssp.transferobject.ServiceResponse.java

/**
 * Extract the Validation messages out of the
 * MethodArgumentNotValidException, and use as the ServiceResponse Message.
 * // ww w  .j  a v a  2  s .  c  om
 * @param success
 *            If the response should indicate success or not
 * @param e
 *            Error messages to show
 */
public ServiceResponse(final boolean success, final MethodArgumentNotValidException e) {
    this.success = success;

    // collect the error messages
    final List<String> errorMessages = Lists.newArrayList();
    for (final ObjectError error : e.getBindingResult().getAllErrors()) {
        final StringBuilder sb = new StringBuilder(); // NOPMD

        // get the field name if it is a field error.
        if (error instanceof FieldError) {
            final FieldError fe = (FieldError) error;
            sb.append("[").append(fe.getField());
        } else {
            sb.append("[");
        }

        // get the default message
        sb.append(" ").append(error.getDefaultMessage()).append("] ");
        // add it to the list of error messages
        errorMessages.add(sb.toString());
    }

    // sort the messages for readablility
    Collections.sort(errorMessages);

    // introduce the error messages
    final int errorCount = e.getBindingResult().getErrorCount();
    final StringBuilder sb = new StringBuilder("Validation failed for argument ")
            .append(e.getParameter().getParameterName()).append(", with ").append(errorCount)
            .append(errorCount > 1 ? " errors: " : " error: ");

    // append the sorted error messages to the introduction and set as the
    // service response message.
    sb.append(StringUtils.join(errorMessages, ","));

    message = sb.toString();
}

From source file:org.mifos.clientportfolio.loan.ui.LoanAccountFormBean.java

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = {
        "SIC_INNER_SHOULD_BE_STATIC_ANON" }, justification = "")
public void validateEnterAccountDetailsStep(ValidationContext context) {
    MessageContext messageContext = context.getMessageContext();

    Errors errors = validator.checkConstraints(this);

    // handle data binding errors that may of occurred
    if (messageContext.hasErrorMessages()) {
        Message[] errorMessages = messageContext.getMessagesByCriteria(new MessageCriteria() {

            @Override/*from  ww w  .  j  a  va  2s.  c  om*/
            public boolean test(@SuppressWarnings("unused") Message message) {
                return true;
            }
        });
        messageContext.clearMessages();

        for (Message message : errorMessages) {
            handleDataMappingError(errors, message);
        }
    }

    if (this.glimApplicable) {
        int index = 0;
        int selectedCount = 0;
        for (Boolean clientSelected : this.clientSelectForGroup) {
            if (clientSelected != null && clientSelected.booleanValue()) {

                Number clientAmount = this.clientAmount[index];

                if (clientAmount == null
                        || exceedsMinOrMax(clientAmount, Integer.valueOf(1), this.maxAllowedAmount)) {
                    String defaultErrorMessage = "Please specify valid Amount.";
                    rejectGlimClientAmountField(index + 1, errors, defaultErrorMessage);
                }

                if (clientAmount != null) {
                    BigDecimal amountAsDecimal = new BigDecimal(clientAmount.toString()).stripTrailingZeros();
                    int places = amountAsDecimal.scale();
                    if (places > this.digitsAfterDecimalForMonetaryAmounts) {
                        String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number.";
                        rejectInterestRateFieldValue(errors, defaultErrorMessage,
                                "loanAccountFormBean.client.amount.digitsAfterDecimal.invalid",
                                new Object[] { index + 1, this.digitsAfterDecimalForMonetaryAmounts });
                    }

                    int digitsBefore = amountAsDecimal.toBigInteger().toString().length();
                    if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) {
                        String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number.";
                        rejectInterestRateFieldValue(errors, defaultErrorMessage,
                                "loanAccountFormBean.client.amount.digitsBeforeDecimal.invalid",
                                new Object[] { index + 1, this.digitsBeforeDecimalForMonetaryAmounts });
                    }
                }

                // check error message of loan purpose for each client when its mandatory..
                Integer clientLoanPurposeId = this.clientLoanPurposeId[index];
                if (this.purposeOfLoanMandatory && isInvalidSelection(clientLoanPurposeId)) {
                    errors.rejectValue("clientLoanPurposeId", "loanAccountFormBean.glim.purposeOfLoan.invalid",
                            new Object[] { index + 1 }, "Please specify loan purpose.");
                    this.clientLoanPurposeId[index] = 0;
                } else {
                    // needed so attempt in freemarker(ftl) to display loan purpose doesnt fall over.
                    if (clientLoanPurposeId == null) {
                        this.clientLoanPurposeId[index] = 0;
                    }
                }

                selectedCount++;
            } else {

                Number clientAmount = this.clientAmount[index];
                Integer clientLoanPurposeId = this.clientLoanPurposeId[index];
                if (clientAmount != null || clientLoanPurposeId != null) {
                    String defaultErrorMessage = "You have entered details for a member you have not selected. Select the checkbox in front of the member's name in order to include him or her in the loan.";
                    rejectUnselectedGlimClientAmountField(index + 1, errors, defaultErrorMessage);
                }
            }

            index++;
        }

        if (selectedCount < 2) {
            String defaultErrorMessage = "Not enough clients for group loan.";
            rejectGroupLoanWithTooFewClients(errors, defaultErrorMessage);
        }
    }

    if (this.amount == null || exceedsMinOrMax(this.amount, this.minAllowedAmount, this.maxAllowedAmount)) {
        String defaultErrorMessage = "Please specify valid Amount.";
        if (glimApplicable) {
            defaultErrorMessage = "The sum of the amounts specified for each member is outside the allowable total amount for this loan product.";
            rejectGlimTotalAmountField(errors, defaultErrorMessage);
        } else {
            rejectAmountField(errors, defaultErrorMessage);
        }
    }

    if (this.amount != null) {
        BigDecimal amountAsDecimal = new BigDecimal(this.amount.toString()).stripTrailingZeros();
        int places = amountAsDecimal.scale();
        if (places > this.digitsAfterDecimalForMonetaryAmounts) {
            String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number.";
            rejectInterestRateFieldValue(errors, defaultErrorMessage,
                    "loanAccountFormBean.amount.digitsAfterDecimal.invalid",
                    new Object[] { this.digitsAfterDecimalForMonetaryAmounts });
        }

        int digitsBefore = amountAsDecimal.toBigInteger().toString().length();
        if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) {
            String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number.";
            rejectInterestRateFieldValue(errors, defaultErrorMessage,
                    "loanAccountFormBean.amount.digitsBeforeDecimal.invalid",
                    new Object[] { this.digitsBeforeDecimalForMonetaryAmounts });
        }
    }

    if (this.interestRate == null
            || exceedsMinOrMax(this.interestRate, this.minAllowedInterestRate, this.maxAllowedInterestRate)) {
        String defaultErrorMessage = "Please specify valid Interest rate.";
        rejectInterestRateField(errors, defaultErrorMessage);
    }

    if (this.interestRate != null) {
        BigDecimal interestRateAsDecimal = new BigDecimal(this.interestRate.toString()).stripTrailingZeros();
        int places = interestRateAsDecimal.scale();
        if (places > this.digitsAfterDecimalForInterest) {
            String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number.";
            rejectInterestRateFieldValue(errors, defaultErrorMessage,
                    "loanAccountFormBean.digitsAfterDecimalForInterest.invalid",
                    new Object[] { this.digitsAfterDecimalForInterest });
        }

        int digitsBefore = interestRateAsDecimal.toBigInteger().toString().length();
        if (digitsBefore > this.digitsBeforeDecimalForInterest) {
            String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number.";
            rejectInterestRateFieldValue(errors, defaultErrorMessage,
                    "loanAccountFormBean.digitsBeforeDecimalForInterest.invalid",
                    new Object[] { this.digitsBeforeDecimalForInterest });
        }
    }

    if (this.numberOfInstallments == null || exceedsMinOrMax(this.numberOfInstallments,
            this.minNumberOfInstallments, this.maxNumberOfInstallments)) {
        String defaultErrorMessage = "Please specify valid number of installments.";
        rejectNumberOfInstallmentsField(errors, defaultErrorMessage);
    }

    if (this.graceDuration == null || this.graceDuration.intValue() < 0) {
        if (!errors.hasFieldErrors("graceDuration")) {
            String defaultErrorMessage = "Please specify valid Grace period for repayments. Grace period should be a value less than "
                    + numberOfInstallments.intValue() + ".";
            rejectGraceDurationField(errors, defaultErrorMessage);
        }
    } else {
        if (this.graceDuration.intValue() > this.maxGraceDuration.intValue()) {
            String defaultErrorMessage = "The Grace period cannot be greater than in loan product definition.";
            errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDuration.invalid",
                    defaultErrorMessage);
        }

        if (this.numberOfInstallments != null
                && (this.graceDuration.intValue() >= this.numberOfInstallments.intValue())) {
            String defaultErrorMessage = "Grace period for repayments must be less than number of loan installments.";
            errors.rejectValue("graceDuration",
                    "loanAccountFormBean.gracePeriodDurationInRelationToInstallments.invalid",
                    defaultErrorMessage);
        }
    }

    if (dateValidator == null) {
        dateValidator = new DateValidator();
    }
    if (!dateValidator.formsValidDate(this.disbursementDateDD, this.disbursementDateMM,
            this.disbursementDateYY)) {
        String defaultErrorMessage = "Please specify valid disbursal date.";
        rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD",
                "loanAccountFormBean.DisbursalDate.invalid", "");
    } else {
        LocalDate validDate = new DateTime().withDate(disbursementDateYY.intValue(),
                disbursementDateMM.intValue(), disbursementDateDD.intValue()).toLocalDate();

        org.mifos.platform.validations.Errors disbursementDateErrors = new org.mifos.platform.validations.Errors();
        if (this.redoLoanAccount) {
            disbursementDateErrors = loanDisbursementDateValidationServiceFacade
                    .validateLoanWithBackdatedPaymentsDisbursementDate(validDate, customerId, productId);
        } else {
            disbursementDateErrors = loanDisbursementDateValidationServiceFacade
                    .validateLoanDisbursementDate(validDate, customerId, productId);
        }
        for (ErrorEntry entry : disbursementDateErrors.getErrorEntries()) {
            String defaultErrorMessage = "The disbursal date is invalid.";
            rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", entry.getErrorCode(),
                    entry.getArgs().get(0));
        }
    }

    if (this.sourceOfFundsMandatory && isInvalidSelection(this.fundId)) {
        errors.rejectValue("fundId", "loanAccountFormBean.SourceOfFunds.invalid",
                "Please specify source of funds.");
    }

    if (this.externalIdMandatory && StringUtils.isBlank(this.externalId)) {
        errors.rejectValue("externalId", "loanAccountFormBean.externalid.invalid",
                "Please specify required external id.");
    }

    if (!this.glimApplicable && this.purposeOfLoanMandatory && isInvalidSelection(this.loanPurposeId)) {
        errors.rejectValue("loanPurposeId", "loanAccountFormBean.PurposeOfLoan.invalid",
                "Please specify loan purpose.");
    }

    validateAdministrativeAndAdditionalFees(errors);

    if (this.repaymentScheduleIndependentOfCustomerMeeting) {
        if (isInvalidRecurringFrequency(this.repaymentRecursEvery)) {
            errors.rejectValue("repaymentRecursEvery", "loanAccountFormBean.repaymentDay.recursEvery.invalid",
                    "Please specify a valid recurring frequency for repayment day.");
        }
        if (this.weekly) {
            if (isInvalidDayOfWeekSelection()) {
                errors.rejectValue("repaymentDayOfWeek",
                        "loanAccountFormBean.repaymentDay.weekly.dayOfWeek.invalid",
                        "Please select a day of the week for repayment day.");
            }
        } else if (this.monthly) {
            if (this.monthlyDayOfMonthOptionSelected) {
                if (isInvalidDayOfMonthEntered()) {
                    errors.rejectValue("repaymentDayOfMonth",
                            "loanAccountFormBean.repaymentDay.monthly.dayOfMonth.invalid",
                            "Please select a day of the month for repayment day.");
                }
            } else if (this.monthlyWeekOfMonthOptionSelected) {
                if (isInvalidWeekOfMonthSelection()) {
                    errors.rejectValue("repaymentWeekOfMonth",
                            "loanAccountFormBean.repaymentDay.monthly.weekOfMonth.invalid",
                            "Please select a week of the month for repayment day.");
                }
                if (isInvalidDayOfWeekSelection()) {
                    errors.rejectValue("repaymentDayOfWeek",
                            "loanAccountFormBean.repaymentDay.monthly.dayOfWeek.invalid",
                            "Please select a day of the week for repayment day.");
                }
            }
        }

        if (this.variableInstallmentsAllowed) {
            if (this.selectedFeeId != null) {
                for (Number feeId : this.selectedFeeId) {
                    if (feeId != null) {
                        VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade
                                .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue());
                        if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) {
                            errors.rejectValue("selectedFeeId",
                                    "loanAccountFormBean.additionalfees.variableinstallments.invalid",
                                    new String[] { result.getFeeName() },
                                    "This type of fee cannot be applied to loan with variable installments.");
                        }
                    }
                }
            }

            int defaultFeeIndex = 0;
            if (this.defaultFeeId != null) {
                for (Number feeId : this.defaultFeeId) {
                    if (feeId != null) {
                        Boolean feeSelectedForRemoval = this.defaultFeeSelected[defaultFeeIndex];
                        if (feeSelectedForRemoval == null || !feeSelectedForRemoval) {
                            VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade
                                    .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue());
                            if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) {
                                errors.rejectValue("selectedFeeId",
                                        "loanAccountFormBean.defaultfees.variableinstallments.invalid",
                                        new String[] { result.getFeeName() },
                                        "This type of fee cannot be applied to loan with variable installments.");
                            }
                        }
                    }
                    defaultFeeIndex++;
                }
            }
        }
    }

    if (errors.hasErrors()) {
        for (FieldError fieldError : errors.getFieldErrors()) {
            MessageBuilder builder = new MessageBuilder().error().source(fieldError.getField())
                    .codes(fieldError.getCodes()).defaultText(fieldError.getDefaultMessage())
                    .args(fieldError.getArguments());

            messageContext.addMessage(builder.build());
        }
    }
}

From source file:org.opentestsystem.shared.web.AbstractRestController.java

/**
 * Catch validation exception and return customized error message
 *//*  w w  w  .ja  va  2 s  .  co  m*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public ResponseError handleMethodArgumentNotValidException(final MethodArgumentNotValidException except) {
    final List<FieldError> errors = except.getBindingResult().getFieldErrors();
    final Map<String, List<String>> errorsByField = new TreeMap<String, List<String>>();
    for (final FieldError error : errors) {
        if (errorsByField.get(error.getField()) == null) {
            errorsByField.put(error.getField(), new ArrayList<String>());
        }
        final List<String> messageList = errorsByField.get(error.getField());
        String rejectedValue = "";
        if (error.getRejectedValue() == null) {
            rejectedValue = "null";
        } else {
            rejectedValue = error.getRejectedValue().toString();
        }
        final List<String> args = Lists.newArrayList(error.getField(), rejectedValue);
        if (error.getArguments() != null) {
            final Iterable<String> argsToAdd = Iterables.transform(Arrays.asList(error.getArguments()),
                    TO_STRING_FUNCTION);
            args.addAll(Lists.newArrayList(argsToAdd));
        }
        messageList.add(getLocalizedMessage(error.getDefaultMessage(), args.toArray(new String[args.size()])));
    }

    // sort error messages
    for (final Map.Entry<String, List<String>> entry : errorsByField.entrySet()) {
        Collections.sort(entry.getValue());
    }

    return new ResponseError(errorsByField);
}

From source file:org.sparkcommerce.openadmin.web.processor.ErrorsProcessor.java

@Override
protected ProcessorResult processAttribute(Arguments arguments, Element element, String attributeName) {
    String attributeValue = element.getAttributeValue(attributeName);

    BindStatus bindStatus = FieldUtils.getBindStatus(arguments.getConfiguration(), arguments, attributeValue);

    if (bindStatus.isError()) {
        EntityForm form = (EntityForm) ((BindingResult) bindStatus.getErrors()).getTarget();

        // Map of tab name -> (Map field Name -> list of error messages)
        Map<String, Map<String, List<String>>> result = new HashMap<String, Map<String, List<String>>>();
        for (FieldError err : bindStatus.getErrors().getFieldErrors()) {
            //attempt to look up which tab the field error is on. If it can't be found, just use
            //the default tab for the group
            String tabName = EntityForm.DEFAULT_TAB_NAME;
            Tab tab = form.findTabForField(err.getField());
            if (tab != null) {
                tabName = tab.getTitle();
            }/* w w w  .  ja v  a2 s . co  m*/

            Map<String, List<String>> tabErrors = result.get(tabName);
            if (tabErrors == null) {
                tabErrors = new HashMap<String, List<String>>();
                result.put(tabName, tabErrors);
            }
            if (err.getField().contains(DynamicEntityFormInfo.FIELD_SEPARATOR)) {
                //at this point the field name actually occurs within some array syntax
                String fieldName = err.getField().substring(err.getField().indexOf('[') + 1,
                        err.getField().lastIndexOf(']'));
                String[] fieldInfo = fieldName.split("\\" + DynamicEntityFormInfo.FIELD_SEPARATOR);
                Field formField = form.getDynamicForm(fieldInfo[0]).getFields().get(fieldName);

                if (formField != null) {
                    addFieldError(formField.getFriendlyName(), err.getCode(), tabErrors);
                } else {
                    LOG.warn("Could not find field " + fieldName + " within the dynamic form " + fieldInfo[0]);
                    addFieldError(fieldName, err.getCode(), tabErrors);
                }
            } else {
                Field formField = form.findField(err.getField());
                if (formField != null) {
                    addFieldError(formField.getFriendlyName(), err.getCode(), tabErrors);
                } else {
                    LOG.warn("Could not field field " + err.getField() + " within the main form");
                    addFieldError(err.getField(), err.getCode(), tabErrors);
                }
            }
        }

        for (ObjectError err : bindStatus.getErrors().getGlobalErrors()) {
            Map<String, List<String>> tabErrors = result.get(GENERAL_ERRORS_TAB_KEY);
            if (tabErrors == null) {
                tabErrors = new HashMap<String, List<String>>();
                result.put(GENERAL_ERRORS_TAB_KEY, tabErrors);
            }
            addFieldError(GENERAL_ERROR_FIELD_KEY, err.getCode(), tabErrors);
        }

        Map<String, Object> localVariables = new HashMap<String, Object>();
        localVariables.put("tabErrors", result);
        return ProcessorResult.setLocalVariables(localVariables);
    }
    return ProcessorResult.OK;

}

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

/**
 * Creates a new {@link RepositoryConstraintViolationExceptionMessage} for the given
 * {@link RepositoryConstraintViolationException} and {@link MessageSourceAccessor}.
 * // ww  w  . j  a va  2s.  c  o m
 * @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)));
    }
}