Java 类javax.validation.executable.ExecutableValidator 实例源码

项目:java-notes    文件:App.java   
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);

}
项目:vertx-zero    文件:Validator.java   
/**
 * Validate the method parameters based on javax.validation: Hibernate Validator.
 *
 * @param proxy  The checked target object.
 * @param method The checked target method.
 * @param args   The checked target method's parameters.
 * @param <T>    The target object type: Generic types.
 */
public <T> void verifyMethod(
        final T proxy,
        final Method method,
        final Object[] args) {
    // 1. Get method validator
    final ExecutableValidator validatorParam
            = VALIDATOR.forExecutables();
    // 2. Create new params that wait for validation
    final Set<ConstraintViolation<T>> constraints
            = validatorParam.validateParameters(proxy, method, args);
    // 3. Throw out exception
    if (!constraints.isEmpty()) {
        final ConstraintViolation<T> item = constraints.iterator().next();
        if (null != item) {
            final WebException error
                    = new _400ValidationException(getClass(),
                    proxy.getClass(), method, item.getMessage());
            error.setReadible(item.getMessage());
            throw error;
        }
    }
}
项目:cuba    文件:ServiceInterceptor.java   
@Nullable
protected ValidateServiceMethodContext getValidateServiceMethodContext(ProceedingJoinPoint ctx) {
    ValidateServiceMethodContext validatedContext = null;
    if (ctx instanceof MethodInvocationProceedingJoinPoint) {
        MethodInvocationProceedingJoinPoint methodInvocationCtx = (MethodInvocationProceedingJoinPoint) ctx;

        Method method = ((MethodSignature) ctx.getSignature()).getMethod();

        Validated validated = getValidated(method, ctx.getSignature().getDeclaringType());
        if (validated != null) {
            Object[] args = methodInvocationCtx.getArgs();
            ExecutableValidator validator = beanValidation.getValidator().forExecutables();

            validatedContext = new ValidateServiceMethodContext(validator, ctx.getThis(),
                    method, args, validated.value());
        }
    }
    return validatedContext;
}
项目:JavaIncrementalParser    文件:ConstructorParametersConstraintsTest.java   
@Test
public void constructorViolationsWhenNullParameters() throws NoSuchMethodException, SecurityException {
       final MyParameter parameter = new MyParameter();

    ExecutableValidator methodValidator = validator.forExecutables();
    Constructor<MyBean2> constructor = MyBean2.class
            .getConstructor(parameter.getClass());

    Set<ConstraintViolation<MyBean2>> constraints = methodValidator
            .validateConstructorParameters(constructor, new Object[] {parameter});

    ConstraintViolation<MyBean2> violation = constraints.iterator().next();
    assertThat(constraints.size(), equalTo(1));
    assertThat(violation.getMessageTemplate(), equalTo("{javax.validation.constraints.NotNull.message}"));
    assertThat(violation.getPropertyPath().toString(), equalTo("MyBean2.arg0.value"));
}
项目:guice-validator    文件:AbstractValidationModule.java   
@Override
protected void configure() {
    final GuiceConstraintValidatorFactory constraintValidatorFactory = new GuiceConstraintValidatorFactory();
    requestInjection(constraintValidatorFactory);

    /* Overriding just constraints factory to allow them use guice injections */
    final Validator validator = factory.usingContext()
            .constraintValidatorFactory(constraintValidatorFactory)
            .getValidator();

    bind(Validator.class).toInstance(validator);
    bind(ExecutableValidator.class).toInstance(validator.forExecutables());
    bind(ValidatorFactory.class).toInstance(factory);

    bindConstant().annotatedWith(Names.named("guice.validator.addDefaultGroup")).to(addDefaultGroup);
    final ValidationGroupInterceptor groupInterceptor = new ValidationGroupInterceptor();
    requestInjection(groupInterceptor);
    configureGroupsAop(groupInterceptor);

    final ValidationMethodInterceptor interceptor = new ValidationMethodInterceptor();
    requestInjection(interceptor);
    configureAop(interceptor);
}
项目:wisdom    文件:ValidationTest.java   
@Test
public void testMethodParameters() throws NoSuchMethodException {
    ExecutableValidator executableValidator = validator.forExecutables();
    Method method = RentalStation.class.getMethod("rentCar", String.class, Date.class,
            Integer.TYPE);
    RentalStation station = new RentalStation("hertz", "");
    Set<ConstraintViolation<RentalStation>> violations = executableValidator.validateParameters(
            station, method, new Object[]{"Clement", new Date(System.currentTimeMillis() + 10000), 1});
    assertThat(violations.size()).isEqualTo(0);
    violations = executableValidator.validateParameters(
            station, method, new Object[]{"Clement", new Date(System.currentTimeMillis() - 10000), 1});
    assertThat(violations.size()).isEqualTo(1);
    violations = executableValidator.validateParameters(
            station, method, new Object[]{"Clement", new Date(System.currentTimeMillis() - 10000), 0});
    assertThat(violations.size()).isEqualTo(2);
    violations = executableValidator.validateParameters(
            station, method, new Object[]{null, new Date(System.currentTimeMillis() - 10000), 0});
    assertThat(violations.size()).isEqualTo(3);
}
项目:wisdom    文件:ValidationIT.java   
@Test
public void testMethodParameters() throws NoSuchMethodException {
    ExecutableValidator executableValidator = validator.forExecutables();
    Method method = RentalStation.class.getMethod("rentCar", String.class, Date.class,
            Integer.TYPE);
    RentalStation station = new RentalStation("hertz", "");
    Set<ConstraintViolation<RentalStation>> violations = executableValidator.validateParameters(
            station, method, new Object[]{"Clement", new Date(System.currentTimeMillis() + 10000), 1});
    assertThat(violations.size()).isEqualTo(0);
    violations = executableValidator.validateParameters(
            station, method, new Object[]{"Clement", new Date(System.currentTimeMillis() - 10000), 1});
    assertThat(violations.size()).isEqualTo(1);
    violations = executableValidator.validateParameters(
            station, method, new Object[]{"Clement", new Date(System.currentTimeMillis() - 10000), 0});
    assertThat(violations.size()).isEqualTo(2);
    violations = executableValidator.validateParameters(
            station, method, new Object[]{null, new Date(System.currentTimeMillis() - 10000), 0});
    assertThat(violations.size()).isEqualTo(3);
}
项目:ozark    文件:ValidationInterceptor.java   
@AroundInvoke
public Object validateMethodInvocation(InvocationContext ctx) throws Exception {

    Object resource = ctx.getTarget();
    Method method = ctx.getMethod();

    log.log(Level.FINE, "Starting validation for controller method: {0}#{1}", new Object[]{
            resource.getClass().getName(), method.getName()
    });

    Validator validator = validatorFactory.getValidator();
    ExecutableValidator executableValidator = validator.forExecutables();

    // validate controller property parameters
    processViolations(ctx,
            validator.validate(resource)
    );

    // validate controller method parameters
    processViolations(ctx,
            executableValidator.validateParameters(resource, method, ctx.getParameters())
    );

    // execute method
    Object result = ctx.proceed();

    // TODO: Does this make sense? Nobody will be able to handle these. Remove?
    processViolations(ctx,
            executableValidator.validateReturnValue(resource, method, result)
    );

    return result;

}
项目:microbule    文件:ValidationInterceptor.java   
@Override
public void handleMessage(Message message) {
    final List<Object> arguments = MessageContentsList.getContentsList(message);
    if (!arguments.isEmpty()) {
        final Object instance = message.getExchange().get(Message.SERVICE_OBJECT);
        final Method method = (Method) message.get(METHOD_KEY);
        final ExecutableValidator methodValidator = validator.forExecutables();
        final Class<?>[] groups = Optional.ofNullable(method.getAnnotation(Groups.class)).map(Groups::value).orElse(DEFAULT_GROUPS);
        final Set<ConstraintViolation<Object>> violations = methodValidator.validateParameters(instance, method, arguments.toArray(), groups);
        if (!violations.isEmpty()) {
            message.put(FaultListener.class.getName(), new NoOpFaultListener());
            throw new JaxrsServerValidationException(violations);
        }
    }
}
项目:cuba    文件:ServiceInterceptor.java   
protected void validateMethodParameters(ProceedingJoinPoint ctx,
                                        @Nullable ValidateServiceMethodContext validatedContext) {
    if (validatedContext != null) {
        log.trace("Validating service call params: {}", ctx.getSignature());

        ExecutableValidator validator = validatedContext.getValidator();

        Class[] constraintGroups = validatedContext.getGroups();
        if (constraintGroups.length == 0) {
            constraintGroups = new Class[]{Default.class, ServiceParametersChecks.class};
        }

        Set<ConstraintViolation<Object>> violations = validator.validateParameters(
                validatedContext.getTarget(),
                validatedContext.getMethod(),
                validatedContext.getArgs(),
                constraintGroups);

        if (!violations.isEmpty()) {
            Class serviceInterface = ctx.getSignature().getDeclaringType();
            Set<ConstraintViolation<Object>> resultViolations = violations.stream()
                    .map(violation -> new ServiceMethodConstraintViolation(serviceInterface, violation))
                    .collect(Collectors.toSet());

            throw new MethodParametersValidationException("Service method parameters validation failed", resultViolations);
        }
    }
}
项目:cuba    文件:ServiceInterceptor.java   
protected void validateMethodResult(ProceedingJoinPoint ctx, ValidateServiceMethodContext validatedContext,
                                    Object methodResult) {
    if (validatedContext != null) {
        ExecutableValidator validator = validatedContext.getValidator();

        log.trace("Validating service call result: {}", ctx.getSignature());

        Class[] constraintGroups = validatedContext.getGroups();
        if (constraintGroups.length == 0) {
            constraintGroups = new Class[]{Default.class, ServiceResultChecks.class};
        }

        Set<ConstraintViolation<Object>> violations = validator.validateReturnValue(
                validatedContext.getTarget(),
                validatedContext.getMethod(),
                methodResult,
                constraintGroups);

        if (!violations.isEmpty()) {
            Class serviceInterface = ctx.getSignature().getDeclaringType();
            Set<ConstraintViolation<Object>> paramsViolations = violations.stream()
                    .map(violation -> new ServiceMethodConstraintViolation(serviceInterface, violation))
                    .collect(Collectors.toSet());

            throw new MethodResultValidationException("Service method result validation failed", paramsViolations);
        }
    }
}
项目:cuba    文件:ServiceInterceptor.java   
public ValidateServiceMethodContext(ExecutableValidator validator, Object target, Method method, Object[] args,  Class[] groups) {
    this.validator = validator;
    this.target = target;
    this.method = method;
    this.args = args;
    this.groups = groups;
}
项目:carbon-device-mgt    文件:ValidationInterceptor.java   
public <T> void validate(final Method method, final Object[] arguments, final T instance) {
    if (validator == null) {
        log.warn("Bean Validation provider could not be found, no validation will be performed");
        return;
    }

    ExecutableValidator methodValidator = validator.forExecutables();
    Set<ConstraintViolation<T>> violations = methodValidator.validateParameters(instance,
            method, arguments);

    if (!violations.isEmpty()) {
        throw new ConstraintViolationException(violations);
    }
}
项目:carbon-device-mgt    文件:ValidationInterceptor.java   
public <T> void validate(final Method method, final Object[] arguments, final T instance) {
    if (validator == null) {
        log.warn("Bean Validation provider could not be found, no validation will be performed");
        return;
    }

    ExecutableValidator methodValidator = validator.forExecutables();
    Set<ConstraintViolation<T>> violations = methodValidator.validateParameters(instance,
            method, arguments);

    if (!violations.isEmpty()) {
        throw new ConstraintViolationException(violations);
    }
}
项目:sdcct    文件:SdcctValidatorFactoryBean.java   
@Nullable
@Override
public ExecutableValidator forExecutables() {
    Validator validator = this.getValidator();

    return ((validator instanceof ExecutableValidator) ? ((ExecutableValidator) validator) : null);
}
项目:actframework    文件:ParamValueLoaderService.java   
private ExecutableValidator executableValidator() {
    if (null == executableValidator) {
        synchronized (this) {
            if (null == executableValidator) {
                validator = Act.getInstance(Validator.class);
                executableValidator = validator.forExecutables();
            }
        }
    }
    return executableValidator;
}
项目:JavaIncrementalParser    文件:ConstructorParametersConstraintsTest.java   
@Test
public void constructorViolationsWhenNotNullParameters() throws NoSuchMethodException, SecurityException {
    final MyParameter parameter = new MyParameter();
       parameter.setValue("foo");

       ExecutableValidator methodValidator = validator.forExecutables();
    Constructor<MyBean2> constructor = MyBean2.class
            .getConstructor(parameter.getClass());

    Set<ConstraintViolation<MyBean2>> constraints = methodValidator
            .validateConstructorParameters(constructor, new Object[] {parameter});

    assertThat(constraints.isEmpty(), equalTo(true));
}
项目:laputa    文件:DefaultRequestProcessor.java   
private void validate(Object target, Method method, Object[] args) {
  ExecutableValidator executableValidator = VALIDATOR.forExecutables();
  Set<ConstraintViolation<Object>> violations = executableValidator.validateParameters(target, method, args);
  if (violations.isEmpty()) {
    return;
  }

  throw new ParameterValidationException(violations);
}
项目:wisdom    文件:ValidationTest.java   
@Test
public void testConstructorParameters() throws NoSuchMethodException {
    ExecutableValidator executableValidator = validator.forExecutables();
    Constructor<RentalStation> constructor = RentalStation.class.getConstructor(String.class, String.class);
    Set<ConstraintViolation<RentalStation>> violations = executableValidator.validateConstructorParameters
            (constructor, new Object[] {"Hertz", ""});
    assertThat(violations.size()).isEqualTo(0);
    violations = executableValidator.validateConstructorParameters
            (constructor, new Object[] {null, ""});
    assertThat(violations.size()).isEqualTo(1);
    violations = executableValidator.validateConstructorParameters
            (constructor, new Object[] {null, null});
    assertThat(violations.size()).isEqualTo(2);
}
项目:wisdom    文件:ValidationIT.java   
@Test
public void testConstructorParameters() throws NoSuchMethodException {
    ExecutableValidator executableValidator = validator.forExecutables();
    Constructor<RentalStation> constructor = RentalStation.class.getConstructor(String.class, String.class);
    Set<ConstraintViolation<RentalStation>> violations = executableValidator.validateConstructorParameters
            (constructor, new Object[] {"Hertz", ""});
    assertThat(violations.size()).isEqualTo(0);
    violations = executableValidator.validateConstructorParameters
            (constructor, new Object[] {null, ""});
    assertThat(violations.size()).isEqualTo(1);
    violations = executableValidator.validateConstructorParameters
            (constructor, new Object[] {null, null});
    assertThat(violations.size()).isEqualTo(2);
}
项目:crest    文件:BeanValidation11.java   
@Override
public void validateParameters(final Object instanceOrClass, final Method method, final Object[] parameters) {
    if (instanceOrClass == null) { // bval 11 doesnt support it
        return;
    }
    final ExecutableValidator executableValidator = validatorFactory.getValidator().forExecutables();
    final Set<ConstraintViolation<Object>> violations = executableValidator.validateParameters(instanceOrClass, method, parameters);
    if (!violations.isEmpty()) {
        throw new ConstraintViolationException(violations);
    }
}
项目:crest    文件:BeanValidation11.java   
@Override
public void validateParameters(final Constructor constructor, final Object[] parameters) {
    final ExecutableValidator executableValidator = validatorFactory.getValidator().forExecutables();
    final Set<ConstraintViolation<?>> violations = executableValidator.validateConstructorParameters(constructor, parameters);
    if (!violations.isEmpty()) {
        throw new ConstraintViolationException(violations);
    }
}
项目:minijax    文件:MinijaxValidator.java   
@Override
public ExecutableValidator forExecutables() {
    return this;
}
项目:my-spring-cache-redis    文件:SpringValidatorAdapter.java   
@Override
public ExecutableValidator forExecutables() {
    // TODO Auto-generated method stub
    return null;
}
项目:my-spring-cache-redis    文件:LocalValidatorFactoryBean.java   
@Override
public ExecutableValidator forExecutables() {
    // TODO Auto-generated method stub
    return null;
}
项目:ozark    文件:ConstraintViolationsTest.java   
private List<ConstraintViolation<?>> simulateValidation(Object controller, String methodName, Object... args) {

        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

        Validator validator = validatorFactory.getValidator();
        ExecutableValidator executableValidator = validator.forExecutables();

        List<ConstraintViolation<?>> result = new ArrayList<>();

        // validate controller fields
        result.addAll(validator.validate(controller));

        // controller method parameters
        Method method = getFirstMethod(controller.getClass(), methodName);
        result.addAll(executableValidator.validateParameters(controller, method, args));

        return result;

    }
