Example usage for org.springframework.validation FieldError getRejectedValue

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

Introduction

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

Prototype

@Nullable
public Object getRejectedValue() 

Source Link

Document

Return the rejected field value.

Usage

From source file:com.asual.summer.core.ErrorResolver.java

public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception e) {//  w  ww.j  a  va2s.  co m

    if (e instanceof BindException) {

        BindException be = (BindException) e;
        Map<String, Map<String, Object>> errors = new HashMap<String, Map<String, Object>>();

        for (FieldError fe : (List<FieldError>) be.getFieldErrors()) {
            Map<String, Object> error = new HashMap<String, Object>();
            Object[] args = fe.getArguments();
            String key = fe.isBindingFailure() ? fe.getCodes()[2].replaceFirst("typeMismatch", "conversion")
                    : "validation." + fe.getCodes()[2];
            String message = ResourceUtils.getMessage(key, args);
            if (message == null) {
                if (!fe.isBindingFailure()) {
                    if (key.split("\\.").length > 3) {
                        message = ResourceUtils
                                .getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1))
                                        + key.substring(key.lastIndexOf(".")), args);
                    }
                    if (message == null && key.split("\\.").length > 2) {
                        message = ResourceUtils
                                .getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)), args);
                    }
                } else if (fe.isBindingFailure() && key.split("\\.").length > 2) {
                    message = ResourceUtils.getMessage(
                            key.substring(0, key.indexOf(".")) + key.substring(key.lastIndexOf(".")), args);
                } else {
                    message = fe.getDefaultMessage();
                }
            }
            error.put("message", message != null ? message : "Error (" + key + ")");
            error.put("value", fe.getRejectedValue());
            errors.put(fe.getField(), error);
        }

        for (ObjectError oe : (List<ObjectError>) be.getGlobalErrors()) {
            Map<String, Object> error = new HashMap<String, Object>();
            Object[] args = oe.getArguments();
            String key = "global" + (oe.getCodes() != null ? "." + oe.getCodes()[2] : "");
            String message = ResourceUtils.getMessage(key, args);
            if (message == null) {
                if (key.split("\\.").length > 3) {
                    message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1))
                            + key.substring(key.lastIndexOf(".")), args);
                }
                if (message == null && key.split("\\.").length > 2) {
                    message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)),
                            args);
                }
                if (message == null) {
                    message = oe.getDefaultMessage();
                }
            }
            error.put("message", message != null ? message : "Error (" + key + ")");
            error.put("value", oe.getObjectName());
            errors.put(oe.getObjectName(), error);
        }

        String form = (String) RequestUtils.getParameter("_form");
        if (form != null) {
            if (request.getAttribute(ERRORS) == null) {
                request.setAttribute(ERRORS, errors);
                request.setAttribute(be.getObjectName(), be.getTarget());
                return new ModelAndView(new InternalResourceView(
                        form.concat(form.contains("?") ? "&" : "?").concat("_error=true")));
            }
        } else {
            List<String> pairs = new ArrayList<String>();
            for (String key : errors.keySet()) {
                pairs.add(key + "=" + errors.get(key).get("message"));
            }
            try {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, StringUtils.join(pairs, ";"));
            } catch (IOException ioe) {
                logger.error(ioe.getMessage(), ioe);
            }
        }
    }

    return null;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractUsersController.java

