Example usage for org.springframework.validation ObjectError getDefaultMessage

List of usage examples for org.springframework.validation ObjectError getDefaultMessage

Introduction

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

Prototype

@Override
    @Nullable
    public String getDefaultMessage() 

Source Link

Usage

From source file:org.zht.framework.validate.ValidateHandler.java

public static ValidateResult handle(BindingResult result) {
    ValidateResult retVal = new ValidateResult();
    if (result.hasErrors()) {
        List<ObjectError> list = result.getAllErrors();
        ObjectError oe = list.get(0);
        retVal.setMessage(oe.getDefaultMessage());
        retVal.setResult(false);//w w w  .  j a  v  a  2  s. com
    } else {
        retVal.setResult(true);
    }
    return retVal;
}

From source file:org.zht.framework.validate.ValidateHandler.java

public static String getDefaultError(BindingResult result) {
    if (result.hasErrors()) {
        List<FieldError> fieldEist = result.getFieldErrors();
        if (fieldEist != null && fieldEist.size() > 0) {
            FieldError fieldError = fieldEist.get(0);
            fieldError.getCode();//from w ww  .j  a  va  2 s  . c o m
            String prefix = "\r\n" + "???";
            String value = "{" + (fieldError.getRejectedValue() == null ? " " : fieldError.getRejectedValue())
                    + "}";
            String message = "" + fieldError.getDefaultMessage();
            return prefix + "" + value + "\r\n" + message;
        } else {
            List<ObjectError> allErrorlist = result.getAllErrors();
            ObjectError oe = allErrorlist.get(0);
            return "" + oe.getDefaultMessage();
        }
    } else {
        return null;
    }
}

From source file:org.wallride.web.support.RestValidationErrorModel.java

public static RestValidationErrorModel fromBindingResult(BindingResult result,
        MessageSourceAccessor messageSourceAccessor) {
    RestValidationErrorModel restResult = new RestValidationErrorModel();
    restResult.globalErrors = new ArrayList<>();
    for (ObjectError error : result.getGlobalErrors()) {
        restResult.globalErrors.add(/*  www .  j  ava 2  s .co m*/
                messageSourceAccessor.getMessage(error.getDefaultMessage(), LocaleContextHolder.getLocale()));
    }
    restResult.fieldErrors = new LinkedHashMap<>();
    for (FieldError error : result.getFieldErrors()) {
        restResult.fieldErrors.put(error.getField(),
                messageSourceAccessor.getMessage(error, LocaleContextHolder.getLocale()));
    }
    return restResult;
}

From source file:es.jffa.tsc.sip04.web.AccountController.java

/**
 *
 * @param result/*from   www . j  a v  a 2  s . co  m*/
 */
private static void _convertPasswordError(final BindingResult result) {
    for (ObjectError error : result.getGlobalErrors()) {
        String msg = error.getDefaultMessage();

        if ("account.password.mismatch.message".equals(msg) == true) {
            if (result.hasFieldErrors("password") == false)
                result.rejectValue("password", "error.mismatch");
        }
    }
}

From source file:net.maritimecloud.identityregistry.utils.ValidateUtil.java

public static void hasErrors(BindingResult bindingResult, HttpServletRequest request)
        throws McBasicRestException {
    if (bindingResult.hasErrors()) {
        String combinedErrMsg = "";
        for (ObjectError err : bindingResult.getAllErrors()) {
            if (combinedErrMsg.length() != 0) {
                combinedErrMsg += ", ";
            }// w  w w.  ja  v a 2 s .c  om
            combinedErrMsg += err.getDefaultMessage();
        }
        throw new McBasicRestException(HttpStatus.BAD_REQUEST, combinedErrMsg, request.getServletPath());
    }
}

From source file:com.kixeye.chassis.transport.ExceptionServiceErrorMapper.java

/**
 * Maps an exception to an error./*from w  ww  . jav  a2 s  .c  o  m*/
 * 
 * @param ex
 * @return
 */
