Example usage for org.springframework.validation ObjectError getArguments

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

Introduction

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

Prototype

@Override
    @Nullable
    public Object[] getArguments() 

Source Link

Usage

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

/**
 * ??//from ww  w  .  j a va2s. c  o  m
 */
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:org.opentides.util.CrudUtil.java

/**
 * Converts the binding error messages to list of MessageResponse
 * /*from w  ww  .ja  v a 2  s .  co m*/
 * @param bindingResult
 */
public static List<MessageResponse> convertErrorMessage(BindingResult bindingResult, Locale locale,
        MessageSource messageSource) {
    List<MessageResponse> errorMessages = new ArrayList<MessageResponse>();
    if (bindingResult.hasErrors()) {
        for (ObjectError error : bindingResult.getAllErrors()) {
            MessageResponse message = null;
            if (error instanceof FieldError) {
                FieldError ferror = (FieldError) error;
                message = new MessageResponse(MessageResponse.Type.error, error.getObjectName(),
                        ferror.getField(), error.getCodes(), error.getArguments());
            } else
                message = new MessageResponse(MessageResponse.Type.error, error.getObjectName(), null,
                        error.getCodes(), error.getArguments());
            message.setMessage(messageSource.getMessage(message, locale));
            errorMessages.add(message);
        }
    }
    return errorMessages;
}

From source file:com.mitchellbosecke.pebble.spring.extension.function.bindingresult.GetAllErrorsFunction.java

@Override
public Object execute(Map<String, Object> args) {
    List<String> results = new ArrayList<>();
    String formName = (String) args.get(PARAM_FORM_NAME);

    EvaluationContext context = (EvaluationContext) args.get("_context");
    Locale locale = context.getLocale();
    BindingResult bindingResult = this.getBindingResult(formName, context);

    if (bindingResult != null) {
        for (ObjectError error : bindingResult.getAllErrors()) {
            String msg = this.messageSource.getMessage(error.getCode(), error.getArguments(),
                    error.getDefaultMessage(), locale);
            if (msg != null) {
                results.add(msg);//from   w w  w  . j  a va  2  s.co m
            }
        }
    }
    return results;
}

From source file:com.mitchellbosecke.pebble.spring.extension.function.bindingresult.GetGlobalErrorsFunction.java

@Override
public Object execute(Map<String, Object> args) {
    List<String> results = new ArrayList<>();
    String formName = (String) args.get(PARAM_FORM_NAME);

    EvaluationContext context = (EvaluationContext) args.get("_context");
    Locale locale = context.getLocale();
    BindingResult bindingResult = this.getBindingResult(formName, context);

    if (bindingResult != null) {
        for (ObjectError error : bindingResult.getGlobalErrors()) {
            String msg = this.messageSource.getMessage(error.getCode(), error.getArguments(),
                    error.getDefaultMessage(), locale);
            if (msg != null) {
                results.add(msg);//ww w. ja  v  a  2 s .c  om
            }
        }
    }
    return results;
}

From source file:org.openmrs.module.admintoolsui.page.controller.account.AccountPageController.java

private String getMessageErrors(MessageSource messageSource, List<ObjectError> allErrors) {
    String message = "";
    for (ObjectError error : allErrors) {
        Object[] arguments = error.getArguments();
        String errorMessage = messageSource.getMessage(error.getCode(), arguments, Context.getLocale());
        message = message.concat(replaceArguments(errorMessage, arguments).concat("<br>"));
    }/*from w  ww  . ja  v  a  2 s .c  o  m*/
    return message;
}

From source file:com.acc.controller.BaseController.java

protected ValidationErrorData handleValidationErrorInternal(final String errorClass, final String errorMsg,
        final Errors errors) {
    final Locale currentLocale = commerceCommonI18NService.getCurrentLocale();
    final ValidationErrorData validationErrorData = new ValidationErrorData();
    validationErrorData.setClassName(errorClass);
    validationErrorData.setMessage(errorMsg);
    final List<String> validationErrors = new ArrayList<String>();
    for (final ObjectError error : errors.getGlobalErrors()) {
        final String validationError = getMessage(error.getCode(), error.getArguments(), currentLocale);
        validationErrors.add(validationError);
    }//  w w w .j  a  v a 2  s.c o m
    for (final FieldError error : errors.getFieldErrors()) {
        final String validationError = createValidationError(error.getField(),
                getMessage(error.getCode(), error.getArguments(), currentLocale));
        validationErrors.add(validationError);
    }
    validationErrorData.setValidationErrors(validationErrors);
    return validationErrorData;
}