项目:cuba    文件:TestBeanValidation.java   
@Override
public ExecutableValidator forExecutables() {
    return null;
}
项目:cuba    文件:ServiceInterceptor.java   
public ExecutableValidator getValidator() {
    return validator;
}
项目:cuba    文件:ServiceInterceptor.java   
public void setValidator(ExecutableValidator validator) {
    this.validator = validator;
}
项目:nexus-public    文件:ValidationModule.java   
@Provides
@Singleton
ExecutableValidator executableValidator(final Validator validator) {
  return validator.forExecutables();
}
项目:tripled-framework    文件:TestValidator.java   
@Override
public ExecutableValidator forExecutables() {
  return null;
}
项目:gwt-bean-validators    文件:AbstractGwtValidator.java   
@Override
public ExecutableValidator forExecutables() {
  // TODO Auto-generated method stub
  return null;
}
项目:sinavi-jfw    文件:Validations.java   
public static ExecutableValidator getExecutableValitaror() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    return factory.getValidator().forExecutables();
}
项目:tomee    文件:CustomValidatorProvider.java   
@Override
public ExecutableValidator forExecutables() {
    return null;
}
项目:wisdom    文件:WrappedValidator.java   
@Override
public ExecutableValidator forExecutables() {
    return new WrappedExecutableValidator(delegate.forExecutables());
}
项目:wisdom    文件:WrappedExecutableValidator.java   
WrappedExecutableValidator(ExecutableValidator delegate) {
    this.delegate = delegate;
}
项目:druid-api    文件:JsonConfiguratorTest.java   
@Override
public ExecutableValidator forExecutables()
{
  return null;
}