public static ServiceError mapException(Throwable ex) {
    ServiceError error = null;

    if (ex instanceof ServiceException) {
        ServiceException servEx = (ServiceException) ex;

        error = servEx.error;
    } else if (ex instanceof MethodArgumentNotValidException) {
        MethodArgumentNotValidException validationEx = (MethodArgumentNotValidException) ex;

        List<String> errors = Lists.newArrayList();

        for (ObjectError objError : validationEx.getBindingResult().getAllErrors()) {
            errors.add(
                    objError.getObjectName() + ":" + objError.getCode() + ":" + objError.getDefaultMessage());
        }

        error = new ServiceError(VALIDATION_ERROR_CODE, Joiner.on("|").join(errors));
    } else {
        error = new ServiceError(UNKNOWN_ERROR_CODE, ex.getMessage());
    }

    return error;
}

From source file:jetx.ext.springmvc.SpringMvcFunctions.java

/**
 * ??/*from  ww w  . j  a v  a2s.  c  om*/
 */
public static List<String> globalErrors(JetPageContext ctx) {

    Errors errors = FunctionUtils.findErrors(ctx.getContext());
    if (errors == null) {
        return EMPTY_STRING_LIST;
    }

    List<ObjectError> oes = errors.getGlobalErrors();
    List<String> msgs = new ArrayList<String>(0);

    for (ObjectError oe : oes) {
        String[] codes = oe.getCodes();
        String defaultMsg = oe.getDefaultMessage();
        Object[] args = oe.getArguments();
        Locale locale = getLocale(ctx);
        MessageSource ms = getMessageSource(ctx);

        if (codes == null || codes.length == 0 || ms == null) {
            msgs.add(defaultMsg);
        } else {
            String msg = null;
            for (int i = 0; i < codes.length; i++) {
                try {
                    msg = ms.getMessage(codes[i], args, locale);
                } catch (NoSuchMessageException e) {
                    // 
                }
                if (msg == null) {
                    msg = defaultMsg;
                }
            }
            msgs.add(msg);
        }
    }
    return Collections.unmodifiableList(msgs);
}

From source file:com.google.ie.dto.ViewStatus.java

/**
 * @param errors/*www .j a va  2s .c  om*/
 */
public static ViewStatus createProjectErrorViewStatus(BindingResult errors) {
    ViewStatus viewStatus = new ViewStatus();
    log.warn("Project object has " + errors.getErrorCount() + " validation errors");
    viewStatus.setStatus(WebConstants.ERROR);
    for (Iterator<ObjectError> iterator = errors.getAllErrors().iterator(); iterator.hasNext();) {
        ObjectError objError = iterator.next();
        if (objError instanceof FieldError) {
            FieldError fieldError = (FieldError) objError;
            viewStatus.addMessage(WebConstants.ERROR,
                    fieldError.getField() + " - " + fieldError.getDefaultMessage());
            log.warn("Error found in field: " + fieldError.getField() + " Message :"
                    + objError.getDefaultMessage());
        } else {
            viewStatus.addMessage(WebConstants.ERROR, objError.getDefaultMessage());
            log.warn(" Message :" + objError.getDefaultMessage());
        }

    }
    return viewStatus;

}

From source file:org.uimafit.component.initialize.ConfigurationParameterInitializer.java

/**
 * Initialize a component from an {@link UimaContext} This code can be a little confusing
 * because the configuration parameter annotations are used in two contexts: in describing the
 * component and to initialize member variables from a {@link UimaContext}. Here we are
 * performing the latter task. It is important to remember that the {@link UimaContext} passed
 * in to this method may or may not have been derived using reflection of the annotations (i.e.
 * using {@link ConfigurationParameterFactory} via e.g. a call to a AnalysisEngineFactory.create
 * method). It is just as possible for the description of the component to come directly from an
 * XML descriptor file. So, for example, just because a configuration parameter specifies a
 * default value, this does not mean that the passed in context will have a value for that
 * configuration parameter. It should be possible for a descriptor file to specify its own value
 * or to not provide one at all. If the context does not have a configuration parameter, then
 * the default value provided by the developer as specified by the defaultValue element of the
 * {@link ConfigurationParameter} will be used. See comments in the code for additional details.
 *
 * @param component the component to initialize.
 * @param context a UIMA context with configuration parameters.
 *//*from  w w w .j  av  a  2s  . c o m*/
