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:br.com.javatar.examples.handler.BindExceptionExceptionHandler.java

@Override
public ValidationErrorMessage createBody(BindException ex, HttpServletRequest req) {

    ErrorMessage tmpl = super.createBody(ex, req);
    ValidationErrorMessage msg = new ValidationErrorMessage(tmpl);

    for (FieldError violation : ex.getFieldErrors()) {
        String pathNode = violation.getField();

        // path is probably useful only for properties (fields)
        msg.addError(pathNode, convertToString(violation.getRejectedValue()), violation.getDefaultMessage());
    }/*w  ww. j  a  v  a2s .co  m*/

    return msg;
}

From source file:org.tonguetied.web.KeywordValidatorTest.java

/**
 * Test method for {@link org.tonguetied.web.KeywordValidator#validate(java.lang.Object, org.springframework.validation.Errors)}.
 *///ww  w .  j a v  a 2s .  co m
@Test
public final void testValidate() {
    KeywordValidator validator = new KeywordValidator();
    validator.setKeywordService(keywordService);
    Errors errors = new BindException(this.keyword, "keyword");
    validator.validate(this.keyword, errors);

    assertFalse(errors.getAllErrors().isEmpty());
    FieldError error = errors.getFieldError(fieldName);
    if (FIELD_KEYWORD.equals(fieldName)) {
        assertEquals(this.keyword.getKeyword(), error.getRejectedValue());
    } else if (FIELD_TRANSLATIONS.equals(fieldName)) {
        assertEquals(this.keyword.getTranslations(), error.getRejectedValue());
        assertEquals(1, errors.getErrorCount());
    } else {
        fail("cannot match error field");
    }
    assertFalse(error.isBindingFailure());
}

From source file:org.tonguetied.web.ExportParametersValidatorTest.java

/**
 * Test method for {@link org.tonguetied.web.ExportParametersValidator#validate(java.lang.Object, org.springframework.validation.Errors)}.
 *//*from w ww.j a va 2s . c  om*/
@Test
public void testValidate() {
    ExportParametersValidator validator = new ExportParametersValidator();
    Errors errors = new BindException(this.parameters, "parameters");
    validator.validate(parameters, errors);

    assertFalse(errors.getAllErrors().isEmpty());
    FieldError error = errors.getFieldError(fieldName);
    if (FIELD_BUNDLES.equals(fieldName)) {
        assertEquals(this.parameters.getBundles(), error.getRejectedValue());
    } else if (FIELD_COUNTRIES.equals(fieldName)) {
        assertEquals(this.parameters.getCountries(), error.getRejectedValue());
    } else if (FIELD_LANGUAGES.equals(fieldName)) {
        assertEquals(this.parameters.getLanguages(), error.getRejectedValue());
    } else if (FIELD_FORMAT_TYPE.equals(fieldName)) {
        assertEquals(this.parameters.getFormatType(), error.getRejectedValue());
    } else if (FIELD_TRANSLATION_STATE.equals(fieldName)) {
        assertEquals(this.parameters.getTranslationState(), error.getRejectedValue());
    }

    assertFalse(error.isBindingFailure());
}

From source file:org.tonguetied.web.UserValidatorTest.java

/**
 * Test method for {@link org.tonguetied.web.UserValidator#validate(java.lang.Object, org.springframework.validation.Errors)}.
 *//*  ww w .j av a  2 s .co m*/
