javax.validation.Validation Java Examples

The following examples show how to use javax.validation.Validation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ValidatorTest.java    From ueboot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void test(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    ReqBody reqBody = new ReqBody();
    Set<ConstraintViolation<Object>> validRetval = validator.validate(reqBody);
    StringBuilder sb = new StringBuilder();
    // 校验失败
    if (!validRetval.isEmpty()) {
        for (ConstraintViolation<Object> t : validRetval) {
            sb.append(t.getPropertyPath()).append(t.getMessage()).append(",");
        }
    }
    String checkError = sb.toString();
    System.out.println(checkError);
}
 
Example #2
Source File: InfoBean.java    From tomee with Apache License 2.0 6 votes vote down vote up
@PostConstruct
protected void showWelcomeMessage() {
    String versionString = ClassUtils.getJarVersion(InfoBean.class);

    if (versionString != null) {
        this.applicationMessageVersionInfo = " (v" + versionString + ")";
    }

    this.beanValidationVersion =
            ClassUtils.getJarVersion(Validation.buildDefaultValidatorFactory().getValidator().getClass());

    this.jpaVersion =
            ClassUtils.getJarVersion(Persistence.createEntityManagerFactory("demoApplicationPU").getClass());

    if (!ProjectStage.IntegrationTest.equals(this.projectStage)) {
        this.messageContext.message().text("{msgWelcome}").add();
    }
}
 
Example #3
Source File: T212MapVerifyTest.java    From hj-t212-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataLevelFalse(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Map m = dataLevel.entrySet()
            .stream()
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    kv -> kv.getValue() + "---------------"
            ));
    T212Map t212Map = T212Map.createDataLevel(m);

    Set<ConstraintViolation<T212Map>> e2005 = validator.validate(t212Map,Default.class,
            VersionGroup.V2005.class);
    assertTrue(e2005.size() > 0);
    Set<ConstraintViolation<T212Map>> e2017 = validator.validate(t212Map,Default.class,
            VersionGroup.V2017.class);
    assertTrue(e2017.size() > 0);
}
 
Example #4
Source File: CardLastFourDigitsValidatorTest.java    From pay-publicapi with MIT License 6 votes vote down vote up
@BeforeClass
public static void setUpValidator() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    validator = factory.getValidator();

    builder
            .withAmount(1200)
            .withDescription("Some description")
            .withReference("Some reference")
            .withProcessorId("1PROC")
            .withProviderId("1PROV")
            .withCardExpiry("01/99")
            .withCardType("visa")
            .withFirstSixDigits("123456")
            .withPaymentOutcome(new PaymentOutcome("success"));
}
 
Example #5
Source File: Application.java    From tutorials with MIT License 6 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
public void placeOrder(String productId, int amount) throws Exception {

    String orderId = UUID.randomUUID()
        .toString();
    Inventory inventory = inventoryRepository.findOne(productId);
    inventory.setBalance(inventory.getBalance() - amount);
    inventoryRepository.save(inventory);
    Order order = new Order();
    order.setOrderId(orderId);
    order.setProductId(productId);
    order.setAmount(new Long(amount));
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<Order>> violations = validator.validate(order);
    if (violations.size() > 0)
        throw new Exception("Invalid instance of an order.");
    orderRepository.save(order);

}
 
Example #6
Source File: TestNcssParams.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@BeforeClass
public static void setUp() {
  ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
  validator = factory.getValidator();

  Class c = resolver.getClass();
  InputStream is = c.getResourceAsStream("/ValidationMessages.properties");
  if (is != null) {
    try {
      resolver.load(is);
      resolver.list(System.out);
      is.close();
    } catch (IOException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
    }
  }
}
 
Example #7
Source File: ViewController.java    From hibernate-demos with Apache License 2.0 6 votes vote down vote up
public void initialize(final URL location, final ResourceBundle resources) {
    final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    final Model model = new Model();
    final Validator validator = factory.getValidator();

    nameField.textProperty().bindBidirectional(model.nameProperty());
    model.countProperty().bind(Bindings.createObjectBinding(() ->
                    countSlider.valueProperty().intValue()
            , countSlider.valueProperty()));

    validateButton.setOnAction(e -> {
        final Set<ConstraintViolation<Model>> violations = validator.validate(model);



        validateMessageLabel.setText(violations.stream().map(v -> v.getMessage()).reduce("", (a, b) -> a + b));
    });
}
 
