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); } }
@Override protected void onInitialize() { super.onInitialize(); add(new IValidator<T>() { @Override public void validate(IValidatable<T> validatable) { Validator validator = AppLoader.getInstance(Validator.class); for (ConstraintViolation<T> violation: validator.validate(validatable.getValue())) { ValuePath valuePath = new ValuePath(violation.getPropertyPath()); if (!valuePath.getElements().isEmpty()) { PathSegment.Property property = (Property) valuePath.getElements().iterator().next(); if (!propertyNames.contains(property.getName())) continue; } ErrorContext errorContext = getErrorContext(valuePath); errorContext.addError(violation.getMessage()); } } }); add(AttributeAppender.append("class", " bean editor editable")); }
@Override protected void onInitialize() { super.onInitialize(); add(new INullAcceptingValidator<T>() { @Override public void validate(IValidatable<T> validatable) { Validator validator = AppLoader.getInstance(Validator.class); Set<?> violations = validator.validateValue( propertyDescriptor.getBeanClass(), propertyDescriptor.getPropertyName(), validatable.getValue()); for (Object each: violations) { ConstraintViolation<?> violation = (ConstraintViolation<?>) each; addError(violation.getMessage()); } } }); add(new AttributeAppender("class", " property editor editable")); }
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()); } }
@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()); } }
@SuppressWarnings("deprecation") public static Object invokeWithinValidation(MethodInvocation invocation, Validator validator, Class<?>[] groups) throws Throwable { org.hibernate.validator.method.MethodValidator methodValidator = validator.unwrap(org.hibernate.validator.method.MethodValidator.class); Set<org.hibernate.validator.method.MethodConstraintViolation<Object>> result = methodValidator.validateAllParameters( invocation.getThis(), invocation.getMethod(), invocation.getArguments(), groups); if (!result.isEmpty()) { throw new org.hibernate.validator.method.MethodConstraintViolationException(result); } Object returnValue = invocation.proceed(); result = methodValidator.validateReturnValue( invocation.getThis(), invocation.getMethod(), returnValue, groups); if (!result.isEmpty()) { throw new org.hibernate.validator.method.MethodConstraintViolationException(result); } return returnValue; }
@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); } }
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; }
@Override protected void configure() { bind(ObjectMapper.class).toInstance(JavaUtils.newObjectMapper()); bind(MetricRegistry.class).toInstance(new MetricRegistry()); SingularityRunnerBaseLogging.quietEagerLogging(); bind(Validator.class).toInstance(Validation.buildDefaultValidatorFactory().getValidator()); bind(SingularityRunnerExceptionNotifier.class).in(Scopes.SINGLETON); final Optional<String> consolidatedConfigFilename = Optional.fromNullable(Strings.emptyToNull(System.getProperty(CONFIG_PROPERTY))); final ConfigurationBinder configurationBinder = ConfigurationBinder.newBinder(binder()); configurationBinder.bindPrimaryConfiguration(primaryConfigurationClass, consolidatedConfigFilename); for (Class<? extends BaseRunnerConfiguration> additionalConfigurationClass : additionalConfigurationClasses) { configurationBinder.bindConfiguration(additionalConfigurationClass, consolidatedConfigFilename); } if (!additionalConfigurationClasses.contains(SingularityRunnerBaseConfiguration.class)) { configurationBinder.bindConfiguration(SingularityRunnerBaseConfiguration.class, consolidatedConfigFilename); } bind(SingularityRunnerBaseLogging.class).asEagerSingleton(); bind(new TypeLiteral<Optional<String>>(){}).annotatedWith(Names.named(CONSOLIDATED_CONFIG_FILENAME)).toInstance(consolidatedConfigFilename); }
@Autowired @SuppressWarnings("unchecked") public KvMapperFactory(ObjectMapper objectMapper, KeyValueStorage storage, TextEncryptor encryptor, Validator validator) { this.objectMapper = objectMapper; this.storage = storage; this.validator = validator; ImmutableMap.Builder<Class<?>, FieldSetter> builder = ImmutableMap.builder(); builder.put(Map.class, (field, value) -> { Map fieldMap = (Map) field; fieldMap.clear(); if (value != null) { fieldMap.putAll((Map)value); } }); builder.put(Collection.class, (field, value) -> { Collection fieldColl = (Collection) field; fieldColl.clear(); fieldColl.addAll((Collection)value); }); setters = builder.build(); interceptors = ImmutableMap.<Class<?>, PropertyInterceptor>builder() .put(PropertyCipher.class, new PropertyCipher(encryptor)) .build(); }
public List<ConstraintViolation> validateRequired() { List<ConstraintViolation> returnListreturnList = new ArrayList(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); for (DatasetField dsf : this.getFlatDatasetFields()) { dsf.setValidationMessage(null); // clear out any existing validation message Set<ConstraintViolation<DatasetField>> constraintViolations = validator.validate(dsf); for (ConstraintViolation<DatasetField> constraintViolation : constraintViolations) { dsf.setValidationMessage(constraintViolation.getMessage()); returnListreturnList.add(constraintViolation); break; // currently only support one message, so we can break out of the loop after the first constraint violation } } return returnListreturnList; }
@Test public void testValidation() throws Exception { // 検証対象の値を格納したBean InputBean bean = new InputBean(); bean.setCode("123456"); // Validatorの生成 ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator v = factory.getValidator(); // 検証結果を取得、検証メッセージを表示 Set<ConstraintViolation<InputBean>> result = v.validate(bean); for (ConstraintViolation<InputBean> cv : result) { System.out.println(cv.getMessage()); System.out.println(cv.getConstraintDescriptor().getAnnotation()); System.out.println(cv.getPropertyPath()); } }
public void validateAdditionalRules(ValidationErrors errors) { // all previous validations return no errors if (crossFieldValidate && errors.isEmpty()) { BeanValidation beanValidation = AppBeans.get(BeanValidation.NAME); Validator validator = beanValidation.getValidator(); Set<ConstraintViolation<Entity>> violations = validator.validate(getItem(), UiCrossFieldChecks.class); violations.stream() .filter(violation -> { Path propertyPath = violation.getPropertyPath(); Path.Node lastNode = Iterables.getLast(propertyPath); return lastNode.getKind() == ElementKind.BEAN; }) .forEach(violation -> errors.add(violation.getMessage())); } }
public static JsonNode parsePolicyEnable(String jsonString, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{ List<String> violation_message = new ArrayList<String>(); ObjectNode result = new_mapper.createObjectNode(); result.put("valid", false); PolicyEnbale policyEnable = new_mapper.readValue(jsonString, PolicyEnbale.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<PolicyEnbale>> set = validator.validate(policyEnable); if (set.size() > 0 ){ for (ConstraintViolation<PolicyEnbale> constraintViolation : set) { violation_message.add(constraintViolation.getMessage()); } result.set("violation_message", new_mapper.valueToTree(violation_message)); return result; } //additional data manipulation String new_json = policyEnable.transformInput(); result.put("valid", true); result.put("new_json", new_json); return result; }
public static JsonNode parseScalingHistory(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, ArrayList.class, HistoryData.class); new_mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); List<HistoryData> scalinghistory = (List<HistoryData>)new_mapper.readValue(jsonString, javaType); 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<List<HistoryData>>> set = validator.validate(scalinghistory); if (set.size() > 0 ){ for (ConstraintViolation<List<HistoryData>> constraintViolation : set) { violation_message.add(constraintViolation.getMessage()); } result.set("violation_message", new_mapper.valueToTree(violation_message)); return result; } //additional data manipulation String new_json = transformHistory(scalinghistory); result.put("valid", true); result.put("new_json", new_json); return result; }
/** * 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; }
@Override protected Advice createMethodValidationAdvice(Validator validator) { if (validator == null) { return new CustomMethodValidationInterceptor(constraintViolationExceptionMapper); } return new CustomMethodValidationInterceptor(validator, constraintViolationExceptionMapper); }
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()); }); }
private static <T> void assertViolation(@Nullable final Class<? extends Annotation> clazz, final T bean, @Nullable final String property, final boolean expectedMatching, final String messageFormat, Class... groups) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> violations = null; if (groups == null || groups.length == 0) { violations = validator.validate(bean); } else { violations = validator.validate(bean, groups); } ConstraintViolation<T> matchingViolation = null; for (ConstraintViolation<T> violation : violations) { if ((clazz == null || violation.getConstraintDescriptor().getAnnotation().annotationType().equals(clazz)) && (property == null || violation.getPropertyPath().toString().equals(property))) { matchingViolation = violation; break; } } if (expectedMatching && matchingViolation == null || !expectedMatching && matchingViolation != null) { Class<? extends Annotation> annotation = clazz; String prop = property; String details = ""; if (matchingViolation != null) { annotation = matchingViolation.getConstraintDescriptor().getAnnotation().annotationType(); prop = matchingViolation.getPropertyPath().toString(); details = " - " + matchingViolation; } throw new AssertionError(MessageFormat.format(messageFormat, annotation, prop) + details); } }
@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()); } }
public ExtensionHandler(final DataManager dataMgr, final ExtensionDataAccessObject fileStore, final ExtensionAnalyzer extensionAnalyzer, final Validator validator) { super(dataMgr); this.fileStore = fileStore; this.extensionAnalyzer = extensionAnalyzer; this.validator = validator; }
public ConnectionHandler(final DataManager dataMgr, final Validator validator, final Credentials credentials, final ClientSideState state, final VerificationConfigurationProperties config, final EncryptionComponent encryptionComponent) { super(dataMgr); this.validator = validator; this.credentials = credentials; this.state = state; this.config = config; this.encryptionComponent = encryptionComponent; }
@Before public void setUp() { DataManager manager = mock(DataManager.class); Validator validator = mock(Validator.class); inspectors = mock(Inspectors.class); handler = new IntegrationHandler(manager, validator, inspectors, new EncryptionComponent(null)); }
@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()); */ }
/** * 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); } }
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()); } }
/** * Set the JSR-303 Validator to delegate to for validating methods. * <p>Default is the default ValidatorFactory's default Validator. */ public void setValidator(Validator validator) { if(validator instanceof LocalValidatorFactoryBean) { this.validator = ((LocalValidatorFactoryBean) validator).getValidator(); } else { this.validator = validator; } }
public static <T> void validateEntityFields(Validator validator, T entity) { Set<ConstraintViolation<T>> errors = validator.validate(entity); Iterator<ConstraintViolation<T>> itErrors = errors.iterator(); if (itErrors.hasNext()) { ConstraintViolation<T> violation = itErrors.next(); throw new FieldNotValidException(violation.getPropertyPath().toString(), violation.getMessage()); } }
@Inject public DefaultDataManager(IdManager idManager, UserManager userManager, ConfigManager configManager, TaskScheduler taskScheduler, PersistManager persistManager, MailManager mailManager, Validator validator, PasswordService passwordService) { this.userManager = userManager; this.configManager = configManager; this.validator = validator; this.idManager = idManager; this.taskScheduler = taskScheduler; this.persistManager = persistManager; this.mailManager = mailManager; this.passwordService = passwordService; }
/** * 线程安全的 * * @return {@link Validator} */ public static Validator getHibernateValidator () { return Validation.byProvider( HibernateValidator.class ) .configure() .buildValidatorFactory() .getValidator(); }
/** * 线程安全的 * * @return {@link Validator} */ public static Validator getValidator ( Class< ? extends ValidationProvider > providerType ) { return Validation.byProvider( providerType ) .configure() .buildValidatorFactory() .getValidator(); }