@Override public List<Constraint> resolveForProperty(String property, Class<?> clazz) { List<Constraint> constraints = new ArrayList<>(); String[] properties = property.split("\\."); Class<?> clazzforLoop = clazz; for (int i = 0; i < properties.length; i++) { String propertyForLoop = properties[i]; propertyForLoop = propertyForLoop.replace("[]", ""); BeanDescriptor beanDescriptor = this.validator.getConstraintsForClass(clazzforLoop); PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty( propertyForLoop); if (propertyDescriptor != null) { if (isLastElement(properties, i)) { collectConstraints(constraints, propertyDescriptor); } clazzforLoop = getFollowUpClass(propertyDescriptor, clazzforLoop); } else { break; } } return constraints; }
protected void initBeanValidator() { MetadataTools metadataTools = AppBeans.get(MetadataTools.NAME); MetaClass propertyEnclosingMetaClass = metadataTools.getPropertyEnclosingMetaClass(metaPropertyPath); Class enclosingJavaClass = propertyEnclosingMetaClass.getJavaClass(); if (enclosingJavaClass != KeyValueEntity.class && !DynamicAttributesUtils.isDynamicAttribute(metaProperty)) { BeanValidation beanValidation = AppBeans.get(BeanValidation.NAME); javax.validation.Validator validator = beanValidation.getValidator(); BeanDescriptor beanDescriptor = validator.getConstraintsForClass(enclosingJavaClass); if (beanDescriptor.isBeanConstrained()) { addValidator(new BeanValidator(enclosingJavaClass, metaProperty.getName())); } } }
/** * @return PropertyDescriptor may be null when JavaBean do not have any Bean Validation * annotations. */ private PropertyDescriptor getPropertyDescriptor() throws JspException { String path = getBindStatus().getPath(); int dotPos = path.indexOf('.'); if (dotPos == -1) { return null; } String beanName = path.substring(0, dotPos); String expression = path.substring(dotPos + 1); Map<String, Object> model = getRequestContext().getModel(); Object bean = getBean(beanName, model); Validator validator = getRequestContext().getWebApplicationContext().getBean(Validator.class); BeanDescriptor constraints = validator.getConstraintsForClass(bean.getClass()); return constraints.getConstraintsForProperty(expression); }
private static void applyDDL( String prefix, PersistentClass persistentClass, Class<?> clazz, ValidatorFactory factory, Set<Class<?>> groups, boolean activateNotNull, Dialect dialect) { final BeanDescriptor descriptor = factory.getValidator().getConstraintsForClass( clazz ); //no bean level constraints can be applied, go to the properties for ( PropertyDescriptor propertyDesc : descriptor.getConstrainedProperties() ) { Property property = findPropertyByName( persistentClass, prefix + propertyDesc.getPropertyName() ); boolean hasNotNull; if ( property != null ) { hasNotNull = applyConstraints( propertyDesc.getConstraintDescriptors(), property, propertyDesc, groups, activateNotNull, dialect ); if ( property.isComposite() && propertyDesc.isCascaded() ) { Class<?> componentClass = ( (Component) property.getValue() ).getComponentClass(); /* * we can apply not null if the upper component let's us activate not null * and if the property is not null. * Otherwise, all sub columns should be left nullable */ final boolean canSetNotNullOnColumns = activateNotNull && hasNotNull; applyDDL( prefix + propertyDesc.getPropertyName() + ".", persistentClass, componentClass, factory, groups, canSetNotNullOnColumns, dialect ); } //FIXME add collection of components } } }
@Override public <T> Set<ConstraintViolation<T>> validate(final T object, final Class<?>... groups) { final MinijaxConstraintValidatorContext<T> context = new MinijaxConstraintValidatorContext<>(object); final BeanDescriptor descriptor = getConstraintsForClass(object.getClass()); for (final PropertyDescriptor propertyDescriptor : descriptor.getConstrainedProperties()) { final Object value = ((MinijaxPropertyDescriptor) propertyDescriptor).getValue(object); validateProperty(context, propertyDescriptor, value); } return context.getResult(); }
@Override public <T> Set<ConstraintViolation<T>> validateProperty(final T object, final String propertyName, final Class<?>... groups) { final MinijaxConstraintValidatorContext<T> context = new MinijaxConstraintValidatorContext<>(object); final BeanDescriptor descriptor = getConstraintsForClass(object.getClass()); final PropertyDescriptor propertyDescriptor = descriptor.getConstraintsForProperty(propertyName); final Object value = ((MinijaxPropertyDescriptor) propertyDescriptor).getValue(object); validateProperty(context, propertyDescriptor, value); return context.getResult(); }
private GwtValidationContext(final Class<T> rootBeanClass, final T rootBean, final BeanDescriptor beanDescriptor, final MessageInterpolator messageInterpolator, final TraversableResolver traversableResolver, final AbstractGwtValidator validator, final Set<Object> validatedObjects) { this.rootBeanClass = rootBeanClass; this.rootBean = rootBean; this.beanDescriptor = beanDescriptor; this.messageInterpolator = messageInterpolator; this.traversableResolver = traversableResolver; this.validator = validator; this.validatedObjects = new HashSet<>(validatedObjects); }
@Override protected void compose(final ClassSourceFileComposerFactory composerFactory) { this.addImports(composerFactory, GWT.class, GwtBeanDescriptor.class, GwtSpecificValidator.class, GwtValidationContext.class, ValidationGroupsMetadata.class, Set.class, HashSet.class, Map.class, HashMap.class, Default.class, ConstraintViolation.class, BeanDescriptor.class); composerFactory.setSuperclass(AbstractGwtValidator.class.getCanonicalName()); composerFactory.addImplementedInterface(this.validatorType.getQualifiedSourceName()); }
private BeanHelper doCreateHelper(final Class<?> clazz, final JClassType beanType, final TreeLogger logger, final GeneratorContext context) throws UnableToCompleteException { BeanHelper helper = this.getBean(beanType); if (helper == null) { BeanDescriptor bean; try { bean = this.serverSideValidator.getConstraintsForClass(clazz); } catch (final ValidationException e) { logger.log(TreeLogger.ERROR, "Unable to create a validator for " + clazz.getCanonicalName() + " because " + e.getMessage(), e); throw new UnableToCompleteException(); // NOPMD } helper = new BeanHelper(beanType, clazz, bean); this.cache.put(helper.getJClass(), helper); this.writeInterface(context, logger, helper); // now recurse on all Cascaded elements for (final PropertyDescriptor p : bean.getConstrainedProperties()) { // TODO(idol) only bother creating objects for properties that have constrains in the groups // specified in @GwtValidation, but not others if (p.isCascaded()) { this.doCreateHelperForProp(p, helper, logger, context); } } } return helper; }
/** * Shouldn't be created directly; instead use BeanHelperCache. */ BeanHelper(final JClassType pjclass, final Class<?> pclazz, final BeanDescriptor pbeanDescriptor) { this.beanDescriptor = pbeanDescriptor; this.jclass = pjclass; this.clazz = pclazz; }
public Validator<?> buildValidator(Class<?> beanClass, String propertyName) { javax.validation.Validator beanValidator = getDefaultValidator(); if (beanValidator != null) { BeanDescriptor descriptor = beanValidator.getConstraintsForClass(beanClass); PropertyDescriptor propDescriptor = descriptor.getConstraintsForProperty(propertyName); if (propDescriptor != null && propDescriptor.hasConstraints()) { return new JSR303BeanValidator(beanClass, propertyName); } } return null; }
/** * Only accepts if method isn't parameterless and have at least one constraint. */ private boolean hasConstraints(ControllerMethod controllerMethod) { Method method = controllerMethod.getMethod(); if (method.getParameterTypes().length == 0) { logger.debug("method {} has no parameters, skipping", controllerMethod); return false; } BeanDescriptor bean = bvalidator.getConstraintsForClass(controllerMethod.getController().getType()); if(bean == null) { return false; } MethodDescriptor descriptor = bean.getConstraintsForMethod(method.getName(), method.getParameterTypes()); return descriptor != null && descriptor.hasConstrainedParameters(); }
public void testPropertyDescriptorHasConstraints() { BeanDescriptor cons = validator.getConstraintsForClass(Book.class); Assert.assertTrue(cons.getConstraintsForProperty("author").hasConstraints()); Assert.assertTrue(cons.getConstraintsForProperty("title").hasConstraints()); Assert.assertTrue(cons.getConstraintsForProperty("uselessField").hasConstraints()); // cons.getConstraintsForProperty("unconstraintField") == null without // Introspector // cons.getConstraintsForProperty("unconstraintField") != null with // Introspector assertTrue(cons.getConstraintsForProperty("unconstraintField") == null || !cons.getConstraintsForProperty("unconstraintField").hasConstraints()); assertNull(cons.getConstraintsForProperty("unknownField")); }
public void testMetadataAPI_Book() { Assert.assertNotNull(validator.getConstraintsForClass(Book.class)); // not necessary for implementation correctness, but we'll test // nevertheless: Assert.assertSame(validator.getConstraintsForClass(Book.class), validator.getConstraintsForClass(Book.class)); BeanDescriptor bc = validator.getConstraintsForClass(Book.class); // assertEquals(ElementType.TYPE, bc.getElementType()); Assert.assertEquals(Book.class, bc.getElementClass()); // assertEquals(false, bc.isCascaded()); // assertEquals("", bc.getPropertyPath()); Assert.assertTrue(bc.getConstraintDescriptors() != null); TestUtils.failOnModifiable(bc.getConstraintDescriptors(), "beanDescriptor constraintDescriptors"); }
@Override public Set<ConstraintDescriptor<?>> getConstraintDescriptors(final Object keyObj) { String key = String.valueOf(keyObj); final Validator validator = Validation.byDefaultProvider().configure().buildValidatorFactory().getValidator(); BeanDescriptor beanDesc = validator.getConstraintsForClass(getClass()); for(PropertyDescriptor prop : beanDesc.getConstrainedProperties()) { if(prop.getPropertyName().equalsIgnoreCase(key)) { return prop.getConstraintDescriptors(); } } return new HashSet<ConstraintDescriptor<?>>(); }
@Override public BeanDescriptor getConstraintsForClass(Class<?> clazz) { Assert.notNull(this.targetValidator, "No target Validator set"); return this.targetValidator.getConstraintsForClass(clazz); }
@Override public BeanDescriptor getConstraintsForClass(Class<?> clazz) { throw new ValidationException(this.getClass().getName() + " does not implement getConstraintsForClass()"); }
@Override public BeanDescriptor getConstraintsForClass(Class<?> clazz) { Assert.state(this.targetValidator != null, "No target Validator set"); return this.targetValidator.getConstraintsForClass(clazz); }
@Override public BeanDescriptor getConstraintsForClass(Class<?> clazz) { return null; }
public GwtValidationContext(final Class<T> rootBeanClass, final T rootBean, final BeanDescriptor beanDescriptor, final MessageInterpolator messageInterpolator, final TraversableResolver traversableResolver, final AbstractGwtValidator validator) { this(rootBeanClass, rootBean, beanDescriptor, messageInterpolator, traversableResolver, validator, new HashSet<>()); }
private void writeBeanDescriptor(final SourceWriter sw) { final BeanDescriptor beanDescriptor = this.beanHelper.getBeanDescriptor(); // private final GwtBeanDescriptor <MyBean> beanDescriptor = sw.print("private final "); sw.print(GwtBeanDescriptor.class.getCanonicalName()); sw.print("<" + this.beanHelper.getTypeCanonicalName() + ">"); sw.println(" beanDescriptor = "); sw.indent(); sw.indent(); // GwtBeanDescriptorImpl.builder(Order.class) sw.print(GwtBeanDescriptorImpl.class.getCanonicalName()); sw.println(".builder(" + this.beanHelper.getTypeCanonicalName() + ".class)"); sw.indent(); sw.indent(); // .setConstrained(true) sw.println(".setConstrained(" + beanDescriptor.isBeanConstrained() + ")"); int count = 0; for (final ConstraintDescriptor<?> constraint : beanDescriptor.getConstraintDescriptors()) { if (this.areConstraintDescriptorGroupsValid(constraint)) { // .add(c0) sw.println(".add(" + this.constraintDescriptorVar("this", count) + ")"); count++; } } // .put("myProperty", myProperty_pd) for (final PropertyDescriptor p : beanDescriptor.getConstrainedProperties()) { sw.print(".put(\""); sw.print(p.getPropertyName()); sw.print("\", "); sw.print(p.getPropertyName()); sw.println("_pd)"); } // .setBeanMetadata(beanMetadata) sw.println(".setBeanMetadata(beanMetadata)"); // .build(); sw.println(".build();"); sw.outdent(); sw.outdent(); sw.outdent(); sw.outdent(); }
public BeanDescriptor getBeanDescriptor() { return this.beanDescriptor; }
public GwtValidationContext(final Class<T> prootBeanClass, final T prootBean, final BeanDescriptor pbeanDescriptor, final MessageInterpolator pmessageInterpolator, final TraversableResolver ptraversableResolver, final AbstractGwtValidator pvalidator) { super(prootBeanClass, prootBean, pbeanDescriptor, pmessageInterpolator, ptraversableResolver, pvalidator); }
@Override public BeanDescriptor getBeanDescriptor() { return beanDescriptor; }
public BeanDescriptor getConstraintsForClass(Class<?> clazz) { return this.targetValidator.getConstraintsForClass(clazz); }
@Override public BeanDescriptor getConstraintsForClass(final Class<?> clazz) { return null; }
@Override public BeanDescriptor getConstraintsForClass(Class<?> aClass) { return delegate.getConstraintsForClass(aClass); }
@Override public void readModelConstraints(MapModelRenderingContext clientRenderingContext, ClassLoader classLoader) { if (clientRenderingContext == null) { throw new IllegalArgumentException("Context cannot be null"); } if (classLoader == null) { throw new IllegalArgumentException("ClassLoader cannot be null"); } clientRenderingContext.getAvailableForms().values().forEach(formDefinition -> { if (formDefinition.getModel() instanceof JavaFormModel) { JavaFormModel javaModel = (JavaFormModel) formDefinition.getModel(); if (clientRenderingContext.getModelConstraints().containsKey(javaModel)) { return; } Class clazz = null; try { clazz = classLoader.loadClass(javaModel.getType()); if (clazz == null) { clazz = getClass().forName(javaModel.getType()); } } catch (ClassNotFoundException e) { // maybe Class is not on the project ClassLoader, let's try on the main ClassLoader try { clazz = getClass().forName(javaModel.getType()); } catch (ClassNotFoundException e1) { // ops! class not available on the main classLoader } } if (clazz == null) { logger.warn("Unable to find class for type {} on any classLoader. Skipping annotation processing", javaModel.getType()); } else { BeanDescriptor descriptor = Validation.buildDefaultValidatorFactory().getValidator().getConstraintsForClass(clazz); Set<PropertyDescriptor> properties = descriptor.getConstrainedProperties(); DynamicModelConstraints constraints = new DynamicModelConstraints(javaModel.getType()); clientRenderingContext.getModelConstraints().put(javaModel.getType(), constraints); properties.forEach(property -> { property.getConstraintDescriptors().forEach(constraintDescriptor -> { Map<String, Object> attributes = new HashMap<>(); constraintDescriptor.getAttributes().forEach((key, value) -> { if (key.equals("payload") || key.equals("groups")) { return; } Object portableValue; if (EnvUtil.isPortableType(value.getClass())) { portableValue = value; } else { portableValue = value.toString(); } attributes.put(key, portableValue); }); constraints.addConstraintForField(property.getPropertyName(), new FieldConstraint(constraintDescriptor.getAnnotation().annotationType().getName(), attributes)); }); }); } } }); }