Example #8
Source File: ImageCatalogV4BaseTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws NoSuchFieldException, IllegalAccessException {
    Configuration<?> cfg = Validation.byDefaultProvider().configure();
    cfg.messageInterpolator(new ParameterMessageInterpolator());
    validator = cfg.buildValidatorFactory().getValidator();

    for (Entry<String, Object> entry : Map.of("HTTP_CONTENT_SIZE_VALIDATOR", httpContentSizeValidator, "HTTP_HELPER", httpHelper).entrySet()) {
        Field field = ReflectionUtils.findField(ImageCatalogValidator.class, entry.getKey());
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, entry.getValue());
    }

    when(httpContentSizeValidator.isValid(anyString(), any(ConstraintValidatorContext.class))).thenReturn(true);
    when(statusType.getFamily()).thenReturn(Family.SUCCESSFUL);
}
 
Example #9
Source File: Jsr303Test.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
    String vaadinPackagePrefix = VaadinServlet.class.getPackage()
            .getName();
    vaadinPackagePrefix = vaadinPackagePrefix.substring(0,
            vaadinPackagePrefix.lastIndexOf('.'));
    if (name.equals(UnitTest.class.getName())) {
        super.loadClass(name);
    } else if (name
            .startsWith(Validation.class.getPackage().getName())) {
        throw new ClassNotFoundException();
    } else if (name.startsWith(vaadinPackagePrefix)) {
        String path = name.replace('.', '/').concat(".class");
        URL resource = Thread.currentThread().getContextClassLoader()
                .getResource(path);
        InputStream stream;
        try {
            stream = resource.openStream();
            byte[] bytes = IOUtils.toByteArray(stream);
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return super.loadClass(name);
}
 
Example #10
Source File: App.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void configure() {
    logger.info("init app, name={}, language={}, dir={}", name(), language(), dir());
    binder = new ModuleBinder();

    binder.bind(App.class).toInstance(this);
    binder.bind(MessageBundle.class).toInstance(message());

    binder.bind(Configuration.class).toInstance(Validation.byDefaultProvider().configure()
        .messageInterpolator(new MessageInterpolatorImpl())
        .addProperty("hibernate.validator.fail_fast", "true"));
    register(ValidationFeature.class);

    JacksonJaxbJsonProvider jacksonProvider = new JacksonJaxbJsonProvider();
    jacksonProvider.setMapper(JSON.OBJECT_MAPPER);
    register(jacksonProvider);
    register(JacksonFeature.class);

    register(binder.raw());
    register(new DefaultContainerLifecycleListener(this));

    register(new AppEventListener());
    register(DefaultExceptionMapper.class);

    validate();

    for (String moduleName : orderedModules()) {
        ModuleNode moduleNode = moduleNode(moduleName).orElseThrow();
        if (moduleNode.isOverrided()) {
            moduleNode.status = ModuleStatus.CONFIGURED;
        } else {
            try {
                Stopwatch w = Stopwatch.createStarted();
                configure(moduleNode.module);
                moduleNode.status = ModuleStatus.CONFIGURED;
            } catch (Exception e) {
                throw new ApplicationException("failed to install module {}, type={}", moduleName, moduleNode.module.getClass().getCanonicalName(), e);
            }
        }
    }
}
 
Example #11
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
public static JsonNode parseMetrics(String jsonString, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{
	 List<String> violation_message = new ArrayList<String>();
	 ObjectNode result = new_mapper.createObjectNode();
	 result.put("valid", false);
	 //JavaType javaType = getCollectionType(ArrayList.class, HistoryData.class);
	 //new_mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
	 logger.info("Received metrics: " + jsonString);
	 Metrics metrics = new_mapper.readValue(jsonString, Metrics.class);
	 
	 ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
	 Locale locale = LocaleUtil.getLocale(httpServletRequest);
	 MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale);
	 Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator();
	 Set<ConstraintViolation<Metrics>> set = validator.validate(metrics);
	 if (set.size() > 0 ){
		 for (ConstraintViolation<Metrics> constraintViolation : set) {
			 violation_message.add(constraintViolation.getMessage());
		 }
		 result.set("violation_message", new_mapper.valueToTree(violation_message));
		 return result;
	 }
         

	 //additional data manipulation
   	 String new_json = metrics.transformOutput();
	 result.put("valid", true);
	 result.put("new_json", new_json);
	 return result;
}
 
Example #12
Source File: LanguageTagValidatorTest.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
private Set<ConstraintViolation<Entity>> getViolations(String lang) {
    Entity entity = new Entity();
    entity.lang = lang;
    Validator validator = Validation.buildDefaultValidatorFactory()
            .getValidator();

    return validator.validate(entity);
}
 
Example #13
Source File: BeanValidationInterceptorTest.java    From hibersap with Apache License 2.0 5 votes vote down vote up
@Test
public void throwsConstraintViolationExceptionWhoseMessageContainsNameOfNonValidatingClass() {
    final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    final BeanValidationInterceptor interceptor = new BeanValidationInterceptor(validatorFactory);

    assertThatThrownBy(() -> interceptor.beforeExecution(new TestObject()))
            .isInstanceOf(ConstraintViolationException.class)
            .hasMessageContaining("org.hibersap.interceptor.impl.BeanValidationInterceptorTest$InnerObject");
}
 
Example #14
Source File: Validations.java    From osiris with Apache License 2.0 5 votes vote down vote up
public void checkCollection(Collection<?> collection){
	checkIsNotNull(collection);
	checkCollectionIsNotEmpty(collection);
	Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
	for(Object object:collection){
		Set<ConstraintViolation<Object>> validation = validator.validate(object);
		if (validation.size() > 0) {
			throw new InvalidParametersException("Passed collection is not correct");
		}
	}
}
 
Example #15
Source File: PersonModelTest.java    From blog with MIT License 5 votes vote down vote up
@Test
public void test_WHEN_valid_GIVEN_invalid_model_THEN_error() {

	// GIVEN

	PersonModel person = new PersonModel( //
			null, //
			"", //
			null);

	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();

	// WHEN

	Set<ConstraintViolation<PersonModel>> constraintViolations = validator
			.validate(person);

	// THEN

	assertThat(constraintViolations) //
			.hasSize(3) //
			.haveExactly(2, notNullCondition) //
			.haveExactly(1, notEmptyCondition);
}
 
Example #16
Source File: AuthorizationTests.java    From OpenESPI-Common-java with Apache License 2.0 5 votes vote down vote up
@Test
public void isInvalid() throws Exception {
	Validator validator = Validation.buildDefaultValidatorFactory()
			.getValidator();

	Authorization authorization = new Authorization();

	Set<ConstraintViolation<Authorization>> violations = validator
			.validate(authorization);

	assertThat(violations, is(not(empty())));
}
 
Example #17
Source File: PaymentValidate.java    From aaden-pay with Apache License 2.0 5 votes vote down vote up
private void validMust(PayRequest request) throws Exception {
	Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
	validator.validate(request.getMust());
	Set<ConstraintViolation<PayMustData>> validators = validator.validate(request.getMust());
	for (ConstraintViolation<PayMustData> constraintViolation : validators) {
		throw new Exception(constraintViolation.getMessage());
	}
}
 
Example #18
Source File: BeanValidator.java    From Guice-configuration with Apache License 2.0 5 votes vote down vote up
public BeanValidator() {
    ValidatorFactory f = null;
    try {
        f = Validation.buildDefaultValidatorFactory();
        log.debug("Validation factory builder found");
    } catch (ValidationException e) {
        log.debug("No validation factory found in classpath");
    } finally {
        factory = f;
    }
}
 
Example #19
Source File: ValidatorContextResolver.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public GeneralValidator getContext(final Class<?> type) {
    final ResourceBundleLocator resourceBundleLocator = new PlatformResourceBundleLocator("messages");
    final MessageInterpolator messageInterpolator = new ResourceBundleMessageInterpolator(resourceBundleLocator);
    final Configuration<?> config = Validation.byDefaultProvider().configure()
        .messageInterpolator(messageInterpolator);
    final BootstrapConfiguration bootstrapConfiguration = config.getBootstrapConfiguration();
    final boolean isExecutableValidationEnabled = bootstrapConfiguration.isExecutableValidationEnabled();
    final Set<ExecutableType> defaultValidatedExecutableTypes = bootstrapConfiguration
        .getDefaultValidatedExecutableTypes();

    return new GeneralValidatorImpl(validatorFactory, isExecutableValidationEnabled,
        defaultValidatedExecutableTypes);
}
 
Example #20
Source File: MessageConsumer.java    From code-examples with MIT License 5 votes vote down vote up
public void consumeStringMessage(String messageString) throws IOException {
  logger.info("Consuming message '{}'", messageString);
  UserCreatedMessage message = objectMapper.readValue(messageString, UserCreatedMessage.class);
  Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
  Set<ConstraintViolation<UserCreatedMessage>> violations = validator.validate(message);
  if(!violations.isEmpty()){
    throw new ConstraintViolationException(violations);
  }
  // pass message into business use case
}
 
Example #21
Source File: InjectedValidationTest.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Before
public void initValidator()
{
    this.validator = Validation.byDefaultProvider().configure()
            .constraintValidatorFactory(new CDIAwareConstraintValidatorFactory())
            .buildValidatorFactory().getValidator();
}
 
Example #22
Source File: ValidationModule.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
public Validator getValidator() {
    return Validation.byProvider(ApacheValidationProvider.class)
            .configure()
            .addMapping(Reflection.loaderFromThreadOrClass(this.getClass()).getResourceAsStream(VALIDATION_MAPPING_FILE))
            .buildValidatorFactory()
            .getValidator();
}
 
Example #23
Source File: ProgrammaticallyValidatingService.java    From code-examples with MIT License 5 votes vote down vote up
public void validateInput(Input input) {
  ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
  Validator validator = factory.getValidator();
  Set<ConstraintViolation<Input>> violations = validator.validate(input);
  if (!violations.isEmpty()) {
    throw new ConstraintViolationException(violations);
  }
}
 
Example #24
Source File: OpenAPIUtils.java    From swagger-aem with Apache License 2.0 5 votes vote down vote up
public static <T> void validate(T obj) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
    if (constraintViolations.size() > 0) {
        StringBuilder errors = new StringBuilder();
        for (ConstraintViolation<T> contraintes : constraintViolations) {
            errors.append(String.format("%s.%s %s\n",
            contraintes.getRootBeanClass().getSimpleName(),
            contraintes.getPropertyPath(),
            contraintes.getMessage()));
        }
        throw new RuntimeException("Bean validation : " + errors);
    }
}
 
