Search in sources :

Example 61 with ConstraintViolationException

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

the class JValidator method validate.

public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
    List<Class<?>> groups = new ArrayList<Class<?>>();
    String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName);
    Class<?> methodClass = null;
    try {
        methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
        groups.add(methodClass);
    } catch (ClassNotFoundException e) {
    }
    Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
    Method method = clazz.getMethod(methodName, parameterTypes);
    Class<?>[] methodClasses = null;
    if (method.isAnnotationPresent(MethodValidated.class)) {
        methodClasses = method.getAnnotation(MethodValidated.class).value();
        groups.addAll(Arrays.asList(methodClasses));
    }
    // add into default group
    groups.add(0, Default.class);
    groups.add(1, clazz);
    // convert list to array
    Class<?>[] classgroups = groups.toArray(new Class[0]);
    Object parameterBean = getMethodParameterBean(clazz, method, arguments);
    if (parameterBean != null) {
        violations.addAll(validator.validate(parameterBean, classgroups));
    }
    for (Object arg : arguments) {
        validate(violations, arg, classgroups);
    }
    if (!violations.isEmpty()) {
        logger.error("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations);
        throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
    }
}
Also used : ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) CtClass(javassist.CtClass) HashSet(java.util.HashSet)

Example 62 with ConstraintViolationException

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

the class ValidationConsumer method main.

public static void main(String[] args) throws Exception {
    String config = ValidationConsumer.class.getPackage().getName().replace('.', '/') + "/validation-consumer.xml";
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);
    context.start();
    ValidationService validationService = (ValidationService) context.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);
    System.out.println("Validation Save OK");
    // Save Error
    try {
        parameter = new ValidationParameter();
        validationService.save(parameter);
        System.err.println("Validation Save ERROR");
    } catch (Exception e) {
        ConstraintViolationException ve = (ConstraintViolationException) e;
        Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
        System.out.println(violations);
    }
    // Delete OK
    validationService.delete(2, "abc");
    System.out.println("Validation Delete OK");
    // Delete Error
    try {
        validationService.delete(0, "abc");
        System.err.println("Validation Delete ERROR");
    } catch (Exception e) {
        ConstraintViolationException ve = (ConstraintViolationException) e;
        Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
        System.out.println(violations);
    }
}
Also used : Set(java.util.Set) ValidationParameter(com.alibaba.dubbo.examples.validation.api.ValidationParameter) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ConstraintViolationException(javax.validation.ConstraintViolationException) ValidationService(com.alibaba.dubbo.examples.validation.api.ValidationService) Date(java.util.Date) ConstraintViolationException(javax.validation.ConstraintViolationException)

Example 63 with ConstraintViolationException

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

the class DefaultConfiguredValidator method onValidate.

// Invoked as the last validation interceptor method in the chain.
@Override
public void onValidate(final ValidationInterceptorContext ctx) {
    final Object resource = ctx.getResource();
    final Invocable resourceMethod = ctx.getInvocable();
    final Object[] args = ctx.getArgs();
    final Set<ConstraintViolation<Object>> constraintViolations = new HashSet<>();
    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);
    }
}
Also used : Invocable(org.glassfish.jersey.server.model.Invocable) 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 64 with ConstraintViolationException

use of javax.validation.ConstraintViolationException in project hibernate-orm by hibernate.

the class BeanValidationDisabledTest method testListeners.

@Test
public void testListeners() {
    CupHolder ch = new CupHolder();
    ch.setRadius(new BigDecimal("12"));
    Session s = openSession();
    Transaction tx = s.beginTransaction();
    try {
        s.persist(ch);
        s.flush();
    } catch (ConstraintViolationException e) {
        fail("invalid object should not be validated");
    }
    tx.rollback();
    s.close();
}
Also used : Transaction(org.hibernate.Transaction) ConstraintViolationException(javax.validation.ConstraintViolationException) BigDecimal(java.math.BigDecimal) Session(org.hibernate.Session) Test(org.junit.Test)

Example 65 with ConstraintViolationException

use of javax.validation.ConstraintViolationException in project hibernate-orm by hibernate.

the class BeanValidationTest method testBeanValidationIntegrationOnCommit.

@Test
public void testBeanValidationIntegrationOnCommit() {
    CupHolder ch = new CupHolder();
    ch.setRadius(new BigDecimal("9"));
    ch.setTitle("foo");
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    em.persist(ch);
    em.flush();
    try {
        ch.setRadius(new BigDecimal("12"));
        em.getTransaction().commit();
        fail("invalid object should not be persisted");
    } catch (RollbackException e) {
        final Throwable cve = e.getCause();
        assertTrue(cve instanceof ConstraintViolationException);
        assertEquals(1, ((ConstraintViolationException) cve).getConstraintViolations().size());
    }
    em.close();
}
Also used : EntityManager(javax.persistence.EntityManager) ConstraintViolationException(javax.validation.ConstraintViolationException) RollbackException(javax.persistence.RollbackException) BigDecimal(java.math.BigDecimal) Test(org.junit.Test)

Aggregations

ConstraintViolationException (javax.validation.ConstraintViolationException)87 Test (org.junit.Test)67 LocalMode (com.datatorrent.api.LocalMode)35 Configuration (org.apache.hadoop.conf.Configuration)34 File (java.io.File)16 ConstraintViolation (javax.validation.ConstraintViolation)15 Session (org.hibernate.Session)11 Transaction (org.hibernate.Transaction)11 LogicalPlan (com.datatorrent.stram.plan.logical.LogicalPlan)9 Map (java.util.Map)9 BigDecimal (java.math.BigDecimal)7 HashMap (java.util.HashMap)7 Set (java.util.Set)6 StramLocalCluster (com.datatorrent.stram.StramLocalCluster)5 ConfigApiTest (com.sun.enterprise.configapi.tests.ConfigApiTest)5 HashSet (java.util.HashSet)5 ValidationException (javax.validation.ValidationException)5 Validator (javax.validation.Validator)5 Response (javax.ws.rs.core.Response)5 Path (org.apache.hadoop.fs.Path)5