Example usage for org.springframework.validation FieldError FieldError

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

Introduction

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

Prototype

public FieldError(String objectName, String field, @Nullable Object rejectedValue, boolean bindingFailure,
        @Nullable String[] codes, @Nullable Object[] arguments, @Nullable String defaultMessage) 

Source Link

Document

Create a new FieldError instance.

Usage

From source file:com.company.simple.util.validator.GlobeValidator.java

protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors) {
    for (ConstraintViolation<Object> violation : violations) {
        String field = violation.getPropertyPath().toString();
        FieldError fieldError = errors.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
                String errorCode = cd.getAnnotation().annotationType().getSimpleName();
                Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd);
                if (errors instanceof BindingResult) {
                    // Can do custom FieldError registration with invalid value from ConstraintViolation,
                    // as necessary for Hibernate Validator compatibility (non-indexed set path in field)
                    BindingResult bindingResult = (BindingResult) errors;
                    String nestedField = bindingResult.getNestedPath() + field;
                    if ("".equals(nestedField)) {
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode);
                        bindingResult.addError(new ObjectError(errors.getObjectName(), errorCodes, errorArgs,
                                violation.getMessage()));
                    } else {
                        Object invalidValue = violation.getInvalidValue();
                        if (!"".equals(field) && (invalidValue == violation.getLeafBean()
                                || (field.contains(".") && !field.contains("[]")))) {
                            // Possibly a bean constraint with property path: retrieve the actual property value.
                            // However, explicitly avoid this for "address[]" style paths that we can't handle.
                            invalidValue = bindingResult.getRawFieldValue(field);
                        }//ww w  .  ja  va  2s.  c o  m
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field);
                        bindingResult.addError(new FieldError(errors.getObjectName(), nestedField, invalidValue,
                                false, errorCodes, errorArgs, violation.getMessage()));
                    }
                } else {
                    // got no BindingResult - can only do standard rejectValue call
                    // with automatic extraction of the current field value
                    errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
                }
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field
                        + "' does not have a corresponding accessor for Spring data binding - "
                        + "check your DataBinder's configuration (bean property versus direct field access)",
                        ex);
            }
        }
    }
}

From source file:com.oak_yoga_studio.controller.CustomerController.java

@RequestMapping(value = "/addCredential", method = RequestMethod.POST)
public String addCredential(@Valid Credential credential, BindingResult result, HttpSession session) {
    String view = "redirect:/addCustomer";
    //dumb fix/*  ww w . ja  va2 s  .  c om*/
    boolean used = customerService.checkUserName(credential.getUserName());
    if (used) {
        FieldError f = new FieldError("credential", "userName", credential.getUserName(), false, null, null,
                "Username : " + credential.getUserName() + " already in use");
        result.addError(f);
    }
    if (!result.hasErrors()) {
        Customer c = (Customer) session.getAttribute("loggedUser");
        credential.setRole("ROLE_CUSTOMER");
        credential.setActive(true);
        session.setAttribute("credential", credential);

    } else {
        view = "addCredential";
    }
    return view;
}

From source file:cs544.wamp_blog_engine.controller.UserController.java

@RequestMapping(value = "/addCredential", method = RequestMethod.POST)
public String addCredential(@Valid Credential credential, BindingResult result, HttpSession session) {
    String view = "redirect:/addUser";
    //dumb fix// ww  w  .  ja  v a2 s. c  o  m
    boolean used = userService.checkUserName(credential.getUsername());
    if (used) {
        FieldError f = new FieldError("credential", "username", credential.getUsername(), false, null, null,
                "Username : " + credential.getUsername() + " already in use");
        result.addError(f);
    }
    if (!result.hasErrors()) {
        User u = (User) session.getAttribute("loggedUser");
        if (u != null && u.getUserCredential().isAdmin()) {
            credential.setPreviledge("ROLE_ADMIN");
        } else {
            credential.setPreviledge("ROLE_BLOGGER");
        }
        credential.setBlocked(false);
        session.setAttribute("credential", credential);
    } else {
        view = "addCredential";
    }
    return view;
}

