Java Code Examples for javax.validation.Validation

The following examples show how to use javax.validation.Validation. These examples are extracted from open source projects.
Example 1
Project: flow   File: Jsr303Test.java    License: 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 2
Project: blog   File: PersonModelTest.java    License: MIT License 6 votes vote down vote up
@Test
public void test_WHEN_valid_GIVEN_valid_model_THEN_ok_no_errors() {

	// GIVEN

	PersonModel person = new PersonModel( //
			"Kim", //
			"Kardashian", //
			new GregorianCalendar(1980, Calendar.OCTOBER, 21));
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();

	// WHEN

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

	// THEN

	assertThat(constraintViolations).isEmpty();
}
 
Example 3
Project: tds   File: TestNcssParams.java    License: 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 4
Project: hibernate-demos   File: ViewController.java    License: 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 5
Project: ueboot   File: ValidatorTest.java    License: 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 6
Project: cloudbreak   File: ImageCatalogV4BaseTest.java    License: 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 7
Project: springboot-guide   File: PersonControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 手动校验对象,很多场景下需要使用这种方式
 */
@Test
public void check_person_manually() {

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Person person = new Person();
    person.setSex("Man22");
    person.setClassId("82938390");
    person.setEmail("SnailClimb");
    Set<ConstraintViolation<Person>> violations = validator.validate(person);
    //output:
    //email 格式不正确
    //name 不能为空
    //sex 值不在可选范围
    for (ConstraintViolation<Person> constraintViolation : violations) {
        System.out.println(constraintViolation.getMessage());
    }
}
 
Example 8
Project: hj-t212-parser   File: T212MapVerifyTest.java    License: 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 9
Project: tomee   File: InfoBean.java    License: 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 10
Project: pay-publicapi   File: CardLastFourDigitsValidatorTest.java    License: 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 11
Project: tutorials   File: Application.java    License: 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 12
Project: blog   File: PersonModelTest.java    License: MIT License 6 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 13
Project: code-examples   File: MessageConsumer.java    License: 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 14
Project: sundrio   File: ValidationUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static Validator createValidator() {
    try {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        return factory.getValidator();
    } catch (ValidationException e) {
        return null;
    }
}
 
Example 15
Project: OpenESPI-Common-java   File: UsagePointValidationTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void isValid() throws Exception {
	Validator validator = Validation.buildDefaultValidatorFactory()
			.getValidator();

	UsagePoint usagePoint = new UsagePoint();
	usagePoint.setMRID("urn:uuid:E8E75691-7F9D-49F3-8BE2-3A74EBF6BFC0");
	usagePoint.setServiceCategory(new ServiceCategory(
			ServiceCategory.ELECTRICITY_SERVICE));

	Set<ConstraintViolation<UsagePoint>> violations = validator
			.validate(usagePoint);

	assertTrue(violations.isEmpty());
}
 
Example 16
Project: circus-train   File: SourceTableTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
  ValidatorFactory config = Validation.buildDefaultValidatorFactory();
  validator = config.getValidator();

  sourceTable.setDatabaseName("databaseName");
  sourceTable.setTableName("tableName");
}
 
Example 17
Project: OpenESPI-Common-java   File: ReadingQualityValidationTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void isValid() throws Exception {
	Validator validator = Validation.buildDefaultValidatorFactory()
			.getValidator();

	ReadingQuality readingQuality = new ReadingQuality();

	Set<ConstraintViolation<ReadingQuality>> violations = validator
			.validate(readingQuality);

	assertTrue(violations.isEmpty());
}
 
Example 18
Project: parsec-libraries   File: ValidCurrencyValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
private Set<ConstraintViolation<Entity>> getViolations(String currency) {
    Entity entity = new Entity();
    entity.currency = currency;
    Validator validator = Validation.buildDefaultValidatorFactory()
            .getValidator();

    return validator.validate(entity);
}
 
Example 19
Project: tutorials   File: ValidatorProducer.java    License: MIT License 5 votes vote down vote up
@Produces
public Validator createValidator() {
    return Validation
      .byDefaultProvider()
      .configure()
      .buildValidatorFactory()
      .getValidator();
}
 
Example 20
Project: openapi-generator   File: OpenAPIUtils.java    License: 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 21
Project: OpenESPI-Common-java   File: ApplicationInformationTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void isInvalid() throws Exception {
	Validator validator = Validation.buildDefaultValidatorFactory()
			.getValidator();

	ApplicationInformation applicationInformation = new ApplicationInformation();

	Set<ConstraintViolation<ApplicationInformation>> violations = validator
			.validate(applicationInformation);

	assertFalse(violations.isEmpty());
}
 
