@Override
  public void validateResult(
      final Object resource, final Invocable resourceMethod, final Object result) {
    if (configuration.getBootstrapConfiguration().isExecutableValidationEnabled()) {
      final Set<ConstraintViolation<Object>> constraintViolations =
          new HashSet<ConstraintViolation<Object>>();
      final Method handlingMethod = resourceMethod.getHandlingMethod();

      final BeanDescriptor beanDescriptor = getConstraintsForClass(resource.getClass());
      final MethodDescriptor methodDescriptor =
          beanDescriptor.getConstraintsForMethod(
              handlingMethod.getName(), handlingMethod.getParameterTypes());

      final Method definitionMethod = resourceMethod.getDefinitionMethod();

      if (methodDescriptor != null
          && methodDescriptor.hasConstrainedReturnValue()
          && validateOnExecutionHandler.validateMethod(
              resource.getClass(), definitionMethod, handlingMethod)) {
        constraintViolations.addAll(
            forExecutables().validateReturnValue(resource, handlingMethod, result));

        if (result instanceof Response) {
          constraintViolations.addAll(
              forExecutables()
                  .validateReturnValue(resource, handlingMethod, ((Response) result).getEntity()));
        }
      }

      if (!constraintViolations.isEmpty()) {
        throw new ConstraintViolationException(constraintViolations);
      }
    }
  }
  @Override
  public void validateResourceAndInputParams(
      final Object resource, final Invocable resourceMethod, final Object[] args) {
    final Set<ConstraintViolation<Object>> constraintViolations =
        new HashSet<ConstraintViolation<Object>>();
    final BeanDescriptor beanDescriptor = getConstraintsForClass(resource.getClass());

    // Resource validation.
    if (beanDescriptor.isBeanConstrained()) {
      constraintViolations.addAll(validate(resource));
    }

    if (resourceMethod != null
        && configuration.getBootstrapConfiguration().isExecutableValidationEnabled()) {
      final Method handlingMethod = resourceMethod.getHandlingMethod();

      // Resource method validation - input parameters.
      final MethodDescriptor methodDescriptor =
          beanDescriptor.getConstraintsForMethod(
              handlingMethod.getName(), handlingMethod.getParameterTypes());

      if (methodDescriptor != null && methodDescriptor.hasConstrainedParameters()) {
        constraintViolations.addAll(
            forExecutables().validateParameters(resource, handlingMethod, args));
      }
    }

    if (!constraintViolations.isEmpty()) {
      throw new ConstraintViolationException(constraintViolations);
    }
  }
  @Override
  public boolean hasConstraints() {
    if (beanDescriptor.isBeanConstrained()
        || !beanDescriptor.getConstrainedConstructors().isEmpty()
        || !beanDescriptor
            .getConstrainedMethods(MethodType.NON_GETTER, MethodType.GETTER)
            .isEmpty()) {
      return true;
    }

    return false;
  }
  @Test
  @TestForIssue(jiraKey = "HV-333")
  public void
      testContextWithRightDescriptorAndValueAndRootBeanClassIsPassedToMessageInterpolator() {

    // use a easy mock message interpolator for verifying that the right MessageInterpolatorContext
    // will be passed
    MessageInterpolator mock = createMock(MessageInterpolator.class);
    Configuration<?> config = ValidatorUtil.getConfiguration().messageInterpolator(mock);

    Validator validator = config.buildValidatorFactory().getValidator();

    BeanDescriptor beanDescriptor = validator.getConstraintsForClass(TestBean.class);
    PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty("test");
    Set<ConstraintDescriptor<?>> constraintDescriptors =
        propertyDescriptor.getConstraintDescriptors();
    assertTrue(constraintDescriptors.size() == 1);

    // prepare the mock interpolator to expect the right interpolate call
    String validatedValue = "value";
    expect(
            mock.interpolate(
                MESSAGE,
                new MessageInterpolatorContext(
                    constraintDescriptors.iterator().next(),
                    validatedValue,
                    TestBean.class,
                    Collections.<String, Object>emptyMap())))
        .andReturn("invalid");
    replay(mock);

    Set<ConstraintViolation<TestBean>> violations =
        validator.validate(new TestBean(validatedValue));
    assertNumberOfViolations(violations, 1);

    // verify that the right context was passed
    verify(mock);
  }
  private <T> void determineConstrainedConstructors(
      AnnotatedType<T> type,
      BeanDescriptor beanDescriptor,
      Set<AnnotatedCallable<? super T>> callables) {
    Class<?> clazz = type.getJavaClass();
    EnumSet<ExecutableType> classLevelExecutableTypes = executableTypesDefinedOnType(clazz);

    for (AnnotatedConstructor<T> annotatedConstructor : type.getConstructors()) {
      Constructor<?> constructor = annotatedConstructor.getJavaMember();
      EnumSet<ExecutableType> memberLevelExecutableType =
          executableTypesDefinedOnConstructor(constructor);

      if (veto(classLevelExecutableTypes, memberLevelExecutableType, ExecutableType.CONSTRUCTORS)) {
        continue;
      }

      if (beanDescriptor.getConstraintsForConstructor(constructor.getParameterTypes()) != null) {
        callables.add(annotatedConstructor);
      }
    }
  }
 private boolean isGetterConstrained(Method method, BeanDescriptor beanDescriptor) {
   String propertyName = ReflectionHelper.getPropertyName(method);
   PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty(propertyName);
   return propertyDescriptor != null
       && propertyDescriptor.findConstraints().declaredOn(ElementType.METHOD).hasConstraints();
 }
 private boolean isNonGetterConstrained(Method method, BeanDescriptor beanDescriptor) {
   return beanDescriptor.getConstraintsForMethod(method.getName(), method.getParameterTypes())
       != null;
 }
