Example usage for org.springframework.validation BeanPropertyBindingResult hasErrors

List of usage examples for org.springframework.validation BeanPropertyBindingResult hasErrors

Introduction

In this page you can find the example usage for org.springframework.validation BeanPropertyBindingResult hasErrors.

Prototype

@Override
    public boolean hasErrors() 

Source Link

Usage

From source file:com.kixeye.chassis.transport.websocket.RawWebSocketMessage.java

/**
 * Deserializes the given message.//from  w  w  w.  j a  v  a  2 s  .  c  om
 * 
 * @param action
 * @return
 * @throws Exception
 */
public T deserialize(WebSocketAction action) throws Exception {
    // first deserialize
    T message = null;

    if (messageClass != null) {
        message = serDe.deserialize(new ByteBufferBackedInputStream(rawData), messageClass);
    }

    // then validate
    if (message != null && action.shouldValidatePayload()) {
        SpringValidatorAdapter validatorAdapter = new SpringValidatorAdapter(messageValidator);

        BeanPropertyBindingResult result = new BeanPropertyBindingResult(message, messageClass.getName());

        validatorAdapter.validate(message, result);

        if (result.hasErrors()) {
            throw new MethodArgumentNotValidException(
                    new MethodParameter(action.getMethod(), action.getPayloadParameterIndex()), result);
        }
    }

    return message;
}

From source file:org.oncoblocks.centromere.core.test.DataImportTests.java

@Test
public void validationTest() throws Exception {
    EntrezGene gene = new EntrezGene();
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(gene, gene.getClass().getName());
    validator.validate(gene, bindingResult);
    if (bindingResult.hasErrors()) {
        for (ObjectError error : bindingResult.getAllErrors()) {
            System.out.println(error.toString());
        }/*from  w  w w .  ja v a 2s.co  m*/
    } else {
        fail("Validation did not catch missing field.");
    }
}

From source file:org.openmrs.web.controller.OptionsFormControllerTest.java

@Test
public void shouldRejectEmptyNotificationAddress() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("POST", "");
    request.setParameter("notification", "email");
    request.setParameter("notificationAddress", "");

    HttpServletResponse response = new MockHttpServletResponse();
    ModelAndView modelAndView = controller.handleRequest(request, response);

    BeanPropertyBindingResult bindingResult = (BeanPropertyBindingResult) modelAndView.getModel()
            .get("org.springframework.validation.BindingResult.opts");
    Assert.assertTrue(bindingResult.hasErrors());
}

From source file:org.openmrs.web.controller.OptionsFormControllerTest.java

@Test
public void shouldRejectInvalidNotificationAddress() throws Exception {
    final String incorrectAddress = "gayan@gmail";
    MockHttpServletRequest request = new MockHttpServletRequest("POST", "");
    request.setParameter("notification", "email");
    request.setParameter("notificationAddress", incorrectAddress);

    HttpServletResponse response = new MockHttpServletResponse();
    ModelAndView modelAndView = controller.handleRequest(request, response);

    OptionsForm optionsForm = (OptionsForm) controller.formBackingObject(request);
    assertEquals(incorrectAddress, optionsForm.getNotificationAddress());

    BeanPropertyBindingResult bindingResult = (BeanPropertyBindingResult) modelAndView.getModel()
            .get("org.springframework.validation.BindingResult.opts");
    Assert.assertTrue(bindingResult.hasErrors());
}

From source file:org.oncoblocks.centromere.core.dataimport.GenericRecordProcessor.java

/**
 * {@link RecordProcessor#run(String)}//from   ww  w .j  a va 2  s  . c o  m
 * @param inputFilePath
 * @throws DataImportException
 */
public void run(String inputFilePath) throws DataImportException {
    reader.doBefore(inputFilePath);
    writer.doBefore(this.getTempFilePath(inputFilePath));
    T record = reader.readRecord();
    while (record != null) {
        if (record instanceof DataSetAware)
            ((DataSetAware) record).setDataSetMetadata(dataSet);
        if (validator != null) {
            BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(record,
                    record.getClass().getName());
            validator.validate(record, bindingResult);
            if (bindingResult.hasErrors()) {
                logger.warn(String.format("Record failed validation: %s", record.toString()));
                if (!options.isSkipInvalidRecords()) {
                    throw new DataImportException(bindingResult.toString());
                }
            }
        }
        writer.writeRecord(record);
        record = reader.readRecord();
    }
    writer.doAfter();
    reader.doAfter();
    if (importer != null) {
        importer.importFile(this.getTempFilePath(inputFilePath));
    }
}

From source file:org.jasig.schedassist.web.register.Registration.java

