Example usage for org.springframework.validation FieldError getCode

List of usage examples for org.springframework.validation FieldError getCode

Introduction

In this page you can find the example usage for org.springframework.validation FieldError getCode.

Prototype

@Nullable
public String getCode() 

Source Link

Document

Return the default code of this resolvable, that is, the last one in the codes array.

Usage

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

/**
 * ?O?W.<br>//from ww w .j  a  v a2  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.AbstractBillingController.java

@RequestMapping(value = "/record_deposit", method = RequestMethod.POST)
@ResponseBody//from ww w . j  a v  a2 s.  co  m
public DepositRecordForm recordDeposit(@RequestParam(value = "tenant", required = false) String tenantParam,
        @Valid @ModelAttribute("depositRecordForm") DepositRecordForm depositRecordForm, BindingResult result,
        ModelMap map, HttpServletResponse response) {
    logger.debug("###Entering in recordDeposit method @POST");

    setPage(map, Page.USAGE_BILLING_RECORD_DEPOSIT);
    map.addAttribute("showUserProfile", true);

    Tenant tenant = tenantService.get(tenantParam);
    map.addAttribute("tenant", tenant);
    map.addAttribute("depositForm", depositRecordForm);
    DepositRecordValidator depositRecordValidator = new DepositRecordValidator();
    depositRecordValidator.validate(depositRecordForm, result);
    if (result.hasErrors()) {
        map.addAttribute("depositRecordForm", depositRecordForm);
        List<FieldError> l = result.getFieldErrors();
        for (FieldError f : l) {
            if (f.getCode().equals("js.deposit.record.validationReceivedOn")) {
                throw new AjaxFormValidationException(result);
            }
        }
    }

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        Date recievedOn = null;
        try {
            recievedOn = sdf.parse(depositRecordForm.getReceivedOn());
        } catch (ParseException e) {
        }
        tenantService.recordDeposit(tenant,
                new DepositRecord(
                        tenant, recievedOn, tenant.getAccountType()
                                .getInitialDeposit(tenant.getCurrency().getCurrencyCode()).doubleValue(),
                        getCurrentUser()));

    } catch (HibernateOptimisticLockingFailureException ex) {
        logger.error(ex);
        tenantService.refresh(tenant);
        throw new InvalidAjaxRequestException(ex.getMessage());
    }
    response.setStatus(HttpStatus.OK.value());
    logger.debug("###Exiting recordDeposit method @POST");

    return depositRecordForm;
}

From source file:fragment.web.RegistrationControllerTest.java

@Test
public void testRegisterInvalidUsernameLength() throws Exception {
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    AccountType accountType = accountTypeDAO.getAccountTypeByName("RETAIL");

    UserRegistration registration = new UserRegistration();
    // Creating user and tenant objects for registration
    final String USERNAME = "abcd";
    User user = new User("test", "test", "test@test.com", USERNAME, VALID_PASSWORD, VALID_PHONE, VALID_TIMEZONE,
            null, null, null);/* w w  w .  ja  v  a  2  s  . co  m*/
    BindingResult result = setUpRegistrationForGivenUser(user, registration, accountType);

    beforeRegisterCall(mockRequest, registration);
    int beforeUserCount = userDAO.count();

    String view = controller.userInfo(registration, result, map, null, status, mockRequest);
    Assert.assertTrue(result.hasErrors());
    Assert.assertEquals("register.userinfo", view);
    List<FieldError> fieldErrorList = result.getFieldErrors();
    int errorMessage = 0;
    for (FieldError fieldError : fieldErrorList) {
        if ("javax.validation.constraints.Size.message".equals(fieldError.getCode())) {
            errorMessage++;
        } else if ("javax.validation.constraints.MinimumSize.message".equals(fieldError.getCode())) {
            errorMessage++;
        }
    }
    Assert.assertTrue(errorMessage == 2);
    int afterUserCount = userDAO.count();
    Assert.assertEquals(afterUserCount, beforeUserCount);
}

From source file:edu.psu.citeseerx.myciteseer.domain.logic.AccountValidator.java

/**
 * @param errors/*  ww w.j  a v  a  2  s . c  o  m*/
 * @param fieldName
 * @return The error from the message source for fieldName if any
 */
protected String getValidationMessage(Errors errors, String fieldName) {

    String message = "";
    FieldError fieldError = errors.getFieldError(fieldName);

    if (fieldError != null) {
        message = messageSource.getMessage(fieldError.getCode(), null, "This field is invalid", Locale.ENGLISH);
    }

    return message;

}

From source file:edu.psu.citeseerx.myciteseer.domain.logic.CollectionValidator.java

protected String getValidationMessage(Errors errors, String fieldName) {

    String message = "";
    FieldError fieldError = errors.getFieldError(fieldName);

    if (fieldError != null) {
        message = messageSource.getMessage(fieldError.getCode(), null, "This field is invalid", Locale.ENGLISH);
    }/*ww  w . j  a  va 2s .  co  m*/

    return message;

}

From source file:fi.hsl.parkandride.front.ExceptionHandlers.java

@ExceptionHandler(BindException.class)
public ResponseEntity<Map<String, Object>> bindException(HttpServletRequest request, BindException ex) {
    List<Violation> violations = new ArrayList<>();
    for (FieldError fieldError : ex.getFieldErrors()) {
        violations.add(/*from  w  w  w.ja v a  2 s  .c  o  m*/
                new Violation(fieldError.getCode(), fieldError.getField(), fieldError.getDefaultMessage()));
    }
    return handleError(request, BAD_REQUEST, ex, "Invalid request parameters", violations);
}

From source file:gov.nih.nci.cabig.caaers.web.fields.InputFieldTest.java

public void testErrorWhenRequiredFieldIsNotPresent() throws Exception {
    bean.setName(null);// w w  w  .  j a  va  2  s. com
    field.setRequired(true);
    field.validate(wrappedBean, errors);
    assertEquals("Wrong number of errors", 1, errors.getErrorCount());
    assertEquals("Wrong number of field errors", 1, errors.getFieldErrorCount());
    FieldError actualError = errors.getFieldError("name");
    assertNotNull("Error is on wrong property", actualError);
    assertEquals("Wrong key for error", "REQUIRED", actualError.getCode());
    assertEquals("Wrong default message for error", "<b>Missing:</b> &quot;Nomen&quot;",
            actualError.getDefaultMessage());
}

From source file:it.cilea.osd.common.validation.BaseValidator.java

/**
 * Get the FieldError validation message from the underlying MessageSource for the given fieldName.
 *
 * @param errors The validation errors.//  w  w  w.  j  a  v a  2 s  .c o m
 * @param fieldName The fieldName to retrieve the error message from.
 * @return The validation message or an empty String.
 */
protected String getValidationMessage(Errors errors, String fieldName) {
    String message = "";
    FieldError fieldError = errors.getFieldError(fieldName);
    if (fieldError != null) {
        WebContext ctx = WebContextFactory.get();
        MessageSource messageSource = WebApplicationContextUtils
                .getWebApplicationContext(ctx.getServletContext());
        String errore = fieldError.getCode();
        //il messaggio deve essere ripescato dal resource bundle
        ResourceBundle resourceBundle = ResourceBundle.getBundle(Constants.BUNDLE_KEY,
                ctx.getHttpServletRequest().getLocale());
        message = resourceBundle.getString(errore);
    }
    return message;
}