@Test public void testCustomConstraintValidatorFactory() { Configuration<?> configuration = Validation.byDefaultProvider().configure(); assertDefaultBuilderAndFactory(configuration); ValidatorFactory factory = configuration.buildValidatorFactory(); Validator validator = factory.getValidator(); Customer customer = new Customer(); customer.setFirstName("John"); Set<ConstraintViolation<Customer>> constraintViolations = validator.validate(customer); assertEquals(constraintViolations.size(), 1, "Wrong number of constraints"); ConstraintViolation<Customer> constraintViolation = constraintViolations.iterator().next(); assertEquals("may not be empty", constraintViolation.getMessage(), "Wrong message"); // get a new factory using a custom configuration configuration = Validation.byDefaultProvider().configure(); configuration.constraintValidatorFactory( new ConstraintValidatorFactory() { public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) { if (key == NotNullValidator.class) { return (T) new BadlyBehavedNotNullConstraintValidator(); } return new ConstraintValidatorFactoryImpl().getInstance(key); } }); factory = configuration.buildValidatorFactory(); validator = factory.getValidator(); constraintViolations = validator.validate(customer); assertEquals(constraintViolations.size(), 0, "Wrong number of constraints"); }
@POST @Path("pay") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public ResponseBean payment(ExamBean2 bean) { ResponseBean<ExamBean2> res = new ResponseBean(); // We can't @Inject Validator on Glassfish 4.0, 4.0.1 may be fix it. final ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<ExamBean2>> violations = validator.validate(bean, bean.validateGroups()); System.out.println(violations.toString()); if (!violations.isEmpty()) { // There are some validation errors res.setSuccess(false); res.setValidationError(violations); return res; } res.setSuccess(true); return res; }
@Override public String getTaxNumber(String firmokpo, String docnum, String docdate) { TaxNumberParameter params = new TaxNumberParameter(firmokpo, docnum, docdate); StringBuilder outputBuffer = new StringBuilder(); // here we should validate parameters, that have been passed with query ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<TaxNumberParameter>> constraintViolations = validator.validate(params); StringBuilder validationBuffer = new StringBuilder(); validationBuffer.append( constraintViolations .stream() .map(ConstraintViolation::getMessage) .collect(Collectors.joining("\n"))); String validationMessage = validationBuffer.toString(); if (!validationMessage.isEmpty()) { // outputBuffer.append(validationMessage); // Throwing Exception with contents. throw new IllegalArgumentException("Invalid input parameters: " + validationMessage); } String taxNumber = taxNumberDAO.getTaxNumber(params); return taxNumber; }
public static void main(String[] args) { Configuration configuration = Validation.byProvider(HibernateValidator.class).configure(); ValidatorFactory factory = configuration.buildValidatorFactory(); Validator validator = factory.getValidator(); validator.validate(Object.class); // programmation constraint mappings ConstraintMapping mapping = new ConstraintMapping(); }
private Validator configure(String mappingsUrl) { Configuration<?> configuration = ValidatorUtil.getConfiguration(); configuration.traversableResolver(new DummyTraversableResolver()); configuration.addMapping(InheritanceMappingsTest.class.getResourceAsStream(mappingsUrl)); ValidatorFactory validatorFactory = configuration.buildValidatorFactory(); return validatorFactory.getValidator(); }
private Object getInstanceSafely() { final ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged( factory.getClass().getClassLoader()); return factory.getValidator(); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl); } }
@Before public void removeOldKeys() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); keyStore .getUsers() .stream() .map(keyStore::getKeys) .flatMap(Collection::stream) .forEach(unsafe(PersistedKey::delete)); }
@Test public void ifAgeNotRange_ageValidationFails() { User user = new User(); user.setName("MyName"); user.setAboutMe("Its all about me!!"); user.setAge(8); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<User>> violations = validator.validate(user); assertEquals(violations.isEmpty(), false); }
@Test public void ifNameIsNull_nameValidationFails() { User user = new User(); user.setWorking(true); user.setAboutMe("Its all about me!!"); user.setAge(50); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<User>> violations = validator.validate(user); assertEquals(violations.isEmpty(), false); }
static Validator getBeanValidator() { if (beanValidator == null) { try { ValidatorFactory f = Validation.buildDefaultValidatorFactory(); return f.getValidator(); } catch (ValidationException e) { LOG.info("No JSR-303 bean validation configuration found: " + e.getMessage()); return null; } } return beanValidator; }
public static boolean hasErrors(Object obj, String message) { if (message != null) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> errors = validator.validate(obj); for (ConstraintViolation<Object> constraintViolation : errors) { if (message.equals(constraintViolation.getMessage())) { return true; } } } return false; }
@Test public void ifFnameNullAgeNotRangeAndWorkingIsFalse_validationFailsWithThreeErrors() { User user = new User(); user.setAboutMe("Its all about me!!"); user.setAge(300); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<User>> violations = validator.validate(user); logViolations(violations); assertEquals(violations.isEmpty(), false); assertEquals(violations.size(), 3); }
@Test public void validateFromJson() throws IOException { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); XenonConfiguration actual = fromJson(jsonFixture("fixtures/xenon.json"), XenonConfiguration.class); Set<ConstraintViolation<XenonConfiguration>> constraintViolations = validator.validateProperty(actual, "scheduler"); assertThat(constraintViolations.size()).isEqualTo(0); }
@Override public void close() { delegate.close(); for (final Releasable<?> r : toRelease) { r.release(); } }
@RequestMapping(method = RequestMethod.POST) public String processSubmit(@ModelAttribute("bean") @Valid Bean bean, BindingResult result) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); logger.info(validator.getClass()); logger.info(bean.toString()); logger.info(result.getAllErrors().toString()); if (result.hasErrors()) { return "bean/form"; } return "bean/done"; }
public String addQuestionThroughForm() throws IOException { if (idTaskAddQuestion < 1) { addFieldError("warning", "Select task and then add questions"); return INPUT; } SessionFactory sessionFactory = (SessionFactory) servletContext.getAttribute("SessionFactory"); try { task = new TaskDaoImpl(sessionFactory).getTask(idTaskAddQuestion); } catch (Exception e) { e.printStackTrace(); return INPUT; } if (hasFieldErrors()) { return ERROR; } if (fileImage != null) { Path imagePath = Paths.get(fileImage.getAbsolutePath()); InputStream io = Files.newInputStream(imagePath); question.setImage(IOUtils.toByteArray(io)); } question.setTask(task); ValidatorFactory validatorFactory = (ValidatorFactory) servletContext.getAttribute("ValidatorFactory"); Validator validator = validatorFactory.getValidator(); Set<ConstraintViolation<Question>> constraintViolations = validator.validate(question); if (!constraintViolations.isEmpty()) { for (ConstraintViolation item : constraintViolations) { addFieldError("warning", "Question validate error. " + item.getMessage()); } return ERROR; } if (!parseVariants(question)) { return ERROR; } try { task = new TaskDaoImpl(sessionFactory).addQuestion(idTaskAddQuestion, question); addFieldError("success", "Question was added!"); question = null; return SUCCESS; } catch (Exception e) { addFieldError("warning", e.getMessage()); return ERROR; } }
public StatisticalValidationState() { ValidatorFactory factory = null; final Configuration<?> configuration = Validation.byDefaultProvider().configure(); try (InputStream mappingStream = StatisticalValidation.class.getResourceAsStream("mapping.xml")) { configuration.addMapping(mappingStream); factory = configuration.buildValidatorFactory(); assertThat(factory).isNotNull(); } catch (IOException e) { e.printStackTrace(); } validator = factory.getValidator(); entitiesUnderTest = IntStream.rangeClosed(0, NUMBER_OF_TEST_ENTITIES) .mapToObj(index -> new TestEntity(index % 10)) .collect(Collectors.toList()); }
public ValidationExtension() { Configuration<?> config = Validation.byDefaultProvider().configure(); BootstrapConfiguration bootstrap = config.getBootstrapConfiguration(); globalExecutableTypes = bootstrap.getDefaultValidatedExecutableTypes(); isExecutableValidationEnabled = bootstrap.isExecutableValidationEnabled(); validatorFactory = config.buildValidatorFactory(); validator = validatorFactory.getValidator(); executableHelper = new ExecutableHelper(new TypeResolutionHelper()); }
public static void main(String[] args) { // Cria o objeto que deseja-se validar ModalidadeDisciplina ser = new ModalidadeDisciplina(); // Faz uma frabrica de validações ValidatorFactory fabrica = Validation.buildDefaultValidatorFactory(); // Cria a validação Validator valida = fabrica.getValidator(); // Pega a coleção de erros elencados Set<ConstraintViolation<ModalidadeDisciplina>> constraintViolationsCliente = valida.validate(ser); for (ConstraintViolation<ModalidadeDisciplina> erro : constraintViolationsCliente) { // Imprime os erros System.err.println(erro.getMessage()); } }
private Validator configureValidation(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); GenericBootstrap bootstrap = Validation.byDefaultProvider(); Configuration config = bootstrap.configure(); InputStream mappingsXml = new ByteArrayInputStream(validationXml.getBytes()); config.addMapping(mappingsXml); ValidatorFactory factory = config.buildValidatorFactory(); ValidatorContext validatorContext = factory.usingContext(); Validator validator = validatorContext.getValidator(); if (null == validator) { factory = Validation.byDefaultProvider().configure().buildValidatorFactory(); validator = factory.getValidator(); } out.print("<p>"); out.print("Obtained ValidatorFactory: " + factory + "."); out.print("</p>"); return validator; }
@Test public void testBasicRequestBuild() throws Exception { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); TatraPaySettings settings = new TatraPaySettings(); settings.setKey("123456789"); settings.setBaseUrl(BASEURL); settings.setMid("08A"); settings.setRurl("http://hungaropage.hu/"); TatraPayRequest request = new TatraPayRequest(); request.setSettings(settings); request.setAmt(BigDecimal.valueOf(12.7d)); request.setVs(235664L); PaymentSigner signer = new DESSigner(); TatraPayRequestBuilder builder = new TatraPayRequestBuilder(factory.getValidator(), signer); PaymentRequest paymentRequest = builder.generate(request, null); assertEquals("12.70", paymentRequest.getParameters().get(TatraPayParameter.AMT.getName())); assertNotNull( "Sign not generated?", paymentRequest.getParameters().get(TatraPayParameter.SIGN.getName())); }
protected final int add() { Validator validator = FACTORY.getValidator(); Set<ConstraintViolation<Model>> violations = validator.validate(this); if (violations.size() > 0) { ValidationUtils.throwException(violations); } BasicDBObject dbObjectToAdd = toBasicDBObject(); WriteResult result = MongoDB.getInstance().create(getCollectionName(getClass()), dbObjectToAdd); if (!Tools.isBlankOrNull(result.getError())) { throw new JCertifException(this.getClass(), result.getError()); } return 1; }
private Validator getValidator(DescriptorEvent event) { ClassDescriptor descriptor = event.getDescriptor(); Validator res = validatorMap.get(descriptor); if (res == null) { TraversableResolver traversableResolver = new AutomaticLifeCycleValidationTraversableResolver(descriptor); res = validatorFactory.usingContext().traversableResolver(traversableResolver).getValidator(); Validator t = validatorMap.put(descriptor, res); if (t != null) { // Threading collision, use existing res = t; } } return res; }
protected final int update() { Validator validator = FACTORY.getValidator(); Set<ConstraintViolation<Model>> violations = validator.validate(this); if (violations.size() > 0) { ValidationUtils.throwException(violations); } BasicDBObject dbObjectToUpdate = toBasicDBObject(); dbObjectToUpdate.append(Constantes.MONGOD_ID_ATTRIBUTE_NAME, _id); int newId = increment(dbObjectToUpdate); WriteResult result = MongoDB.getInstance().update(getCollectionName(getClass()), dbObjectToUpdate); if (!Tools.isBlankOrNull(result.getError())) { throw new JCertifException(this.getClass(), result.getError()); } return newId; }
private ValidatorFactory() { Configuration<?> config = Validation.byDefaultProvider().configure(); final MessageInterpolator defaultMessageInterpolator = config.getDefaultMessageInterpolator(); config.messageInterpolator( new MessageInterpolator() { @Override public String interpolate(String messageTemplate, Context context) { String message; if (context.getConstraintDescriptor().getPayload() != null && context.getConstraintDescriptor().getPayload().contains(Localized.class)) { // Retrieve message from message library message = MessageUtility.getLocalizedMessage(messageTemplate).getMessage(); } else { message = defaultMessageInterpolator.interpolate(messageTemplate, context); } return message; } @Override public String interpolate(String messageTemplate, Context context, Locale locale) { String message; if (context.getConstraintDescriptor().getPayload() != null && context.getConstraintDescriptor().getPayload().contains(Localized.class)) { // Retrieve message from message library message = MessageUtility.getLocalizedMessage(messageTemplate, locale).getMessage(); } else { message = defaultMessageInterpolator.interpolate(messageTemplate, context); } return message; } }); // Stop validation if Entity action is DELETE config.traversableResolver( new TraversableResolver() { @Override public boolean isReachable( Object traversableObject, Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) { if (traversableObject != null && AbstractBindingBean.class.isAssignableFrom(traversableObject.getClass())) { AbstractBindingBean bean = (AbstractBindingBean) traversableObject; if (bean.getEntityAction() != null && bean.getEntityAction() == EntityAction.DELETE) { return false; } } return true; } @Override public boolean isCascadable( Object traversableObject, Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) { return true; } }); javax.validation.ValidatorFactory factory = config.buildValidatorFactory(); validator = factory.getValidator(); }
{ ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); }
@Override public TraversableResolver getTraversableResolver() { return delegate.getTraversableResolver(); }
@Override public ParameterNameProvider getParameterNameProvider() { return delegate.getParameterNameProvider(); }
@Override public <T> T unwrap(final Class<T> type) { return delegate.unwrap(type); }
@Override public ConstraintValidatorFactory getConstraintValidatorFactory() { return delegate.getConstraintValidatorFactory(); }