Example #25
Source File: BeanValidation.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor
 */
public BeanValidation()
{
   Configuration configuration = Validation.byDefaultProvider().configure();
   Configuration<?> conf = configuration.traversableResolver(new JCATraversableResolver());

   validatorFactory = conf.buildValidatorFactory();
   validator = validatorFactory.getValidator();
}
 
Example #26
Source File: WorkflowDefValidatorTest.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Test
public void testWorkflowSchemaVersion1() {
	WorkflowDef workflowDef = new WorkflowDef();//name is null
	workflowDef.setSchemaVersion(3);
	workflowDef.setName("test_env");
	workflowDef.setOwnerEmail("[email protected]");

	WorkflowTask workflowTask = new WorkflowTask();

	workflowTask.setName("t1");
	workflowTask.setWorkflowTaskType(TaskType.SIMPLE);
	workflowTask.setTaskReferenceName("t1");

	Map<String, Object> map = new HashMap<>();
	map.put("blabla", "");
	workflowTask.setInputParameters(map);

	workflowDef.getTasks().add(workflowTask);

	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();
	Set<ConstraintViolation<Object>> result = validator.validate(workflowDef);
	assertEquals(1, result.size());

	List<String> validationErrors = new ArrayList<>();
	result.forEach(e -> validationErrors.add(e.getMessage()));

	assertTrue(validationErrors.contains("workflowDef schemaVersion: 2 is only supported"));
}
 