From source file:com.laxser.blitz.web.paramresolver.MethodParameterResolver.java

public Object[] resolve(final Invocation inv, final ParameterBindingResult parameterBindingResult)
        throws Exception {
    Object[] parameters = new Object[paramMetaDatas.length];
    for (int i = 0; i < resolvers.length; i++) {
        if (resolvers[i] == null) {
            continue;
        }//w w  w.  j av a2  s  .  co  m
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Resolves parameter " + paramMetaDatas[i].getParamType().getSimpleName()
                        + " using " + resolvers[i].getClass().getName());
            }
            parameters[i] = resolvers[i].resolve(inv, paramMetaDatas[i]);
            // afterPropertiesSet
            if (parameters[i] instanceof InitializingBean) {
                ((InitializingBean) parameters[i]).afterPropertiesSet();
            }
        } catch (TypeMismatchException e) {
            // ???bean???

            logger.debug("", e);

            // ???
            if (paramMetaDatas[i].getParamType().isPrimitive()) {
                DefValue defValudeAnnotation = paramMetaDatas[i].getAnnotation(DefValue.class);
                if (defValudeAnnotation == null
                        || DefValue.NATIVE_DEFAULT.equals(defValudeAnnotation.value())) {
                    // ?if-else?converter???
                    if (paramMetaDatas[i].getParamType() == int.class) {
                        parameters[i] = Integer.valueOf(0);
                    } else if (paramMetaDatas[i].getParamType() == long.class) {
                        parameters[i] = Long.valueOf(0);
                    } else if (paramMetaDatas[i].getParamType() == boolean.class) {
                        parameters[i] = Boolean.FALSE;
                    } else if (paramMetaDatas[i].getParamType() == double.class) {
                        parameters[i] = Double.valueOf(0);
                    } else if (paramMetaDatas[i].getParamType() == float.class) {
                        parameters[i] = Float.valueOf(0);
                    } else {
                        TypeConverter typeConverter = SafedTypeConverterFactory.getCurrentConverter();
                        parameters[i] = typeConverter.convertIfNecessary("0", paramMetaDatas[i].getParamType());
                    }
                } else {
                    TypeConverter typeConverter = SafedTypeConverterFactory.getCurrentConverter();
                    parameters[i] = typeConverter.convertIfNecessary(defValudeAnnotation.value(),
                            paramMetaDatas[i].getParamType());
                }
            }
            // 
            String paramName = parameterNames[i];
            if (paramName == null) {
                for (String name : paramMetaDatas[i].getParamNames()) {
                    if ((paramName = name) != null) {
                        break;
                    }
                }
            }
            Assert.isTrue(paramName != null);
            FieldError fieldError = new FieldError(//
                    "method", // ????method
                    paramName, // ??????
                    inv.getParameter(paramName), // ?
                    true, //whether this error represents a binding failure (like a type mismatch); else, it is a validation failure
                    new String[] { e.getErrorCode() }, // "typeMismatch"
                    new String[] { inv.getParameter(paramName) }, //the array of arguments to be used to resolve this message
                    null // the default message to be used to resolve this message
            );
            parameterBindingResult.addError(fieldError);
        } catch (Exception e) {
            // ????
            logger.error("", e);
            throw e;
        }
    }
    return parameters;
}

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

/**
 * @param form/*  ww  w . j  a v a 2  s. c o m*/
 * @param result
 * @param map
 * @param status
 * @return
 */