From source file:org.openmrs.module.OpenmrsLite.page.controller.EditPatientDemographicsPageController.java

/**
 * @should void the old person name and replace it with a new one when it is edited
 * @should not void the existing name if there are no changes in the name
 *///from w  w  w .  j av a2 s . co m
public String post(UiSessionContext sessionContext, PageModel model,
        @SpringBean("patientService") PatientService patientService,
        @RequestParam("patientId") @BindParams Patient patient, @BindParams PersonName name,
        @RequestParam("returnUrl") String returnUrl,
        @SpringBean("nameTemplateGivenFamily") NameTemplate nameTemplate, HttpServletRequest request,
        @SpringBean("messageSourceService") MessageSourceService messageSourceService, Session session,
        @SpringBean("patientValidator") PatientValidator patientValidator, UiUtils ui) throws Exception {

    sessionContext.requireAuthentication();

    if (patient.getPersonName() != null && name != null) {
        PersonName currentName = patient.getPersonName();
        if (!currentName.equalsContent(name)) {
            //void the old name and replace it with the new one
            patient.addName(name);
            currentName.setVoided(true);
        }
    }

    BindingResult errors = new BeanPropertyBindingResult(patient, "patient");
    patientValidator.validate(patient, errors);

    if (!errors.hasErrors()) {
        try {
            patientService.savePatient(patient);
            InfoErrorMessageUtil.flashInfoMessage(request.getSession(),
                    ui.message("OpenmrsLite.editDemographicsMessage.success", patient.getPersonName()));

            return "redirect:" + returnUrl;
        } catch (Exception e) {
            log.warn("Error occurred while saving patient demographics", e);
            session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, "OpenmrsLite.save.fail");
        }

    } else {
        model.addAttribute("errors", errors);
        StringBuffer errorMessage = new StringBuffer(
                messageSourceService.getMessage("error.failed.validation"));
        errorMessage.append("<ul>");
        for (ObjectError error : errors.getAllErrors()) {
            errorMessage.append("<li>");
            errorMessage.append(messageSourceService.getMessage(error.getCode(), error.getArguments(),
                    error.getDefaultMessage(), null));
            errorMessage.append("</li>");
        }
        errorMessage.append("</ul>");
        session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, errorMessage.toString());
    }

    model.addAttribute("patient", patient);
    model.addAttribute("nameTemplate", nameTemplate);
    model.addAttribute("returnUrl", returnUrl);
    //redisplay the form
    return null;
}

From source file:org.openmrs.module.registration.page.controller.EditPatientDemographicsPageController.java

/**
 * @should void the old person name and replace it with a new one when it is edited
 * @should not void the existing name if there are no changes in the name
 *///from w w w.j  a  v a2s .c  om
public String post(UiSessionContext sessionContext, PageModel model,
        @SpringBean("patientService") PatientService patientService,
        @RequestParam("patientId") @BindParams Patient patient, @BindParams PersonName name,
        @RequestParam("returnUrl") String returnUrl,
        @SpringBean("nameTemplateGivenFamily") NameTemplate nameTemplate, HttpServletRequest request,
        @SpringBean("messageSourceService") MessageSourceService messageSourceService, Session session,
        @SpringBean("patientValidator") PatientValidator patientValidator, UiUtils ui) throws Exception {

    sessionContext.requireAuthentication();

    if (patient.getPersonName() != null && name != null) {
        PersonName currentName = patient.getPersonName();
        if (!currentName.equalsContent(name)) {
            //void the old name and replace it with the new one
            patient.addName(name);
            currentName.setVoided(true);
        }
    }

    BindingResult errors = new BeanPropertyBindingResult(patient, "patient");
    patientValidator.validate(patient, errors);

    if (!errors.hasErrors()) {
        try {
            patientService.savePatient(patient);
            InfoErrorMessageUtil.flashInfoMessage(request.getSession(),
                    ui.message("registration.editDemographicsMessage.success", patient.getPersonName()));

            return "redirect:" + returnUrl;
        } catch (Exception e) {
            log.warn("Error occurred while saving patient demographics", e);
            session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, "registration.save.fail");
        }

    } else {
        model.addAttribute("errors", errors);
        StringBuffer errorMessage = new StringBuffer(
                messageSourceService.getMessage("error.failed.validation"));
        errorMessage.append("<ul>");
        for (ObjectError error : errors.getAllErrors()) {
            errorMessage.append("<li>");
            errorMessage.append(messageSourceService.getMessage(error.getCode(), error.getArguments(),
                    error.getDefaultMessage(), null));
            errorMessage.append("</li>");
        }
        errorMessage.append("</ul>");
        session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, errorMessage.toString());
    }

    model.addAttribute("patient", patient);
    model.addAttribute("nameTemplate", nameTemplate);
    model.addAttribute("returnUrl", returnUrl);
    //redisplay the form
    return null;
}