Example #8
0
  /**
   * Retrieve a field.
   *
   * @param key field name
   * @return the field (even if the field does not exist you get a field)
   */
  public Field field(String key) {

    // Value
    String fieldValue = null;
    if (data.containsKey(key)) {
      fieldValue = data.get(key);
    } else {
      if (value.isPresent()) {
        BeanWrapper beanWrapper = new BeanWrapperImpl(value.get());
        beanWrapper.setAutoGrowNestedPaths(true);
        String objectKey = key;
        if (rootName != null && key.startsWith(rootName + ".")) {
          objectKey = key.substring(rootName.length() + 1);
        }
        if (beanWrapper.isReadableProperty(objectKey)) {
          Object oValue = beanWrapper.getPropertyValue(objectKey);
          if (oValue != null) {
            final String objectKeyFinal = objectKey;
            fieldValue =
                withRequestLocale(
                    () ->
                        formatters.print(
                            beanWrapper.getPropertyTypeDescriptor(objectKeyFinal), oValue));
          }
        }
      }
    }

    // Error
    List<ValidationError> fieldErrors = errors.get(key);
    if (fieldErrors == null) {
      fieldErrors = new ArrayList<>();
    }

    // Format
    Tuple<String, List<Object>> format = null;
    BeanWrapper beanWrapper = new BeanWrapperImpl(blankInstance());
    beanWrapper.setAutoGrowNestedPaths(true);
    try {
      for (Annotation a : beanWrapper.getPropertyTypeDescriptor(key).getAnnotations()) {
        Class<?> annotationType = a.annotationType();
        if (annotationType.isAnnotationPresent(play.data.Form.Display.class)) {
          play.data.Form.Display d = annotationType.getAnnotation(play.data.Form.Display.class);
          if (d.name().startsWith("format.")) {
            List<Object> attributes = new ArrayList<>();
            for (String attr : d.attributes()) {
              Object attrValue = null;
              try {
                attrValue = a.getClass().getDeclaredMethod(attr).invoke(a);
              } catch (Exception e) {
                // do nothing
              }
              attributes.add(attrValue);
            }
            format = Tuple(d.name(), attributes);
          }
        }
      }
    } catch (NullPointerException e) {
      // do nothing
    }

    // Constraints
    List<Tuple<String, List<Object>>> constraints = new ArrayList<>();
    Class<?> classType = backedType;
    String leafKey = key;
    if (rootName != null && leafKey.startsWith(rootName + ".")) {
      leafKey = leafKey.substring(rootName.length() + 1);
    }
    int p = leafKey.lastIndexOf('.');
    if (p > 0) {
      classType = beanWrapper.getPropertyType(leafKey.substring(0, p));
      leafKey = leafKey.substring(p + 1);
    }
    if (classType != null) {
      BeanDescriptor beanDescriptor =
          play.data.validation.Validation.getValidator().getConstraintsForClass(classType);
      if (beanDescriptor != null) {
        PropertyDescriptor property = beanDescriptor.getConstraintsForProperty(leafKey);
        if (property != null) {
          constraints = Constraints.displayableConstraint(property.getConstraintDescriptors());
        }
      }
    }

    return new Field(this, key, constraints, format, fieldErrors, fieldValue);
  }