public static void initialize(final Object component, final UimaContext context)
        throws ResourceInitializationException {
    MutablePropertyValues values = new MutablePropertyValues();
    List<String> mandatoryValues = new ArrayList<String>();

    for (Field field : ReflectionUtil.getFields(component)) { // component.getClass().getDeclaredFields())
        if (ConfigurationParameterFactory.isConfigurationParameterField(field)) {
            org.uimafit.descriptor.ConfigurationParameter annotation = field
                    .getAnnotation(org.uimafit.descriptor.ConfigurationParameter.class);

            Object parameterValue;
            String parameterName = ConfigurationParameterFactory.getConfigurationParameterName(field);

            // Obtain either from the context - or - if the context does not provide the
            // parameter, check if there is a default value. Note there are three possibilities:
            // 1) Parameter present and set
            // 2) Parameter present and set to null (null value)
            // 3) Parameter not present (also provided as null value by UIMA)
            // Unfortunately we cannot make a difference between case 2 and 3 since UIMA does 
            // not allow us to actually get a list of the parameters set in the context. We can
            // only get a list of the declared parameters. Thus we have to rely on the null
            // value.
            parameterValue = context.getConfigParameterValue(parameterName);
            if (parameterValue == null) {
                parameterValue = ConfigurationParameterFactory.getDefaultValue(field);
            }

            if (parameterValue != null) {
                values.addPropertyValue(field.getName(), parameterValue);
            }

            // TODO does this check really belong here? It seems that
            // this check is already performed by UIMA
            if (annotation.mandatory()) {
                mandatoryValues.add(field.getName());

                //               if (parameterValue == null) {
                //                  final String key = ResourceInitializationException.CONFIG_SETTING_ABSENT;
                //                  throw new ResourceInitializationException(key,
                //                        new Object[] { configurationParameterName });
                //               }
            }
            //            else {
            //               if (parameterValue == null) {
            //                  continue;
            //               }
            //            }
            //            final Object fieldValue = convertValue(field, parameterValue);
            //            try {
            //               setParameterValue(component, field, fieldValue);
            //            }
            //            catch (Exception e) {
            //               throw new ResourceInitializationException(e);
            //            }
        }
    }

    DataBinder binder = new DataBinder(component) {
        @Override
        protected void checkRequiredFields(MutablePropertyValues mpvs) {
            String[] requiredFields = getRequiredFields();
            if (!ObjectUtils.isEmpty(requiredFields)) {
                Map<String, PropertyValue> propertyValues = new HashMap<String, PropertyValue>();
                PropertyValue[] pvs = mpvs.getPropertyValues();
                for (PropertyValue pv : pvs) {
                    String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName());
                    propertyValues.put(canonicalName, pv);
                }
                for (String field : requiredFields) {
                    PropertyValue pv = propertyValues.get(field);
                    boolean empty = (pv == null || pv.getValue() == null);
                    // For our purposes, empty Strings or empty String arrays do not count as
                    // empty. Empty is only "null".
                    //                  if (!empty) {
                    //                     if (pv.getValue() instanceof String) {
                    //                        empty = !StringUtils.hasText((String) pv.getValue());
                    //                     }
                    //                     else if (pv.getValue() instanceof String[]) {
                    //                        String[] values = (String[]) pv.getValue();
                    //                        empty = (values.length == 0 || !StringUtils.hasText(values[0]));
                    //                     }
                    //                  }
                    if (empty) {
                        // Use bind error processor to create FieldError.
                        getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult());
                        // Remove property from property values to bind:
                        // It has already caused a field error with a rejected value.
                        if (pv != null) {
                            mpvs.removePropertyValue(pv);
                            propertyValues.remove(field);
                        }
                    }
                }
            }
        }
    };
    binder.initDirectFieldAccess();
    PropertyEditorUtil.registerUimaFITEditors(binder);
    binder.setRequiredFields(mandatoryValues.toArray(new String[mandatoryValues.size()]));
    binder.bind(values);
    if (binder.getBindingResult().hasErrors()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Errors initializing [" + component.getClass() + "]");
        for (ObjectError error : binder.getBindingResult().getAllErrors()) {
            if (sb.length() > 0) {
                sb.append("\n");
            }
            sb.append(error.getDefaultMessage());
        }
        throw new IllegalArgumentException(sb.toString());
    }
}

From source file:com.github.ukase.web.ValidationError.java

public ValidationError(ObjectError error) {
    object = error.getObjectName();// w  ww  .j  a v  a  2 s . com
    message = error.getDefaultMessage();
    if (error instanceof FieldError) {
        field = ((FieldError) error).getField();
    } else {
        field = null;
    }
}