@RequestMapping(value = { "/{userParam}/myprofile" }, method = RequestMethod.POST)
public String edit(@PathVariable String userParam, @Valid @ModelAttribute("user") UserForm form,
        BindingResult result, HttpServletRequest request, ModelMap map, SessionStatus status) {
    logger.debug("###Entering in edit(form,result,map,status) method @POST");
    com.citrix.cpbm.access.User user = form.getUser();

    MyProfileValidator validator = new MyProfileValidator();
    validator.validate(form, result);
    if (result.hasErrors()
            && !(result.getErrorCount() == 1 && result.getAllErrors().get(0).getCode().equals("Size")
                    && form.getUser().getUsername().equals("root"))) {
        displayErrors(result);
        // TODO to return the edit page with errors
        return "redirect:/portal/users/" + userParam + "/myprofile";
    }
    User logedInUser = this.getCurrentUser();
    if (isEmailBlacklisted(user.getEmail().toLowerCase())) {
        logger.info("Email Id : " + form.getUser().getEmail()
                + " rejected because it is not on the whitelist or part of the blacklist. Kindly contact support");
        result.rejectValue("user.email", "signup.emaildomain.blacklist.error");
        return edit(null, user.getObject().getUuid(), request, map);
    }
    if (form.getClearPassword() != null && !form.getClearPassword().isEmpty()) { // password reset
        if (form.getOldPassword() == null) {
            result.addError(new FieldError(result.getObjectName(), "oldPassword", null, false,
                    new String[] { "errors.password.required" }, null, null));
        } else if (!user.getObject().authenticate(form.getOldPassword())) {
            result.addError(new FieldError(result.getObjectName(), "oldPassword", null, false,
                    new String[] { "errors.password.invalid" }, null, null));
        } else {
            user.getObject().setClearPassword(form.getClearPassword());
        }
    }
    com.citrix.cpbm.access.User userClone = form.getUserClone();
    // TODO need to do Validation(Once fix this then remove @Ignore annotation against testUpdateUserFail from Test
    // Suit.
    form.setPhone(form.getPhone().replaceAll(PHONE_NUMBER_REGEX, "")); // removing all characters from phone number
    String oldPhone = userClone.getPhoneWithoutIsdCode() != null ? userClone.getPhoneWithoutIsdCode() : "";
    boolean phoneVerificationEnabled = false;
    if (!form.getPhone().equals(oldPhone.replaceAll(PHONE_NUMBER_REGEX, ""))
            || !form.getCountryCode().toString().equals(user.getCountryCode())) {

        if (connectorManagementService.getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION) != null
                && ((TelephoneVerificationService) connectorManagementService
                        .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION)).isEnabled()) {
            phoneVerificationEnabled = true;
        }

        if (phoneVerificationEnabled && !userService.hasAuthority(logedInUser, "ROLE_ACCOUNT_CRUD")) {
            String generatedPhoneVerificationPin = (String) request.getSession()
                    .getAttribute("phoneVerificationPin");
            String actualPhoneNumber = (String) request.getSession().getAttribute("phoneNumber");
            if (form.getUserEnteredPhoneVerificationPin() == null
                    || !form.getUserEnteredPhoneVerificationPin().equals(generatedPhoneVerificationPin)
                    || !areDigitsInPhoneNosEqual(form.getPhone(), actualPhoneNumber)) {
                map.addAttribute("userEditError", "phoneVerfication.error");
                result.rejectValue("phone", "phoneVerfication.error");
                parseResult(result, map);
                return edit(null, user.getObject().getUuid(), request, map);
            }
        }
    }
    String phoneNo = form.getCountryCode().replaceAll(PHONE_NUMBER_REGEX, "")
            + COUNTRY_CODE_TO_PHONE_NUMBER_SEPERATOR + form.getPhone().replaceAll(PHONE_NUMBER_REGEX, "");
    // Set the phone number
    if (!phoneVerificationEnabled && StringUtils.isEmpty(form.getPhone())) {
        user.setPhone(null);
    } else {
        user.setPhone(phoneNo);
    }

    if ((user.getObject().getTenant().getState() == State.ACTIVE
            || user.getObject().getTenant().getState() == State.LOCKED
            || user.getObject().getTenant().getState() == State.SUSPENDED)
            && !user.getEmail().equals(userClone.getEmail())) {
        userAlertPreferencesService.createUserAlertPreference(user.getObject(), user.getEmail(),
                AlertType.USER_EMAIL);
        // set email so that it wont be updated in users table and other places
        user.setEmail(userClone.getEmail());
        user.setEmailVerified(true);
    }
    userService.update(user, result);
    form.setUser(user);
    map.addAttribute("user", form);
    setPage(map, Page.USER_PERSONAL_PROFILE);
    status.setComplete();
    logger.debug("###Exiting edit(form,result,map,status) method @POST");
    map.clear();
    return "redirect:/portal/users/" + user.getObject().getParam() + "/myprofile";
}

