Example usage for org.springframework.validation Errors getGlobalErrors

List of usage examples for org.springframework.validation Errors getGlobalErrors

Introduction

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

Prototype

List<ObjectError> getGlobalErrors();

Source Link

Document

Get all global errors.

Usage

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

/**
 * ??/*from   w  w w .  j av a 2 s .co  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:com.wisemapping.rest.model.RestErrors.java

private List<String> processGlobalErrors(@NotNull Errors errors) {
    final List<String> result = new ArrayList<String>();
    final List<ObjectError> globalErrors = errors.getGlobalErrors();
    for (ObjectError globalError : globalErrors) {
        result.add(globalError.getObjectName());
    }/*from ww w  . j a  va 2 s  . c o m*/
    return result;
}

From source file:org.ualerts.fixed.web.controller.AbstractFormController.java

private List<String> getGlobalErrors(Errors errors) {
    if (!errors.hasGlobalErrors())
        return null;

    List<String> globalErrors = new ArrayList<String>();
    for (ObjectError error : errors.getGlobalErrors()) {
        globalErrors.add(getMessage(error.getCode()));
    }//from   w  w w  .j  av  a  2  s .  c  om
    return globalErrors;
}

From source file:org.openmrs.module.casereport.CaseReportValidatorTest.java

/**
 * @see CaseReportValidator#validate(Object,Errors)
 * @verifies fail for a new item if the patient already has an existing report item
 */// ww w  . java  2 s .c o m
@Test
public void validate_shouldFailForANewItemIfThePatientAlreadyHasAnExistingReportItem() throws Exception {
    executeDataSet("moduleTestData-initial.xml");
    Patient patient = Context.getPatientService().getPatient(6);
    CaseReport existing = service.getCaseReport(2);
    final String trigger = "HIV Patient Died";
    assertNotNull(existing);
    assertNotNull(existing.getCaseReportTriggerByName(trigger));
    CaseReport caseReport = new CaseReport(patient, trigger);
    Errors errors = new BindException(caseReport, "casereport");
    validator.validate(caseReport, errors);
    assertTrue(errors.hasErrors());
    assertEquals(1, errors.getGlobalErrors().size());
    assertEquals("casereports.error.patient.alreadyHasQueueItem", errors.getGlobalErrors().get(0).getCode());
}

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 av  a2 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.uiframework.FragmentActionController.java

/**
 * @param path should be of the form "provider/optional/subdirectories/fragmentName/actionName"
 * @param returnFormat/*  w w w . jav a  2s.  c o  m*/
 * @param successUrl
 * @param failureUrl
 * @param request
 * @param model
 * @param response
 * @return
 * @throws Exception
 */
