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, String defaultMessage) 

Source Link

Document

Create a new FieldError instance.

Usage

From source file:io.onedecision.engine.decisions.model.dmn.validators.DmnValidationErrors.java

@Override
public void rejectValue(String field, String errorCode, Object[] errorArgs, String defaultMessage) {
    fieldErrors.add(new FieldError(getObjectName(), field, defaultMessage));
}

From source file:ch.ralscha.extdirectspring.bean.ExtDirectFormPostResultTest.java

@Test
public void testExtDirectFormPostResultBindingResult() {
    BindingResult br = new TestBindingResult(Collections.<FieldError>emptyList());
    ExtDirectFormPostResult result = new ExtDirectFormPostResult(br);
    assertThat(result.getResult()).hasSize(1).contains(MapEntry.entry("success", Boolean.TRUE));

    FieldError error = new FieldError("testobject", "field1", "message");
    br = new TestBindingResult(Collections.singletonList(error));
    result = new ExtDirectFormPostResult(br);
    assertThat(result.getResult()).hasSize(2).contains(MapEntry.entry("success", Boolean.FALSE));
    Map<String, List<String>> errors = (Map<String, List<String>>) result.getResult().get("errors");
    assertThat(errors).isNotNull().hasSize(1);
    assertThat(errors.get("field1")).containsExactly("message");
}

From source file:org.jtalks.common.web.dto.ValidationResultsTest.java

@Test
public void testFieldValidationError() {
    String fieldName = "testField";
    String firstErrorMessage = "testErrorMessage1";
    String secondErrorMessage = "testErrorMessage2";
    List<FieldError> errors = new ArrayList<FieldError>();
    errors.add(new FieldError("object", fieldName, firstErrorMessage));
    errors.add(new FieldError("object", fieldName, secondErrorMessage));

    when(bindingResult.getFieldErrors()).thenReturn(errors);

    ValidationResults results = new ValidationResults(bindingResult);

    assertFalse(results.isSuccess());// w ww  .ja  va  2  s  . com
    assertEquals(results.getFieldErrors().size(), 1);
    assertTrue(results.getFieldErrors().containsKey(fieldName));
    assertEquals(results.getFieldErrors().get(fieldName).size(), 2);
    assertTrue(results.getFieldErrors().get(fieldName).contains(firstErrorMessage));
    assertTrue(results.getFieldErrors().get(fieldName).contains(secondErrorMessage));
    assertEquals(results.getGlobalErrors().size(), 0);
}

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

@Test
public void apply() throws IOException, FacesException {
    String path = "foo.bar";
    String var = "error";

    Map<String, Object> config = new HashMap<>();
    config.put(ErrorsTag.ATTRIBUTE_PATH, path);
    config.put(ErrorsTag.ATTRIBUTE_VAR, var);

    ErrorsTag tag = new ErrorsTag(MockTagConfig.factory(config, this.nextHandler));

    // set up context
    FaceletContext context = new MockFaceletContext();
    context.setAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE, this.requestContext);

    List<FieldError> objectErrors = new ArrayList<>();
    objectErrors.add(new FieldError("foo", "bar", "Test 1"));
    objectErrors.add(new FieldError("foo", "bar", "Test 2"));

    when(this.requestContext.getErrors("foo", false)).thenReturn(this.errors);
    when(this.errors.getFieldErrors("bar")).thenReturn(objectErrors);

    // run the tag
    tag.apply(context, this.parent);

    verify(this.nextHandler, times(2)).apply(context, this.parent);
}

From source file:com.mylaensys.dhtmlx.adapter.test.TestForm.java

@Test
public void errorFormAdapter() throws Exception {

    BindingResult binding = new BeanPropertyBindingResult(object, "object");

    DefaultFormAdapter adapter = new DefaultFormAdapter(object, binding);
    adapter.serialize(Locale.getDefault());

    /* Adds an error */
    binding.addError(new FieldError("object", "date", "error"));
    DefaultFormAdapter adapterWithErrors = new DefaultFormAdapter(object, binding);
    adapterWithErrors.serialize(Locale.getDefault());

}

From source file:ch.ralscha.extdirectspring.bean.ExtDirectFormPostResultTest.java

@Test
public void testExtDirectFormPostResultBindingResultBoolean() {
    BindingResult br = new TestBindingResult(Collections.<FieldError>emptyList());
    ExtDirectFormPostResult result = new ExtDirectFormPostResult(br, false);
    assertThat(result.getResult()).hasSize(1).contains(MapEntry.entry("success", Boolean.FALSE));

    br = new TestBindingResult(Arrays.asList(new FieldError("testobject", "field1", "message"),
            new FieldError("testobject", "field2", "second message")));
    result = new ExtDirectFormPostResult(br, true);
    assertThat(result.getResult()).hasSize(2).contains(MapEntry.entry("success", Boolean.TRUE));
    Map<String, List<String>> errors = (Map<String, List<String>>) result.getResult().get("errors");
    assertThat(errors).isNotNull().hasSize(2);
    assertThat(errors.get("field1")).containsExactly("message");
    assertThat(errors.get("field2")).containsExactly("second message");

    result.addError("field2", "another message");
    errors = (Map<String, List<String>>) result.getResult().get("errors");
    assertThat(errors).isNotNull().hasSize(2);
    assertThat(errors.get("field2")).containsExactly("second message", "another message");
}