From source file:technology.tikal.gae.service.template.RestControllerTemplate.java

@ExceptionHandler(NotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)//from   w  w  w. j a v  a2s  .c om
public BasicErrorMessage handleException(NotValidException ex, HttpServletRequest request,
        HttpServletResponse response) {
    response.setHeader("Content-Type", "application/json;charset=UTF-8");
    BasicErrorMessage result = new BasicErrorMessage();
    BindingResult detail = ex.getDetails();
    String[] msg = new String[detail.getAllErrors().size()];
    String[][] code = new String[detail.getAllErrors().size()][];
    String[][] args = new String[detail.getAllErrors().size()][];
    int index = 0;
    Locale locale = LocaleContextHolder.getLocale();
    for (ObjectError x : detail.getAllErrors()) {
        Object[] tmpArgs = resolveArgumentMessage(x.getCodes(), x.getArguments());
        msg[index] = getValidationMessage(x.getDefaultMessage(), x.getCodes(), tmpArgs, locale);
        code[index] = x.getCodes();
        String[] tmp = new String[tmpArgs.length];
        args[index] = tmp;
        int j = 0;
        for (Object y : tmpArgs) {
            args[index][j] = y.toString();
            j = j + 1;
        }
        index = index + 1;
    }
    result.setType(ex.getClass().getSimpleName());
    result.setMessage(msg);
    result.setCode(code);
    result.setArguments(args);
    return result;
}

From source file:org.openmrs.module.OpenmrsLite.page.controller.EditPatientContactInfoPageController.java

/**
 * @should void the old person address and replace it with a new one when it is edited
 * @should void the old person address and replace it with a new one when it is edited
 * @should not void the existing address if there are no changes
 *//*from  w w  w .  j  a  va 2s .  c  om*/
public String post(UiSessionContext sessionContext, PageModel model,
        @RequestParam("patientId") @BindParams Patient patient, @BindParams PersonAddress address,
        @SpringBean("patientService") PatientService patientService, @RequestParam("appId") AppDescriptor app,
        @RequestParam("returnUrl") String returnUrl,
        @SpringBean("adminService") AdministrationService administrationService, HttpServletRequest request,
        @SpringBean("messageSourceService") MessageSourceService messageSourceService, Session session,
        @SpringBean("patientValidator") PatientValidator patientValidator, UiUtils ui) throws Exception {

    sessionContext.requireAuthentication();

    if (patient.getPersonAddress() != null && address != null) {
        PersonAddress currentAddress = patient.getPersonAddress();
        if (!currentAddress.equalsContent(address)) {
            //void the old address and replace it with the new one
            patient.addAddress(address);
            currentAddress.setVoided(true);
        }
    }

    NavigableFormStructure formStructure = RegisterPatientFormBuilder.buildFormStructure(app);

    BindingResult errors = new BeanPropertyBindingResult(patient, "patient");
    patientValidator.validate(patient, errors);
    RegistrationAppUiUtils.validateLatitudeAndLongitudeIfNecessary(address, errors);

    if (formStructure != null) {
        RegisterPatientFormBuilder.resolvePersonAttributeFields(formStructure, patient,
                request.getParameterMap());
    }

    if (!errors.hasErrors()) {
        try {
            //The person address changes get saved along as with the call to save patient
            patientService.savePatient(patient);
            InfoErrorMessageUtil.flashInfoMessage(request.getSession(),
                    ui.message("OpenmrsLite.editContactInfoMessage.success", patient.getPersonName()));

            return "redirect:" + returnUrl;
        } catch (Exception e) {
            log.warn("Error occurred while saving patient's contact info", e);
            session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, "OpenmrsLite.save.fail");
        }

    } else {
        model.addAttribute("errors", errors);
        StringBuffer errorMessage = new StringBuffer(
                messageSourceService.getMessage("error.failed.validation"));
        errorMessage.append("<ul>");
        for (ObjectError error : errors.getAllErrors()) {
            errorMessage.append("<li>");
            errorMessage.append(messageSourceService.getMessage(error.getCode(), error.getArguments(),
                    error.getDefaultMessage(), null));
            errorMessage.append("</li>");
        }
        errorMessage.append("</ul>");
        session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, errorMessage.toString());
    }

    addModelAttributes(model, patient, formStructure, administrationService, returnUrl);
    //redisplay the form
    return null;
}