Example 22
Project: dropwizard-metrics-cloudwatch   File: CloudWatchReporterFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void verifyConfigurable() throws Exception {
    ObjectMapper mapper = Jackson.newObjectMapper();

    // dropwizard 0.9.1 changed the validation wiring a bit..
    Class<ValidatedValueUnwrapper> optValidatorClazz = (Class<ValidatedValueUnwrapper>) Class
            .forName("io.dropwizard.validation.valuehandling.OptionalValidatedValueUnwrapper");

    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    if (optValidatorClazz != null) {
        validator = Validation.byProvider(HibernateValidator.class).configure()
                .addValidatedValueHandler(optValidatorClazz.newInstance())
                .buildValidatorFactory().getValidator();
    }

    ConfigurationFactory<CloudWatchReporterFactory> configFactory =
            new ConfigurationFactory<>(CloudWatchReporterFactory.class,
                    validator, mapper, "dw");
    CloudWatchReporterFactory f = configFactory.build(new File(Resources.getResource("cw.yml").getFile()));

    assertEquals("[env=default]", f.getGlobalDimensions().toString());
    assertEquals("us-east-1", f.getAwsRegion());
    assertEquals("a.b", f.getNamespace());
    assertEquals("XXXXX", f.getAwsSecretKey());
    assertEquals("11111", f.getAwsAccessKeyId());
    assertEquals("p.neustar.biz", f.getAwsClientConfiguration().getProxyHost());
    assertNull(f.getAwsClientConfiguration().getProxyUsername());
}
 
Example 23
Project: titus-control-plane   File: TestValidator.java    License: Apache License 2.0 5 votes vote down vote up
public static Validator testValidator(String alias, Object bean) {
    Supplier<EvaluationContext> spelContextFactory = () -> {
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setBeanResolver((ctx, beanName) -> beanName.equals(alias) ? bean : null);
        context.setMethodResolvers(Collections.singletonList(new ReflectiveMethodResolver()));
        return context;
    };

    return Validation.buildDefaultValidatorFactory()
            .usingContext()
            .constraintValidatorFactory(new ConstraintValidatorFactoryWrapper(VerifierMode.Strict, type -> Optional.empty(), spelContextFactory))
            .messageInterpolator(new SpELMessageInterpolator(spelContextFactory))
            .getValidator();
}
 
Example 24
Project: hj-t212-parser   File: T212MapEntryValidDateValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<T212MapEntry>> e1 = validator.validate(T212MapEntry.of("yyyyMMddHHmmss","20180101123010"),TypeGroup.YYYYMMDDhhmmss.class);
    assertTrue(e1.isEmpty());
    Set<ConstraintViolation<T212MapEntry>> e2 = validator.validate(T212MapEntry.of("yyyyMMddHHmmsszzz","20180101123010123"),DataElement.Group.QN.class);
    assertTrue(e2.isEmpty());
}
 
Example 25
Project: jaxrs-beanvalidation-javaee7   File: ValidationConfigurationContextResolver.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get a context of type {@code ValidationConfig} that is applicable to the supplied type.
 *
 * @param type the class of object for which a context is desired
 * @return a context for the supplied type or {@code null} if a context for the supplied type is not available from
 *         this provider.
 */
@Override
public ValidationConfig getContext(Class<?> type) {
    final ValidationConfig config = new ValidationConfig();

    config.setMessageInterpolator(new LocaleSpecificMessageInterpolator(Validation.byDefaultProvider().configure()
            .getDefaultMessageInterpolator()));
    config.setParameterNameProvider(new CustomParameterNameProvider());

    return config;
}
 
Example 26
Project: hj-t212-parser   File: T212MapVerifyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCPDataLevel(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<T212Map>> e2005 = validator.validate(cpDataLevel,Default.class,
            T212MapLevelGroup.CpDataLevel.class, VersionGroup.V2005.class);
    assertTrue(e2005.isEmpty());
    Set<ConstraintViolation<T212Map>> e2017 = validator.validate(cpDataLevel,Default.class,
            T212MapLevelGroup.CpDataLevel.class, VersionGroup.V2017.class);
    assertTrue(e2017.isEmpty());
}
 
Example 27
Project: openapi-generator   File: OpenAPIUtils.java    License: 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 28
Project: lams   File: BeanValidationUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a validator factory
 * @return The factory
 */
public static ValidatorFactory createValidatorFactory()
{
   Configuration configuration = Validation.byDefaultProvider().configure();
   Configuration<?> conf = configuration.traversableResolver(new JCATraversableResolver());

   return conf.buildValidatorFactory();
}
 
Example 29
Project: cuba   File: EmailValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
protected Validator createValidator() {
    return Validation
            .byProvider(HibernateValidator.class)
            .configure()
            .buildValidatorFactory()
            .getValidator();
}
 
Example 30
Project: bonita-ui-designer   File: PageRepositoryIT.java    License: 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 31
Project: OpenESPI-Common-java   File: IdentifiedObjectValidationTests.java    License: 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 32
Project: conductor   File: ValidationModule.java    License: 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 33
Project: krazo   File: ConstraintViolationsMvcBindingTest.java    License: 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();

}
 
Example 34
Project: conductor   File: WorkflowDefValidatorTest.java    License: 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 35
Project: swagger-aem   File: OpenAPIUtils.java    License: 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 36
Project: code-examples   File: ProgrammaticallyValidatingService.java    License: 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 37
Project: jweb-cms   File: App.java    License: 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 38
Project: conductor   File: WorkflowDefConstraintTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testWorkflowTaskName() {
    TaskDef taskDef = new TaskDef();//name is null
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<Object>> result = validator.validate(taskDef);
    assertEquals(2, result.size());
}
 
Example 39
Project: open-Autoscaler   File: BeanValidation.java    License: 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 40
Project: osiris   File: Validations.java    License: 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");
		}
	}
}