Search in sources :

Example 1 with ConstraintViolationException

use of javax.validation.ConstraintViolationException in project dubbo by alibaba.

the class ValidationTest method testValidation.

@Test
public void testValidation() {
    ServiceConfig<ValidationService> service = new ServiceConfig<ValidationService>();
    service.setApplication(new ApplicationConfig("validation-provider"));
    service.setRegistry(new RegistryConfig("N/A"));
    service.setProtocol(new ProtocolConfig("dubbo", 29582));
    service.setInterface(ValidationService.class.getName());
    service.setRef(new ValidationServiceImpl());
    service.setValidation(String.valueOf(true));
    service.export();
    try {
        ReferenceConfig<ValidationService> reference = new ReferenceConfig<ValidationService>();
        reference.setApplication(new ApplicationConfig("validation-consumer"));
        reference.setInterface(ValidationService.class);
        reference.setUrl("dubbo://127.0.0.1:29582?scope=remote&validation=true");
        ValidationService validationService = reference.get();
        try {
            // Save OK
            ValidationParameter parameter = new ValidationParameter();
            parameter.setName("liangfei");
            parameter.setEmail("liangfei@liang.fei");
            parameter.setAge(50);
            parameter.setLoginDate(new Date(System.currentTimeMillis() - 1000000));
            parameter.setExpiryDate(new Date(System.currentTimeMillis() + 1000000));
            validationService.save(parameter);
            try {
                parameter = new ValidationParameter();
                parameter.setName("l");
                parameter.setEmail("liangfei@liang.fei");
                parameter.setAge(50);
                parameter.setLoginDate(new Date(System.currentTimeMillis() - 1000000));
                parameter.setExpiryDate(new Date(System.currentTimeMillis() + 1000000));
                validationService.save(parameter);
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
            }
            // Save Error
            try {
                parameter = new ValidationParameter();
                validationService.save(parameter);
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
            }
            // Delete OK
            validationService.delete(2, "abc");
            // Delete Error
            try {
                validationService.delete(2, "a");
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
                Assert.assertEquals(1, violations.size());
            }
            // Delete Error
            try {
                validationService.delete(0, "abc");
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
                Assert.assertEquals(1, violations.size());
            }
            try {
                validationService.delete(2, null);
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
                Assert.assertEquals(1, violations.size());
            }
            try {
                validationService.delete(0, null);
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
                Assert.assertEquals(2, violations.size());
            }
        } finally {
            reference.destroy();
        }
    } finally {
        service.unexport();
    }
}
Also used : RegistryConfig(com.alibaba.dubbo.config.RegistryConfig) Set(java.util.Set) Date(java.util.Date) ServiceConfig(com.alibaba.dubbo.config.ServiceConfig) ApplicationConfig(com.alibaba.dubbo.config.ApplicationConfig) ReferenceConfig(com.alibaba.dubbo.config.ReferenceConfig) RpcException(com.alibaba.dubbo.rpc.RpcException) ConstraintViolationException(javax.validation.ConstraintViolationException) ProtocolConfig(com.alibaba.dubbo.config.ProtocolConfig) Test(org.junit.Test)

Example 2 with ConstraintViolationException

use of javax.validation.ConstraintViolationException in project dubbo by alibaba.

the class ValidationTest method testValidation.

@Test
public void testValidation() {
    ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(ValidationTest.class.getPackage().getName().replace('.', '/') + "/validation-provider.xml");
    providerContext.start();
    try {
        ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext(ValidationTest.class.getPackage().getName().replace('.', '/') + "/validation-consumer.xml");
        consumerContext.start();
        try {
            ValidationService validationService = (ValidationService) consumerContext.getBean("validationService");
            // Save OK
            ValidationParameter parameter = new ValidationParameter();
            parameter.setName("liangfei");
            parameter.setEmail("liangfei@liang.fei");
            parameter.setAge(50);
            parameter.setLoginDate(new Date(System.currentTimeMillis() - 1000000));
            parameter.setExpiryDate(new Date(System.currentTimeMillis() + 1000000));
            validationService.save(parameter);
            try {
                parameter = new ValidationParameter();
                parameter.setName("l");
                parameter.setEmail("liangfei@liang.fei");
                parameter.setAge(50);
                parameter.setLoginDate(new Date(System.currentTimeMillis() - 1000000));
                parameter.setExpiryDate(new Date(System.currentTimeMillis() + 1000000));
                validationService.save(parameter);
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
            }
            // Save Error
            try {
                parameter = new ValidationParameter();
                validationService.save(parameter);
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
            }
            // Delete OK
            validationService.delete(2, "abc");
            // Delete Error
            try {
                validationService.delete(2, "a");
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
                Assert.assertEquals(1, violations.size());
            }
            // Delete Error
            try {
                validationService.delete(0, "abc");
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
                Assert.assertEquals(1, violations.size());
            }
            try {
                validationService.delete(2, null);
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
                Assert.assertEquals(1, violations.size());
            }
            try {
                validationService.delete(0, null);
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
                Assert.assertEquals(2, violations.size());
            }
        } finally {
            consumerContext.stop();
            consumerContext.close();
        }
    } finally {
        providerContext.stop();
        providerContext.close();
    }
}
Also used : Set(java.util.Set) ValidationParameter(com.alibaba.dubbo.examples.validation.api.ValidationParameter) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) RpcException(com.alibaba.dubbo.rpc.RpcException) ConstraintViolationException(javax.validation.ConstraintViolationException) ValidationService(com.alibaba.dubbo.examples.validation.api.ValidationService) Date(java.util.Date) Test(org.junit.Test)