@Test
public final void testValidateInvalidObject() {
    UserValidator validator = new UserValidator();
    validator.setUserService(userService);
    Errors errors = new BindException(this.userForm, "userForm");
    validator.validate(this.userForm, errors);

    if (fieldName == null) {
        assertTrue(errors.getAllErrors().isEmpty());
    } else {
        assertFalse(errors.getAllErrors().isEmpty());
        FieldError error = errors.getFieldError(fieldName);
        if (FIELD_USER_USERNAME.equals(fieldName)) {
            assertEquals(this.userForm.getUser().getUsername(), error.getRejectedValue());
        }
        if (FIELD_USER_FIRSTNAME.equals(fieldName)) {
            assertEquals(this.userForm.getUser().getFirstName(), error.getRejectedValue());
        }
        if (FIELD_USER_LASTNAME.equals(fieldName)) {
            assertEquals(this.userForm.getUser().getLastName(), error.getRejectedValue());
        }
        if (FIELD_USER_EMAIL.equals(fieldName)) {
            assertEquals(this.userForm.getUser().getEmail(), error.getRejectedValue());
        }
        if (FIELD_USER_PASSWORD.equals(fieldName)) {
            assertEquals(this.userForm.getUser().getPassword(), error.getRejectedValue());
        }
        if (FIELD_USER_REPEATED_PASSWORD.equals(fieldName)) {
            assertEquals(this.userForm.getUser().getRepeatedPassword(), error.getRejectedValue());
        }
        assertFalse(error.isBindingFailure());
    }
}

From source file:org.apereo.openlrs.controllers.xapi.XAPIExceptionHandlerAdvice.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody/* ww w  .jav a2  s .  c  o m*/
public XAPIErrorInfo handleMethodArgumentNotValidException(final HttpServletRequest request,
        MethodArgumentNotValidException e) {
    final List<String> errorMessages = new ArrayList<String>();
    for (ObjectError oe : e.getBindingResult().getAllErrors()) {
        if (oe instanceof FieldError) {
            final FieldError fe = (FieldError) oe;
            final String msg = String.format("Field error in object '%s' on field '%s': rejected value [%s].",
                    fe.getObjectName(), fe.getField(), fe.getRejectedValue());
            errorMessages.add(msg);
        } else {
            errorMessages.add(oe.toString());
        }
    }
    final XAPIErrorInfo result = new XAPIErrorInfo(HttpStatus.BAD_REQUEST, request, errorMessages);
    this.logException(e);
    this.logError(result);
    return result;
}

From source file:org.centralperf.controller.RunController.java

/**
 * Create a new Run//from   w  w w .ja v a2s  .  c  o m
 * @param projectId ID of the project (from URI)
 * @param run   The Run to create
 * @param result   BindingResult to check if binding raised some errors
 * @param model   Model prepared for the new project form view in case of errors
 * @return Redirection to the run detail page once the run has been created 
 */
@RequestMapping(value = "/project/{projectId}/run/new", method = RequestMethod.POST)
public String addRun(@PathVariable("projectId") Long projectId, @ModelAttribute("run") @Valid Run run,
        BindingResult result, Model model, RedirectAttributes redirectAttrs) {
    if (result.hasErrors()) {
        String errorMessage = "Error creating Run : ";
        for (FieldError error : result.getFieldErrors()) {
            errorMessage += "Field " + error.getField() + ",  " + error.getDefaultMessage() + " ( "
                    + error.getRejectedValue() + ")";
        }
        redirectAttrs.addFlashAttribute("error", errorMessage);
        return "redirect:/project/" + projectId + "/detail";
    }
    ScriptVersion scriptVersion = scriptVersionRepository.findOne(run.getScriptVersion().getId());
    run.setScriptVersion(scriptVersion);
    runRepository.save(run);
    return "redirect:/project/" + projectId + "/run/" + run.getId() + "/detail";
}

From source file:com.iflytek.edu.cloud.frame.spring.DefaultHandlerExceptionResolver.java

/**
 * ??/*from www .jav a  2 s.  c om*/
 *
 * @param allErrors
 * @param locale
 * @param subErrorType
 * @return
 */
private MainError getBusinessParameterMainError(List<ObjectError> allErrors, Locale locale,
        SubErrorType subErrorType) {
    MainError mainError = SubErrors.getMainError(subErrorType, locale);
    for (ObjectError objectError : allErrors) {
        if (objectError instanceof FieldError) {
            FieldError fieldError = (FieldError) objectError;
            SubErrorType tempSubErrorType = INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.get(fieldError.getCode());
            if (tempSubErrorType == subErrorType) {
                SubError subError = SubErrors.getSubError(tempSubErrorType.value(), locale,
                        fieldError.getField(), fieldError.getRejectedValue(), fieldError.getDefaultMessage());
                mainError.addSubError(subError);
            }
        }
    }
    return mainError;
}