Example #27
Source File: EmailValidatorTest.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected Validator createValidator() {
    return Validation
            .byProvider(HibernateValidator.class)
            .configure()
            .buildValidatorFactory()
            .getValidator();
}
 
Example #28
Source File: PageRepositoryIT.java    From bonita-ui-designer with GNU General Public License v2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    pagesPath = Paths.get(temporaryFolder.getRoot().getPath());
    persister = spy(new DesignerConfig().pageFileBasedPersister());
    loader = spy(new DesignerConfig().pageFileBasedLoader());

    repository = new PageRepository(
            pagesPath,
            persister,
            loader,
            new BeanValidator(Validation.buildDefaultValidatorFactory().getValidator()),
            mock(Watcher.class));
}
 
Example #29
Source File: IdentifiedObjectValidationTests.java    From OpenESPI-Common-java with Apache License 2.0 5 votes vote down vote up
@Test
public void isValid() throws Exception {
	Validator validator = Validation.buildDefaultValidatorFactory()
			.getValidator();

	IdentifiedObject identifiedObject = new IdentifiedObject();
	identifiedObject.setUUID(UUID.randomUUID());

	Set<ConstraintViolation<IdentifiedObject>> violations = validator
			.validate(identifiedObject);

	assertTrue(violations.isEmpty());
}
 
Example #30
Source File: ConstraintViolationsMvcBindingTest.java    From krazo with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize our {@link Validator} instance.
 */
@BeforeClass
public static void initValidator() {

    final ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
    validator = vf.getValidator();

}