From source file:gr.abiss.calipso.userDetails.controller.ProviderSignInController.java

private void addFieldError(String objectName, String fieldName, String fieldValue, String errorCode,
        BindingResult result) {//from  w  w  w  .ja  va2 s  .  c  om
    LOGGER.debug("Adding field error object's: {} field: {}", objectName, fieldName);
    FieldError error = new FieldError(objectName, fieldName, fieldValue, false, new String[] { errorCode },
            new Object[] {}, errorCode);

    result.addError(error);
    LOGGER.debug("Added field error: {} to binding result: {}", error, result);
}

From source file:org.broadleafcommerce.openadmin.web.form.entity.EntityFormValidator.java

/**
 * Validates the form DTO against the passed in map of propertyErrors along with global validation errors.
 * /*from   w w w .  j  av  a2  s  . c om*/
 * @see #validate(EntityForm, Entity, Errors)
 * @param form
 * @param propertyErrors
 * @param globalErrors
 * @param errors
 * @return
 */
public boolean validate(EntityForm form, Map<String, List<String>> propertyErrors, List<String> globalErrors,
        Errors errors) {
    if (MapUtils.isEmpty(propertyErrors) && CollectionUtils.isEmpty(globalErrors)) {
        return true;
    }

    if (MapUtils.isNotEmpty(propertyErrors)) {
        for (Map.Entry<String, List<String>> pe : propertyErrors.entrySet()) {
            for (String errorMessage : pe.getValue()) {
                String unserializedFieldName = pe.getKey();
                String serializedFieldName = JSCompatibilityHelper.encode(unserializedFieldName);

                /**
                 * Rather than just use errors.rejectValue directly, we need to instantiate the FieldError object ourself
                 * and add it to the binding result. This is so that we can resolve the actual rejected value ourselves
                 * rather than rely on Spring to do it for us. If we rely on Spring, Spring will attempt to resolve something
                 * like fields['defaultSku__name'] immediately (at the time of invoking errors.rejectValue). At that point,
                 * the field names within the EntityForm are still in their unserialized state, and thus Spring would only
                 * find fields['defaultSku.name'] and there would be an empty string for the rejected value. Then on the
                 * frontend, Thymeleaf's th:field processor relies on Spring's BindingResult to provide the value that
                 * was actually rejected so you can get blank form fields.
                 * 
                 * With this implementation, we avoid all of those additional problems because we are referencing the
                 * field that is being rejected along with providing our own method for getting the rejected value
                 */
                Field field = null;
                if (StringUtils.contains(unserializedFieldName, DynamicEntityFormInfo.FIELD_SEPARATOR)) {
                    String[] fieldInfo = unserializedFieldName
                            .split("\\" + DynamicEntityFormInfo.FIELD_SEPARATOR);
                    field = form.getDynamicForm(fieldInfo[0]).getFields().get(fieldInfo[1]);
                } else if (form.getFields().get(unserializedFieldName) != null) {
                    field = form.getFields().get(unserializedFieldName);
                }

                //If the submitted field was a radio button but has validation associated with it, that radio field
                //will have never been submitted in the POST and thus will not have ever been attached to the EntityForm.
                //We still want to notate the fact that there was a validation failure on that field
                String value = (field != null) ? field.getValue() : null;

                String[] errorCodes = ((AbstractBindingResult) errors).resolveMessageCodes(errorMessage,
                        serializedFieldName);
                FieldError fieldError = new FieldError("entityForm",
                        String.format("fields[%s].value", serializedFieldName), value, false, errorCodes, null,
                        errorMessage);
                ((AbstractBindingResult) errors).addError(fieldError);
            }
        }
    }

    if (CollectionUtils.isNotEmpty(globalErrors)) {
        for (String errorMessage : globalErrors) {
            errors.reject(errorMessage, errorMessage);
        }
    }

    return false;
}

