public void create(T entity) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity); if(constraintViolations.size() > 0){ Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator(); while(iterator.hasNext()){ ConstraintViolation<T> cv = iterator.next(); System.err.println(cv.getRootBeanClass().getName()+"."+cv.getPropertyPath() + " " +cv.getMessage()); System.err.println(cv.getRootBeanClass().getSimpleName()+"."+cv.getPropertyPath() + " " +cv.getMessage()); } }else{ getEntityManager().persist(entity); } }
public static void main(String[] args) throws NoSuchMethodException, SecurityException { AutoRunHelper.run(App.class); // 测试参数校验 App app = new App(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); ExecutableValidator executableValidator = factory.getValidator().forExecutables(); Method method = App.class.getMethod("showEmail", String.class); Object[] parameterValues = {"email"}; Set<ConstraintViolation<App>> violations = executableValidator.validateParameters(app, method, parameterValues); String message = violations.iterator().hasNext() ? violations.iterator().next().getMessage() : ""; System.out.println("values:" + parameterValues[0].toString() + " size: " + violations.size() + " msg:" + message); Object[] parameterValues2 = {"abc"}; violations = executableValidator.validateParameters(app, method, parameterValues2); message = violations.iterator().hasNext() ? violations.iterator().next().getMessage() : ""; System.out.println("values:" + parameterValues2[0].toString() + " size: " + violations.size() + " msg:" + message); }
@Test public void loads() { Pessoa pessoa = new Pessoa(); pessoa.setNome("João da Silva"); pessoa.setCpf("12345678901"); pessoa.setTelefone("(11)3266-4455"); pessoa.setEndereco("Rua A, 123, Bananal, Guarulhos - SP"); Check check = new SafeguardCheck(); /*Validação manual usando a interface Check*/ Check resultados = check.elementOf(pessoa).validate(); int quantidadeDeElementosInvalidos = resultados.getInvalidElements().size(); boolean temErro = resultados.hasError(); /*Validação pelo provedor de validação, usando javax.validation*/ ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); javax.validation.Validator validator = factory.getValidator(); Set<ConstraintViolation<Pessoa>> violacoes = validator.validate(pessoa, Default.class); Assert.assertEquals(1, quantidadeDeElementosInvalidos); Assert.assertEquals(true, temErro); Assert.assertEquals(1, violacoes.size()); }
public static void main(String[] args) { String src = "src.org/hack/controller"; src = src.replaceAll("/", File.separator + File.separator); System.out.println(src); System.out.println("src\\org\\hack\\controller"); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); System.out.println(factory.getMessageInterpolator().getClass()); Validator validator = factory.getValidator(); Blog blog = new Blog("1", "2121", "212", new Date(), 2); Set<ConstraintViolation<Blog>> constraintViolations = validator.validate(blog); System.out.println(validator.getClass()); for (ConstraintViolation<Blog> c : constraintViolations) { System.out.println(c.getInvalidValue() + ":" + c.getMessage()); } }
public List<Account> getAccounts() { final Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); final ObjectMapper mapper = new ObjectMapper() .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); List<Account> accounts = null; try { accounts = mapper.readValue(rulesFile, new TypeReference<List<Account>>() {}); if (accounts != null) { accounts.forEach((account) -> { final Set<ConstraintViolation<Account>> accountViolations = validator.validate(account); if (accountViolations.size() > 0) { throw new AccountValidationException(accountViolations); } account.getRules().sort((o1, o2) -> o1.getType().compareTo(o2.getType())); }); } } catch (IOException ex) { Logger.getLogger(AccountService.class.getName()).log(Level.SEVERE, null, ex); } return accounts; }
@Test public void testMapElementAttributeNotNull() { ProjectData data = new ProjectData(); data.setValue(null); // violation Project project = new Project(); project.setId(1L); project.setName("test"); project.setDataMap(new LinkedHashMap()); project.getDataMap().put("someKey", data); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); try { projectRepo.create(project); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); Assert.assertEquals(1, violations.size()); ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next(); Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate()); Assert.assertEquals("dataMap[someKey].value", violation.getPropertyPath().toString()); Assert.assertNotNull(violation.getMessage()); Assert.assertEquals("/data/attributes/dataMap/someKey/value", violation.getErrorData().getSourcePointer()); } }
@Override public void validate(Object entity) throws HttpException { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> violations = validator.validate(entity); if (!violations.isEmpty()) { List<ConstraintViolationDescription> errors = new ArrayList<>(); ConstraintViolationResponseError error = new ConstraintViolationResponseError(); error.setMessage(UNPROCESSABLE_ENTITY_MESSAGE); for (ConstraintViolation<Object> violation : violations) { String attribute = violation.getPropertyPath().toString(); String message = violation.getMessage(); errors.add(new ConstraintViolationDescription(message, attribute)); } error.setErrors(errors); throw new UnprocessableEntityException(error); } }
@Override public void afterPropertiesSet() { if (this.validatorFactory == null) { this.validatorFactory = Validation.buildDefaultValidatorFactory(); } ValidatorContext validatorContext = this.validatorFactory.usingContext(); MessageInterpolator targetInterpolator = this.messageInterpolator; if (targetInterpolator == null) { targetInterpolator = this.validatorFactory.getMessageInterpolator(); } validatorContext.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator)); if (this.traversableResolver != null) { validatorContext.traversableResolver(this.traversableResolver); } setTargetValidator(validatorContext.getValidator()); }
/** * Validoi annettu bean:in siinä annettuja BeanValidation annotaatio-ehtoja vasten. * * @param bean * Validoitava bean. * @return Listaus löytyneistä validointivirheistä. */ public Set<ConstraintViolation<T>> doValidation(T bean) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> errors = validator.validate(bean); return errors; }
public static <T> void validate(T object) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> validatorSet = validator.validate(object); validatorSet.forEach(cv -> { throw new BeanValidationException(cv.getPropertyPath() + " - " + cv.getMessage()); }); }
@SuppressWarnings({ "unchecked", "rawtypes" }) public JValidator(URL url) { this.clazz = ReflectUtils.forName(url.getServiceInterface()); String jvalidation = url.getParameter("jvalidation"); ValidatorFactory factory; if (jvalidation != null && jvalidation.length() > 0) { factory = Validation.byProvider((Class)ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory(); } else { factory = Validation.buildDefaultValidatorFactory(); } this.validator = factory.getValidator(); }
@Inject public FileBackedTransactionConfigDataSource(ConfigConfiguration configuration, ConfigurationFactoryFactory<TransactionConfigEntityData> configurationFactoryFactory, ObjectMapper objectMapper) { super( configuration, configurationFactoryFactory.create(TransactionConfigEntityData.class, Validation.buildDefaultValidatorFactory().getValidator(), objectMapper, "hub"), TRANSACTIONS_DATA_DIRECTORY ); }
@Inject public FileBackedCountriesConfigDataSource( ConfigConfiguration configuration, ConfigurationFactoryFactory<CountriesConfigEntityData> configurationFactoryFactory, ObjectMapper objectMapper) { super( configuration, configurationFactoryFactory.create(CountriesConfigEntityData.class, Validation.buildDefaultValidatorFactory().getValidator(), objectMapper, "hub"), COUNTRIES_DATA_DIRECTORY ); }
@Inject public FileBackedMatchingServiceConfigDataSource( ConfigConfiguration configuration, ConfigurationFactoryFactory<MatchingServiceConfigEntityData> configurationFactoryFactory, ObjectMapper objectMapper) { super( configuration, configurationFactoryFactory.create(MatchingServiceConfigEntityData.class, Validation.buildDefaultValidatorFactory().getValidator(), objectMapper, "hub"), MATCHING_SERVICE_DATA_DIRECTORY ); }
@Inject public FileBackedIdentityProviderConfigDataSource( ConfigConfiguration configuration, ConfigurationFactoryFactory<IdentityProviderConfigEntityData> configurationFactoryFactory, ObjectMapper objectMapper) { super( configuration, configurationFactoryFactory.create(IdentityProviderConfigEntityData.class, Validation.buildDefaultValidatorFactory().getValidator(), objectMapper, "hub"), IDENTITY_PROVIDER_DATA_DIRECTORY ); }
@BeforeClass public static void setup() { gson = new GsonBuilder().serializeNulls() .create(); validator = Validation.buildDefaultValidatorFactory() .getValidator(); }
@Override public List<ValidationMessage> validate(MzTab mzTab) { List<ValidationMessage> list = new LinkedList<>(); ValidatorFactory validatorFactory = Validation.byDefaultProvider() .configure() .buildValidatorFactory(); javax.validation.Validator validator = validatorFactory.getValidator(); Set<ConstraintViolation<MzTab>> violations = validator.validate(mzTab); for(ConstraintViolation<MzTab> violation:violations) { list.add(new ValidationMessage().message(getPathLocatorString( violation)+": "+violation.getMessage()).messageType(ValidationMessage.MessageTypeEnum.ERROR)); } return list; }
@Test public void testDefaultMetadataBeanValidation() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<MzTab>> violations = validator.validate( createTestFile()); for (ConstraintViolation<MzTab> violation : violations) { System.err.println("Validation error at " + violation. getPropertyPath(). toString() + ": " + violation.getMessage()); } }
@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); }
public IntegrationTest() { final DefaultConstraintMapping mapping = new DefaultConstraintMapping(); mapping.constraintDefinition(UniqueProperty.class).validatedBy(UniqnenessValidator.class); final ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure() .addMapping(mapping).buildValidatorFactory(); validator = validatorFactory.getValidator(); }
@Test public void testValid() { TextField text = new TextField(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Binder<MyEntity> binder = new BeanValidationBinder<>(MyEntity.class); binder.forField(text).withNullRepresentation("").bind("text"); MyEntity t = new MyEntity(); // valid t.setText("bla"); binder.setBean(t); assertTrue(validator.validate(t).isEmpty()); assertTrue(binder.validate().isOk()); text.setValue(""); assertNull(t.getText()); /* * // invalid t.setText(""); binder.setBean(t); * assertFalse(validator.validate(t).isEmpty()); * assertFalse(binder.validate().isOk()); * * t.setText(null); binder.setBean(t); * assertTrue(validator.validate(t).isEmpty()); * assertTrue(binder.validate().isOk()); */ }
@Before public void setup() { metadataService = mock(MetadataService.class); flowPersistenceProvider = mock(FlowPersistenceProvider.class); snapshotSerializer = mock(VersionedProcessGroupSerializer.class); final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); validator = validatorFactory.getValidator(); registryService = new RegistryService(metadataService, flowPersistenceProvider, snapshotSerializer, validator); }
/** * Valide un bean * * @param bean * @throws CustomException */ public static <T> Boolean validateBean(T bean, Logger logger) { logger.debug(" ***VALIDATION*** : " + bean); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> constraintViolations = validator.validate(bean); if (constraintViolations != null && constraintViolations.size() > 0) { for (ConstraintViolation<?> violation : constraintViolations) { logger.debug(" *** " + violation.getPropertyPath().toString() + " : " + violation.getMessage()); } return false; } return true; }
/** Valide un bean d'individu * @param ind * @throws CustomException */ public void validateIndividuBean(Individu ind) throws CustomException{ ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Individu>> constraintViolations = validator.validate(ind); if (constraintViolations!=null && constraintViolations.size() > 0) { String erreur = ""; for (ConstraintViolation<?> violation : constraintViolations) { erreur += (" *** "+ violation.getPropertyPath().toString() + " : " + violation.getMessage()); } throw new CustomException(applicationContext.getMessage("droitprofil.individu.error", null, UI.getCurrent().getLocale())+" : "+erreur); } }
public MowerPosition(int x, int y, Direction direction, Lawn lawn) { this.x = x; this.y = y; this.direction = direction; this.lawn = lawn; this.vf = Validation.buildDefaultValidatorFactory(); }
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()); } }
private void validCash(PayRequest request) throws Exception { Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); validator.validate(request.getCash()); Set<ConstraintViolation<PayCashData>> validators = validator.validate(request.getCash()); for (ConstraintViolation<PayCashData> constraintViolation : validators) { throw new Exception(constraintViolation.getMessage()); } }
private void validRecharge(PayRequest request) throws Exception { if (request.getSys().getPayType() == PayType.GATEWAY) return; Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); validator.validate(request.getRecharge()); Set<ConstraintViolation<PayRechargeData>> validators = validator.validate(request.getRecharge()); for (ConstraintViolation<PayRechargeData> constraintViolation : validators) { throw new Exception(constraintViolation.getMessage()); } }
@Before public void init() { emFactory = Persistence.createEntityManagerFactory("DB"); em = emFactory.createEntityManager(); valFactory = Validation.buildDefaultValidatorFactory(); validator = valFactory.getValidator(); }
public void initialize(Configuration cfg) { if ( !initialized ) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Properties props = cfg.getProperties(); init( factory, props ); } }
public EntityManagerImpl(SqlSessionFactory sqlSessionFactory) { super(sqlSessionFactory); try { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); this.validator = factory.getValidator(); } catch (Exception e) { logger.warn("Unable to create validator"); } }
@Before public void initTestCase() { validator = Validation.buildDefaultValidatorFactory().getValidator(); partOfSpeechRepository = mock(PartOfSpeechRepository.class); partOfSpeechService = new PartOfSpeechServiceBean(); partOfSpeechService.validator = validator; partOfSpeechService.partOfSpeechRepository = partOfSpeechRepository; }
@Before public void initTestCase() { validator = Validation.buildDefaultValidatorFactory().getValidator(); repository = mock(LocalisedStringRepository.class); service = new LocalisedStringServiceBean(); service.validator = validator; service.repository = repository; }
@Before public void initTestCase() { validator = Validation.buildDefaultValidatorFactory().getValidator(); lexiconRepository = mock(LexiconRepository.class); lexiconService = new LexiconServiceBean(); lexiconService.validator = validator; lexiconService.lexiconRepository = lexiconRepository; }
public static <E> void checkParam(E obj, Class mafExceptionClass, Integer respCode, Class... validateGroup) throws Exception { ValidatorFactory vf = Validation.buildDefaultValidatorFactory(); Validator validator = vf.getValidator(); Set<ConstraintViolation<Object>> set = validator.validate(obj, validateGroup); for(ConstraintViolation<Object> cv : set) { Constructor constructor = mafExceptionClass.getConstructor(int.class, String.class); MafiaException mafException = (MafiaException) constructor.newInstance(respCode, cv.getMessage()); throw mafException; } }
@Before public void initTestCase() { validator = Validation.buildDefaultValidatorFactory().getValidator(); repository = mock(RelationTypeRepository.class); service = new RelationTypeServiceBean(); service.validator = validator; service.relationTypeRepository = repository; }