private void parseResult(BindingResult result, ModelMap map) {

    if (result.getFieldErrors().size() > 0) {
        List<String> errorMsgList = new ArrayList<String>();
        for (FieldError fieldError : result.getFieldErrors()) {
            String fieldName = fieldError.getField();
            if (fieldName.contains(".")) {
                fieldName = fieldName.substring(fieldName.lastIndexOf(".") + 1);
            }/*from  ww  w. ja va 2s.  c o m*/
            errorMsgList.add(fieldName + " field value '" + fieldError.getRejectedValue() + "' is not valid.");
        }

        map.addAttribute("errorMsgList", errorMsgList);
        map.addAttribute("errormsg", "true");
    }
    if (result.hasGlobalErrors()) {
        List<ObjectError> errorList = result.getGlobalErrors();
        if (errorList.size() > 0) {
            List<String> globalErrors = new ArrayList<String>();
            for (ObjectError error : errorList) {
                globalErrors.add(error.getCode());

            }
            map.addAttribute("globalErrors", globalErrors);
            map.addAttribute("errormsg", "true");
        }

    }
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractTenantController.java

protected void parseResult(BindingResult result, ModelMap map) {
    if (result.getFieldErrors().size() > 0) {
        List<String> errorMsgList = new ArrayList<String>();
        for (FieldError fieldError : result.getFieldErrors()) {
            String fieldName = fieldError.getField();
            if (fieldName.contains(".")) {
                fieldName = fieldName.substring(fieldName.lastIndexOf(".") + 1);
            }//  w ww.  ja v a2  s. co m
            errorMsgList.add(fieldName + " field value '" + fieldError.getRejectedValue() + "' is not valid.");
        }

        map.addAttribute("errorMsgList", errorMsgList);
        map.addAttribute("errormsg", true);
    }
}

From source file:com.octanner.controllers.AbstractProductConfigController.java

private void restoreValidationErrorsInGroup(final Map<String, FieldError> userInputToRestore,
        final BindingResult bindingResult, final UiGroupData group) {
    for (final CsticData latestCstic : group.getCstics()) {
        final UiType uiType = latestCstic.getType();
        final boolean restoreValidationError = latestCstic.isVisible() && uiType != UiType.READ_ONLY
                && userInputToRestore.containsKey(latestCstic.getKey());
        if (restoreValidationError) {
            latestCstic.getConflicts().clear();
            latestCstic.setCsticStatus(CsticStatusType.ERROR);
            final FieldError fieldError = userInputToRestore.get(latestCstic.getKey());
            final String errorValue = fieldError.getRejectedValue().toString();
            if (UiType.DROPDOWN_ADDITIONAL_INPUT == uiType || UiType.RADIO_BUTTON_ADDITIONAL_INPUT == uiType) {
                latestCstic.setAdditionalValue(errorValue);
            } else {
                latestCstic.setValue(errorValue);
            }/*from   w w  w  .  j  a  v  a2 s.c o m*/
            bindingResult.addError(fieldError);
            group.setGroupStatus(GroupStatusType.ERROR);
        }
    }

    final List<UiGroupData> subGroups = group.getSubGroups();
    if (null == subGroups) {
        return;
    }

    for (final UiGroupData subGroup : subGroups) {
        restoreValidationErrorsInGroup(userInputToRestore, bindingResult, subGroup);
    }
}

From source file:de.hybris.platform.acceleratorservices.web.payment.controllers.SilentOrderPostMockController.java

@RequestMapping(value = "/process", method = RequestMethod.POST)
public String doValidateAndPost(@Valid final SopPaymentDetailsForm form, final BindingResult bindingResult,
        final HttpServletRequest request, final Model model) {
    final Map<String, String> params = cloneRequestParameters(request);

    // Remove values that we must not post back to the caller
    params.remove("card_cvNumber");

    getSopPaymentDetailsValidator().validate(form, bindingResult);

    if (bindingResult.hasErrors()) {
        // Validation errors
        params.put("decision", "REJECT");
        params.put("reasonCode", "102");
        params.put("decision_publicSignature", getMockedPublicDigest("REJECT" + "102"));

        // Remove card number on validation error
        params.remove("card_accountNumber");

        final List<String> missingFields = new ArrayList<String>();
        final List<String> invalidFields = new ArrayList<String>();

        for (final ObjectError objectError : bindingResult.getAllErrors()) {
            if (objectError instanceof FieldError) {
                final FieldError fieldError = (FieldError) objectError;

                if (fieldError.getRejectedValue() == null || "".equals(fieldError.getRejectedValue())) {
                    missingFields.add(fieldError.getField());
                } else {
                    invalidFields.add(fieldError.getField());
                }//from  w ww .  jav a 2s. com
            }
        }

        for (int i = 0; i < missingFields.size(); i++) {
            params.put("MissingField" + i, missingFields.get(i));
        }
        for (int i = 0; i < invalidFields.size(); i++) {
            params.put("InvalidField" + i, invalidFields.get(i));
        }
    } else {
        // No validation errors create subscription ID

        final String subscriptionId = UUID.randomUUID().toString();
        params.put("ccAuthReply_cvCode", "M");
        params.put("paySubscriptionCreateReply_subscriptionID", subscriptionId);
        params.put("paySubscriptionCreateReply_subscriptionIDPublicSignature",
                getMockedPublicDigest(subscriptionId));

        processTransactionDecision(request, null, params, false);

        //Mask the card number in the response
        final String endPortion = form.getCard_accountNumber().trim()
                .substring(form.getCard_accountNumber().length() - 4);
        final String maskedCardNumber = "************" + endPortion;

        params.put("card_accountNumber", maskedCardNumber);
    }

    model.addAttribute("postParams", params);
    model.addAttribute("postUrl", params.get("orderPage_receiptResponseURL"));

    return SOP_REDIRECT_POST_PAGE;
}

From source file:de.hybris.platform.sap.productconfig.frontend.controllers.AbstractProductConfigController.java

private void restoreValidationErrorsInGroup(final Map<String, FieldError> userInputToRestore,
        final BindingResult bindingResult, final UiGroupData group) {
    for (final CsticData latestCstic : group.getCstics()) {
        final boolean restoreValidationError = latestCstic.isVisible()
                && latestCstic.getType() != UiType.READ_ONLY
                && userInputToRestore.containsKey(latestCstic.getKey());
        if (restoreValidationError) {
            latestCstic.setCsticStatus(CsticStatusType.ERROR);
            final FieldError fieldError = userInputToRestore.get(latestCstic.getKey());
            latestCstic.setValue(fieldError.getRejectedValue().toString());
            bindingResult.addError(fieldError);
            group.setGroupStatus(GroupStatusType.ERROR);
        }/*from  w w w.jav  a 2s.c om*/
    }

    final List<UiGroupData> subGroups = group.getSubGroups();
    if (null == subGroups) {
        return;
    }

    for (final UiGroupData subGroup : subGroups) {
        restoreValidationErrorsInGroup(userInputToRestore, bindingResult, subGroup);
    }
}

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 w  w w.ja  v  a2  s . co  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.opentestsystem.shared.web.AbstractRestController.java

/**
 * Catch validation exception and return customized error message
 *//*from w w w  .j  a  va2  s .  c o  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);
}