From source file:org.codehaus.groovy.grails.validation.AbstractConstraint.java

public void rejectValueWithDefaultMessage(Object target, Errors errors, String defaultMessage, String[] codes,
        Object[] args) {/*from   ww w  .  j  av a  2  s.com*/
    BindingResult result = (BindingResult) errors;
    Set<String> newCodes = new LinkedHashSet<String>();

    if (args.length > 1 && messageSource != null) {
        if ((args[0] instanceof String) && (args[1] instanceof Class<?>)) {
            final Locale locale = LocaleContextHolder.getLocale();
            final Class<?> constrainedClass = (Class<?>) args[1];
            final String fullClassName = constrainedClass.getName();

            String classNameCode = fullClassName + ".label";
            String resolvedClassName = messageSource.getMessage(classNameCode, null, fullClassName, locale);
            final String classAsPropertyName = GrailsNameUtils.getPropertyName(constrainedClass);

            if (resolvedClassName.equals(fullClassName)) {
                // try short version
                classNameCode = classAsPropertyName + ".label";
                resolvedClassName = messageSource.getMessage(classNameCode, null, fullClassName, locale);
            }

            // update passed version
            if (!resolvedClassName.equals(fullClassName)) {
                args[1] = resolvedClassName;
            }

            String propertyName = (String) args[0];
            String propertyNameCode = fullClassName + '.' + propertyName + ".label";
            String resolvedPropertyName = messageSource.getMessage(propertyNameCode, null, propertyName,
                    locale);
            if (resolvedPropertyName.equals(propertyName)) {
                propertyNameCode = classAsPropertyName + '.' + propertyName + ".label";
                resolvedPropertyName = messageSource.getMessage(propertyNameCode, null, propertyName, locale);
            }

            // update passed version
            if (!resolvedPropertyName.equals(propertyName)) {
                args[0] = resolvedPropertyName;
            }
        }
    }

    //Qualified class name is added first to match before unqualified class (which is still resolved for backwards compatibility)
    newCodes.addAll(Arrays.asList(result.resolveMessageCodes(
            constraintOwningClass.getName() + '.' + constraintPropertyName + '.' + getName() + ".error",
            constraintPropertyName)));
    newCodes.addAll(Arrays.asList(result.resolveMessageCodes(
            classShortName + '.' + constraintPropertyName + '.' + getName() + ".error",
            constraintPropertyName)));
    for (String code : codes) {
        newCodes.addAll(Arrays.asList(result.resolveMessageCodes(
                constraintOwningClass.getName() + '.' + constraintPropertyName + '.' + code,
                constraintPropertyName)));
        newCodes.addAll(Arrays.asList(result.resolveMessageCodes(
                classShortName + '.' + constraintPropertyName + '.' + code, constraintPropertyName)));
        //We resolve the error code on it's own last so that a global code doesn't override a class/field specific error
        newCodes.addAll(Arrays.asList(result.resolveMessageCodes(code, constraintPropertyName)));
    }

    FieldError error = new FieldError(errors.getObjectName(), errors.getNestedPath() + constraintPropertyName,
            getPropertyValue(errors, target), false, newCodes.toArray(new String[newCodes.size()]), args,
            defaultMessage);
    ((BindingResult) errors).addError(error);
}