Example 3 with ConstraintViolationException

use of javax.validation.ConstraintViolationException in project jersey by jersey.

the class DefaultConfiguredValidator method validateResult.

@Override
public void validateResult(final Object resource, final Invocable resourceMethod, final Object result) {
    if (configuration.getBootstrapConfiguration().isExecutableValidationEnabled()) {
        final Set<ConstraintViolation<Object>> constraintViolations = new HashSet<>();
        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);
        }
    }
}
Also used : Response(javax.ws.rs.core.Response) BeanDescriptor(javax.validation.metadata.BeanDescriptor) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) Method(java.lang.reflect.Method) MethodDescriptor(javax.validation.metadata.MethodDescriptor) HashSet(java.util.HashSet)

Example 4 with ConstraintViolationException

use of javax.validation.ConstraintViolationException in project jersey by jersey.

the class ValidationExceptionMapper method toResponse.

@Override
public Response toResponse(final ValidationException exception) {
    if (exception instanceof ConstraintViolationException) {
        LOGGER.log(Level.FINER, LocalizationMessages.CONSTRAINT_VIOLATIONS_ENCOUNTERED(), exception);
        final ConstraintViolationException cve = (ConstraintViolationException) exception;
        final Response.ResponseBuilder response = Response.status(ValidationHelper.getResponseStatus(cve));
        // Entity.
        final Object property = config.getProperty(ServerProperties.BV_SEND_ERROR_IN_RESPONSE);
        if (property != null && Boolean.valueOf(property.toString())) {
            final List<Variant> variants = Variant.mediaTypes(MediaType.TEXT_PLAIN_TYPE, MediaType.TEXT_HTML_TYPE, MediaType.APPLICATION_XML_TYPE, MediaType.APPLICATION_JSON_TYPE).build();
            final Variant variant = request.get().selectVariant(variants);
            if (variant != null) {
                response.type(variant.getMediaType());
            } else {
                // default media type which will be used only when none media type from {@value variants} is in accept
                // header of original request.
                // could be settable by configuration property.
                response.type(MediaType.TEXT_PLAIN_TYPE);
            }
            response.entity(new GenericEntity<>(ValidationHelper.constraintViolationToValidationErrors(cve), new GenericType<List<ValidationError>>() {
            }.getType()));
        }
        return response.build();
    } else {
        LOGGER.log(Level.WARNING, LocalizationMessages.VALIDATION_EXCEPTION_RAISED(), exception);
        return Response.serverError().entity(exception.getMessage()).build();
    }
}
Also used : Response(javax.ws.rs.core.Response) Variant(javax.ws.rs.core.Variant) ConstraintViolationException(javax.validation.ConstraintViolationException) List(java.util.List)

Example 5 with ConstraintViolationException

use of javax.validation.ConstraintViolationException in project spring-framework by spring-projects.

the class MethodValidationInterceptor method invoke.

@Override
@SuppressWarnings("unchecked")
public Object invoke(MethodInvocation invocation) throws Throwable {
    Class<?>[] groups = determineValidationGroups(invocation);
    // Standard Bean Validation 1.1 API
    ExecutableValidator execVal = this.validator.forExecutables();
    Method methodToValidate = invocation.getMethod();
    Set<ConstraintViolation<Object>> result;
    try {
        result = execVal.validateParameters(invocation.getThis(), methodToValidate, invocation.getArguments(), groups);
    } catch (IllegalArgumentException ex) {
        // Probably a generic type mismatch between interface and impl as reported in SPR-12237 / HV-1011
        // Let's try to find the bridged method on the implementation class...
        methodToValidate = BridgeMethodResolver.findBridgedMethod(ClassUtils.getMostSpecificMethod(invocation.getMethod(), invocation.getThis().getClass()));
        result = execVal.validateParameters(invocation.getThis(), methodToValidate, invocation.getArguments(), groups);
    }
    if (!result.isEmpty()) {
        throw new ConstraintViolationException(result);
    }
    Object returnValue = invocation.proceed();
    result = execVal.validateReturnValue(invocation.getThis(), methodToValidate, returnValue, groups);
    if (!result.isEmpty()) {
        throw new ConstraintViolationException(result);
    }
    return returnValue;
}
Also used : ExecutableValidator(javax.validation.executable.ExecutableValidator) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) Method(java.lang.reflect.Method)

Aggregations

ConstraintViolationException (javax.validation.ConstraintViolationException)37 Test (org.junit.Test)26 ConstraintViolation (javax.validation.ConstraintViolation)12 Session (org.hibernate.Session)11 Transaction (org.hibernate.Transaction)11 LogicalPlan (com.datatorrent.stram.plan.logical.LogicalPlan)9 BigDecimal (java.math.BigDecimal)7 HashSet (java.util.HashSet)5 Method (java.lang.reflect.Method)4 Set (java.util.Set)4 ValidationException (javax.validation.ValidationException)4 Validator (javax.validation.Validator)4 RpcException (com.alibaba.dubbo.rpc.RpcException)3 RecoverableInputOperator (com.datatorrent.stram.engine.RecoverableInputOperator)3 Date (java.util.Date)3 ValidationParameter (com.alibaba.dubbo.examples.validation.api.ValidationParameter)2 ValidationService (com.alibaba.dubbo.examples.validation.api.ValidationService)2 LocalMode (com.datatorrent.api.LocalMode)2 GenericOperator (com.datatorrent.stram.engine.GenericNodeTest.GenericOperator)2 List (java.util.List)2