From source file:org.sakaiproject.metaobj.shared.control.XsltArtifactView.java

protected Source createXsltSource(Map map, String string, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws Exception {

    httpServletResponse.setContentType(getContentType());
    WebApplicationContext context = getWebApplicationContext();
    setUriResolver((URIResolver) context.getBean(uriResolverBeanName));

    ToolSession toolSession = SessionManager.getCurrentToolSession();

    String homeType = null;/*  w ww. j  av a2 s.  c o  m*/

    ElementBean bean = (ElementBean) map.get("bean");

    Element root = null;
    Map paramsMap = new Hashtable();

    for (Enumeration e = httpServletRequest.getParameterNames(); e.hasMoreElements();) {
        String k = e.nextElement().toString();
        // Do not allow reserved parameter names to be overwritten
        if (!reservedParams.contains(k)) {
            paramsMap.put(k, httpServletRequest.getParameter(k));
        }
    }

    httpServletRequest.setAttribute(STYLESHEET_PARAMS, paramsMap);
    if (toolSession.getAttribute(FormHelper.PREVIEW_HOME_TAG) != null) {
        paramsMap.put("preview", "true");
    }

    if (toolSession.getAttribute(ResourceToolAction.ACTION_PIPE) != null) {
        paramsMap.put("fromResources", "true");
    }

    if (httpServletRequest.getAttribute(FormHelper.URL_DECORATION) != null) {
        paramsMap.put("urlDecoration", httpServletRequest.getAttribute(FormHelper.URL_DECORATION));
    }

    HashMap<String, String> xslParams = new HashMap<String, String>();
    xslParams.put(FormHelper.XSL_PRESENTATION_ID, FormHelper.PRESENTATION_ID);
    xslParams.put(FormHelper.XSL_PRESENTATION_TYPE, FormHelper.PRESENTATION_TEMPLATE_ID);
    xslParams.put(FormHelper.XSL_PRESENTATION_ITEM_ID, FormHelper.PRESENTATION_ITEM_DEF_ID);
    xslParams.put(FormHelper.XSL_PRESENTATION_ITEM_NAME, FormHelper.PRESENTATION_ITEM_DEF_NAME);
    xslParams.put(FormHelper.XSL_FORM_TYPE, ResourceEditingHelper.CREATE_SUB_TYPE);
    xslParams.put(FormHelper.XSL_ARTIFACT_REFERENCE, ResourceEditingHelper.ATTACHMENT_ID);
    xslParams.put(FormHelper.XSL_OBJECT_ID, FormHelper.XSL_OBJECT_ID);
    xslParams.put(FormHelper.XSL_OBJECT_TITLE, FormHelper.XSL_OBJECT_TITLE);
    xslParams.put(FormHelper.XSL_WIZARD_PAGE_ID, FormHelper.XSL_WIZARD_PAGE_ID);

    // Load up our XSL parameters according to the mapping into the tool session above.
    // Note that this is not always one-to-one due to some string/key inconsistencies around the tools.
    for (Entry<String, String> item : xslParams.entrySet()) {
        Object val = toolSession.getAttribute(item.getValue());
        if (val != null) {
            paramsMap.put(item.getKey(), val);
        }
    }

    Id id = null;

    if (bean instanceof Artifact) {
        root = getStructuredArtifactDefinitionManager().createFormViewXml((Artifact) bean, null);
        homeType = getHomeType((Artifact) bean);
        id = ((Artifact) bean).getId();
    } else {
        EditedArtifactStorage sessionBean = (EditedArtifactStorage) httpServletRequest.getSession()
                .getAttribute(EditedArtifactStorage.EDITED_ARTIFACT_STORAGE_SESSION_KEY);

        if (sessionBean != null) {
            root = getStructuredArtifactDefinitionManager()
                    .createFormViewXml((Artifact) sessionBean.getRootArtifact(), null);

            replaceNodes(root, bean, sessionBean);
            paramsMap.put("subForm", "true");
            homeType = getHomeType(sessionBean.getRootArtifact());
            id = sessionBean.getRootArtifact().getId();
        } else {
            return new javax.xml.transform.dom.DOMSource();
        }
    }

    if (id != null) {
        paramsMap.put("edit", "true");
        paramsMap.put(FormHelper.XSL_ARTIFACT_ID, id.getValue());
    }

    httpServletRequest.setAttribute(STYLESHEET_LOCATION,
            getStructuredArtifactDefinitionManager().getTransformer(homeType, readOnly));

    Errors errors = BindingResultUtils.getBindingResult(map, "bean");
    if (errors != null && errors.hasErrors()) {
        Element errorsElement = new Element("errors");

        List errorsList = errors.getAllErrors();

        for (Iterator i = errorsList.iterator(); i.hasNext();) {
            Element errorElement = new Element("error");
            ObjectError error = (ObjectError) i.next();
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                errorElement.setAttribute("field", fieldError.getField());
                Element rejectedValue = new Element("rejectedValue");
                if (fieldError.getRejectedValue() != null) {
                    rejectedValue.addContent(fieldError.getRejectedValue().toString());
                }
                errorElement.addContent(rejectedValue);
            }
            Element message = new Element("message");
            message.addContent(context.getMessage(error, getResourceLoader().getLocale()));
            errorElement.addContent(message);
            errorsElement.addContent(errorElement);
        }

        root.addContent(errorsElement);
    }

    if (httpServletRequest.getParameter("success") != null) {
        Element success = new Element("success");
        success.setAttribute("messageKey", httpServletRequest.getParameter("success"));
        root.addContent(success);
    }

    if (toolSession.getAttribute(ResourceEditingHelper.CUSTOM_CSS) != null) {
        Element uri = new Element("uri");
        uri.setText((String) toolSession.getAttribute(ResourceEditingHelper.CUSTOM_CSS));
        root.getChild("css").addContent(uri);
        uri.setAttribute("order", "100");
    }

    if (toolSession.getAttribute(FormHelper.FORM_STYLES) != null) {
        List styles = (List) toolSession.getAttribute(FormHelper.FORM_STYLES);
        int index = 101;
        for (Iterator<String> i = styles.iterator(); i.hasNext();) {
            Element uri = new Element("uri");
            uri.setText(i.next());
            root.getChild("css").addContent(uri);
            uri.setAttribute("order", "" + index);
            index++;
        }
    }

    Document doc = new Document(root);
    return new JDOMSource(doc);
}