From source file:com.test.springmvc.springmvcproject.IndexController.java

@RequestMapping(value = "", method = RequestMethod.POST)
public String connexion(@Valid LoginBean loginbean, BindingResult result, HttpSession session, ModelMap model) {
    if (result.hasErrors()) {
        return "index";
    }//w w w. j  a v  a  2 s  .  c o  m
    try {
        final UtilisateurBean utilisateur = utilisateurService.get(loginbean);
        if (utilisateur != null) {
            session.setAttribute("IsConnected", true);
            session.setAttribute("utilisateur", utilisateur);
            return "index";
        } else {
            throw new NoDataFoundException("connexion.utilisateur.non.trouve");
        }
    } catch (NoDataFoundException e) {
        result.addError(new FieldError("LoginBean", "email", e.getMessage()));
        return "index";
    }
}

From source file:cz.muni.fi.mvc.controllers.DestinationController.java

/**
 * Creates a new Destination/* w ww .j a  v  a2  s.co  m*/
 * @param model display data
 * @return jsp page
 */
@RequestMapping(method = RequestMethod.POST, value = "/create")
public String create(@Valid @ModelAttribute("destinationCreate") DestinationCreationalDTO formBean,
        BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
        UriComponentsBuilder uriBuilder) {
    if (bindingResult.hasErrors()) {
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);
        }
        return "destination/new";
    }
    try {
        if (destinationFacade.getDestinationWithLocation(formBean.getLocation()) == null) {
            bindingResult.addError(new FieldError("destinationCreate", "location",
                    "Destination was not created because it already exists."));
            model.addAttribute("location_error", true);
            return "destination/new";
        }

        Long id = destinationFacade.createDestination(formBean);
        redirectAttributes.addFlashAttribute("alert_info", "Destination with id: " + id + " was created");
    } catch (Exception ex) {
        model.addAttribute("alert_danger", "Destination was not created because of some unexpected error");
        redirectAttributes.addFlashAttribute("alert_danger",
                "Destination was not created because it already exists.");
    }
    return "redirect:" + uriBuilder.path("/destination").toUriString();
}

From source file:com.greenline.guahao.web.module.home.controllers.sitesmanage.CorrectController.java

/**
 * ???/*from   ww  w  . j ava  2 s . c om*/
 * 
 * @param model
 * @param request
 * @param po
 * @return
 */
@RequestMapping(value = "/submit", method = RequestMethod.POST)
@MethodRemark("remark=???")
@ResponseBody
public Map<String, Object> submit(@ModelAttribute() CorrectPO po, HttpServletRequest request,
        BindingResult result) {
    Map<String, Object> resp = new HashMap<String, Object>();
    List<FieldError> errors = null;
    correctValidator.validate(po, result);
    if (result.hasErrors()) {
        errors = result.getFieldErrors();
    } else {
        try {
            po.setDesc(po.getDesc().trim());
            CorrectDO o = correctConvertor.convertToCorrectDO(po);
            o.setSubmitPerson(UserCookieUtil.getLoginId(request));
            o.setType(po.getType());
            correctManager.addCorrect(o);
        } catch (Exception e) {
            log.error("?", e);
            errors = new ArrayList<FieldError>();
            errors.add(new FieldError("correct-add", "correct-add.error", "???"));
        }
    }
    resp.put("errors", errors);
    return resp;
}

From source file:com.fengduo.bee.commons.component.ObjectArrayDataBinder.java

private int initParamAndValues(NativeWebRequest request, String name, Map<String, String[]> paramAndValues) {
    int size = -1;
    boolean checkPrefix = false;
    if (StringUtils.isNotEmpty(name)) {
        checkPrefix = true;/*ww  w.jav a  2  s  . co m*/
    }
    for (Iterator<String> parameterNames = request.getParameterNames(); parameterNames.hasNext();) {
        String parameterName = parameterNames.next();
        if (checkPrefix && parameterName.startsWith(name + ".")) {
            String[] values = request.getParameterValues(parameterName);
            if (values != null && values.length > 0) {
                paramAndValues.put(parameterName.substring(name.length() + 1), values);
                if (size == -1) {
                    size = values.length;
                } else if (size != values.length) {
                    fieldError = new FieldError(name, name, "?");
                    return -1;
                }
            }
        }
    }
    return size;
}