/**
 * Validate schedule related fields.//from   w w w  .  ja v  a  2  s  .co  m
 * 
 * Delegates to a {@link BlockBuilderFormBackingObject}.
 * @param context
 */
public void validateSetSchedule(final ValidationContext context) {
    MessageContext messages = context.getMessageContext();

    BlockBuilderFormBackingObject command = this.toBlockBuilderFormBackingObject();
    BlockBuilderFormBackingObjectValidator validator = new BlockBuilderFormBackingObjectValidator();
    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(command, "registration");
    validator.validate(command, errors);

    if (errors.hasErrors()) {
        for (FieldError error : errors.getFieldErrors()) {
            messages.addMessage(new MessageBuilder().error().source(error.getField())
                    .defaultText(error.getDefaultMessage()).build());
        }
    } else {
        this.scheduleSet = true;
    }
}

From source file:ch.rasc.wampspring.method.PayloadArgumentResolver.java

protected void validate(Message<?> message, MethodParameter parameter, Object target) {
    if (this.validator == null) {
        return;/*from  w  w  w .ja v a2 s  .com*/
    }
    for (Annotation ann : parameter.getParameterAnnotations()) {
        Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
        if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
            Object hints = validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann);
            Object[] validationHints = hints instanceof Object[] ? (Object[]) hints : new Object[] { hints };
            BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target,
                    getParameterName(parameter));
            if (!ObjectUtils.isEmpty(validationHints) && this.validator instanceof SmartValidator) {
                ((SmartValidator) this.validator).validate(target, bindingResult, validationHints);
            } else {
                this.validator.validate(target, bindingResult);
            }
            if (bindingResult.hasErrors()) {
                throw new MethodArgumentNotValidException(message, parameter, bindingResult);
            }
            break;
        }
    }
}

From source file:org.jasig.schedassist.web.register.Registration.java

/**
 * Validate after the preferences related fields have been set.
 * /*from w w w.jav a2  s .c  om*/
 * Delegates to a {@link PreferencesFormBackingObjectValidator}.
 * @param context
 */
public void validateSetPreferences(final ValidationContext context) {
    MessageContext messages = context.getMessageContext();

    PreferencesFormBackingObject command = this.toPreferencesFormBackingObject();

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(command, "registration");
    preferencesValidator.validate(command, errors);

    if (errors.hasErrors()) {
        for (FieldError error : errors.getFieldErrors()) {
            messages.addMessage(new MessageBuilder().error().source(error.getField())
                    .defaultText(error.getDefaultMessage()).build());
        }
    }
}

From source file:org.toobsframework.social.session.registration.ValidateRegistration.java

@Handler
public DispatchContext validateUser(DispatchContext context) throws ValidationException {
    User user = (User) context.getContextObject();

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(user, "user");
    if (user.getFirstName() == null || user.getFirstName().trim().length() == 0) {
        errors.rejectValue("firstName", "first.name.missing", "first name needs to be provided");
    }/*from  w  w  w .j  av a  2s  .c  o m*/
    if (user.getLastName() == null || user.getLastName().trim().length() == 0) {
        errors.rejectValue("lastName", "last.name.missing", "last name needs to be provided");
    }
    if (user.getUserId() == null || user.getUserId().trim().length() == 0) {
        errors.rejectValue("userId", "email.missing", "email needs to be provided");
    }
    if (user.getPassword() == null || user.getPassword().trim().length() < 6) {
        errors.rejectValue("password", "password.too.short", "password needs to be at least 6 characters");
    }

    User existingUser = dao.getUser(user.getUserId());
    if (existingUser != null) {
        errors.reject("user.exists", "user with email " + user.getUserId() + " already exists");
    }
    if (errors.hasErrors()) {
        throw new ValidationException(errors);
    }
    return context;
}

From source file:fragment.web.UsersControllerTest.java

@Test
public void testCreateUserStep2Failed() throws Exception {
    User user = userDAO.find(3L);//w w  w.java  2s. c  o m
    asUser(user);
    UserForm form = new UserForm();
    form.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    com.citrix.cpbm.access.User newUser = form.getUser();
    newUser.setEmail("test@test.com");
    newUser.setUsername("testuser###");
    newUser.setFirstName("firstName");
    newUser.setLastName("lastName");
    Profile profile = profileDAO.findByName("User");
    form.setUserProfile(profile.getId());
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(form, "validation");
    com.citrix.cpbm.access.Tenant proxyTenant = (com.citrix.cpbm.access.Tenant) CustomProxy
            .newInstance(controller.getTenant());
    String view = controller.createUserStepTwo(form, result, proxyTenant, map, new MockHttpServletRequest(),
            new MockHttpSession());
    Assert.assertTrue(result.hasErrors());
    Assert.assertFalse("users.newuserregistration.finish".equals(view));
}