From source file:jp.terasoluna.batch.functionsample.b009.SkipValidationErrorHandler.java

/**
 * ?O?W.<br>/*from  w w w.ja v a 2 s .  c o m*/
 * @param dataValueObject DataValueObject
 * @param errors Errors
 * @return ?O
 */
protected String logEdit(DataValueObject dataValueObject, Errors errors) {
    StringBuilder sb = new StringBuilder();
    List<FieldError> fel = getFieldErrorList(errors);

    for (FieldError fe : fel) {
        sb.setLength(0);
        sb.append("ValidationError");
        sb.append(" dataCount:[");
        if (dataValueObject != null) {
            sb.append(dataValueObject.getDataCount());
        }
        sb.append("]");
        sb.append(" code:[");
        sb.append(fe.getCode());
        sb.append("]");
        sb.append(" objectName:[");
        sb.append(fe.getObjectName());
        sb.append("]");
        sb.append(" field:[");
        sb.append(fe.getField());
        sb.append("]");
        sb.append(" rejectedValue:[");
        sb.append(fe.getRejectedValue());
        sb.append("]");
    }
    return sb.toString();
}

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

/**
 * Protected method to Parse Result./*from   www.  j  a va2  s .c  o  m*/
 * 
 * @param result
 * @param map
 */
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);
            }
            errorMsgList.add(fieldName + " field value '" + fieldError.getRejectedValue() + "' is not valid.");
        }

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