public String handlePath(String path, String returnFormat, String successUrl, String failureUrl,
        HttpServletRequest request, Model model, HttpServletResponse response) throws Exception {
    // handle the case where the url has two slashes, e.g. host/openmrs//emr/radiology/order.action
    if (path.startsWith("/")) {
        path = path.substring(1);
    }
    int firstSlash = path.indexOf("/");
    int lastSlash = path.lastIndexOf("/");
    if (firstSlash < 0 || lastSlash < 0) {
        throw new IllegalArgumentException(
                "fragment action request must have at least provider/fragmentName/actionName, but this does not: "
                        + request.getRequestURI());
    }
    String providerName = path.substring(0, firstSlash);
    String fragmentName = path.substring(firstSlash + 1, lastSlash);
    String action = path.substring(lastSlash + 1);

    if (returnFormat == null) {
        String acceptHeader = request.getHeader("Accept");
        if (StringUtils.isNotEmpty(acceptHeader)) {
            if (acceptHeader.startsWith("application/json")) {
                returnFormat = "json";
            }
        }
    }

    Object resultObject;
    try {
        resultObject = fragmentFactory.invokeFragmentAction(providerName, fragmentName, action, request);

        // Default status code for failures is 400 (BAD REQUEST), successes is 200 (OK)
        response.setStatus((resultObject instanceof FailureResult) ? 400 : 200);

    } catch (Exception ex) {

        // Look for specific exceptions down the chain
        Exception specificEx = null;

        // It's possible that the underlying exception is that the user was logged out or lacks privileges
        if ((specificEx = ExceptionUtil.findExceptionInChain(ex, APIAuthenticationException.class)) != null) {
            resultObject = new FailureResult("#APIAuthenticationException#" + specificEx.getMessage());
            response.setStatus(403); // 403 (FORBIDDEN)
        } else if ((specificEx = ExceptionUtil.findExceptionInChain(ex,
                ContextAuthenticationException.class)) != null) {
            resultObject = new FailureResult("#APIAuthenticationException#" + specificEx.getMessage());
            response.setStatus(403); // 403 (FORBIDDEN)
        } else {
            // We don't know how to handle other types of exceptions
            log.error("error", ex);

            // TODO figure how to return UiFrameworkExceptions that result from
            // missing controllers or methods with status 404 (NOT FOUND)
            throw new UiFrameworkException("Error invoking fragment action", ex);
        }
    }

    if (!StringUtils.isEmpty(returnFormat)) {
        // this is an ajax request, so we need to return an object

        // turn the non-object result types into ObjectResults
        if (resultObject == null) {
            resultObject = new SuccessResult();
        } else if (resultObject instanceof SuccessResult) {
            SuccessResult success = (SuccessResult) resultObject;
            resultObject = SimpleObject.create("success", "true", "message", success.getMessage());
        } else if (resultObject instanceof FailureResult) {
            FailureResult failure = (FailureResult) resultObject;
            resultObject = SimpleObject.create("failure", "true", "globalErrors", failure.getGlobalErrors(),
                    "fieldErrors", failure.getFieldErrorMap());
        } else if (resultObject instanceof ObjectResult) {
            resultObject = ((ObjectResult) resultObject).getWrapped();
        }

        // Convert result to JSON or plain text depending on requested format
        Object result;
        if (returnFormat.equals("json")) {
            result = toJson(resultObject);
        } else {
            result = resultObject.toString();
        }

        model.addAttribute("html", result);

        return SHOW_HTML_VIEW;

    } else {
        // this is a regular post, so we will return a page

        if (successUrl == null)
            successUrl = getSuccessUrl(request);
        if (failureUrl == null)
            failureUrl = getFailureUrl(request, successUrl);

        successUrl = removeContextPath(successUrl);
        failureUrl = removeContextPath(failureUrl);

        if (resultObject == null || resultObject instanceof SuccessResult) {
            if (resultObject != null) {
                SuccessResult result = (SuccessResult) resultObject;
                if (result.getMessage() != null)
                    request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, result.getMessage());
            }
            return "redirect:/" + successUrl;
        } else if (resultObject instanceof FailureResult) {
            // TODO harmonize this with the return-type version
            FailureResult failureResult = (FailureResult) resultObject;
            String errorMessage = null;
            if (failureResult.getSingleError() != null) {
                errorMessage = failureResult.getSingleError();
            } else if (failureResult.getErrors() != null) {
                Errors errors = failureResult.getErrors();
                StringBuilder sb = new StringBuilder();
                sb.append("<ul>");
                for (ObjectError err : errors.getGlobalErrors()) {
                    sb.append("<li>" + UiFrameworkUtil.getMessage(err) + "</li>");
                }
                for (FieldError err : errors.getFieldErrors()) {
                    sb.append("<li>" + err.getField() + ": " + UiFrameworkUtil.getMessage(err) + "</li>");
                }
                sb.append("</ul>");
                errorMessage = sb.toString();
            }
            request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, errorMessage);
            return redirectHelper(failureUrl, model);
        } else if (resultObject instanceof ObjectResult) {
            // the best we can do is just display a formatted version of the wrapped object
            String formatted = new FormatterImpl(messageSource, administrationService)
                    .format(((ObjectResult) resultObject).getWrapped(), Context.getLocale());
            model.addAttribute("html", formatted);
            return SHOW_HTML_VIEW;

        } else {
            throw new RuntimeException(
                    "Don't know how to handle fragment action result type: " + resultObject.getClass());
        }
    }
}

From source file:pl.chilldev.facelets.taglib.spring.web.form.ErrorsTag.java

/**
 * {@inheritDoc}//  ww  w .  j  ava  2 s. co m
 *
 * @since 0.0.1
 */
@Override
public void apply(FaceletContext context, UIComponent parent) throws IOException {
    RequestContext requestContext = this.getRequestContext(context);

    // unsupported execution context
    if (requestContext == null) {
        return;
    }

    List<String> errorMessages = new ArrayList<>();
    try {
        String beanName;
        String path = this.path.getValue(context);

        // split property path
        int position = path.indexOf('.');
        if (position == -1) {
            beanName = path;
            path = null;
        } else {
            beanName = path.substring(0, position);
            path = path.substring(position + 1);
        }

        Errors errors = requestContext.getErrors(beanName, false);

        // nothing was wrong
        if (errors == null) {
            return;
        }

        // find error objects
        List<? extends ObjectError> objectErrors;
        if (path != null) {
            if ("*".equals(path)) {
                objectErrors = errors.getAllErrors();
            } else {
                objectErrors = errors.getFieldErrors(path);
            }
        } else {
            objectErrors = errors.getGlobalErrors();
        }

        // build messages
        for (ObjectError error : objectErrors) {
            errorMessages.add(requestContext.getMessage(error, false));
        }
    } catch (IllegalStateException error) {
        return;
    }

    String var = this.var.getValue(context);
    Object value = context.getAttribute(var);

    try {
        // invoke tag content for every error message
        for (String message : errorMessages) {
            context.setAttribute(var, message);
            this.nextHandler.apply(context, parent);
        }
    } finally {
        // recover old values
        context.setAttribute(var, value);
    }
}

From source file:org.springframework.validation.SimpleErrors.java

@Override
public void addAllErrors(Errors errors) {
    Assert.notNull(errors, "No errors to add");
    if (ExtendedStringUtils.safeCompare(getObjectName(), errors.getObjectName()) != 0) {
        throw new IllegalArgumentException("addErrors(" + getObjectName()
                + ") mismatched argument object name: " + errors.getObjectName());
    }/*  www .  j a va 2  s .com*/

    Collection<? extends ObjectError> glbl = errors.getGlobalErrors();
    if (ExtendedCollectionUtils.size(glbl) > 0) {
        globalErrors.addAll(glbl);
    }

    Collection<? extends FieldError> flds = errors.getFieldErrors();
    if (ExtendedCollectionUtils.size(flds) > 0) {
        fieldErrors.addAll(flds);
    }
}