Search in sources :

Example 6 with Validator

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

the class BeanValidationEventListener method validate.

private <T> void validate(T object, EntityMode mode, EntityPersister persister, SessionFactoryImplementor sessionFactory, GroupsPerOperation.Operation operation) {
    if (object == null || mode != EntityMode.POJO) {
        return;
    }
    TraversableResolver tr = new HibernateTraversableResolver(persister, associationsPerEntityPersister, sessionFactory);
    Validator validator = factory.usingContext().traversableResolver(tr).getValidator();
    final Class<?>[] groups = groupsPerOperation.get(operation);
    if (groups.length > 0) {
        final Set<ConstraintViolation<T>> constraintViolations = validator.validate(object, groups);
        if (constraintViolations.size() > 0) {
            Set<ConstraintViolation<?>> propagatedViolations = new HashSet<ConstraintViolation<?>>(constraintViolations.size());
            Set<String> classNames = new HashSet<String>();
            for (ConstraintViolation<?> violation : constraintViolations) {
                LOG.trace(violation);
                propagatedViolations.add(violation);
                classNames.add(violation.getLeafBean().getClass().getName());
            }
            StringBuilder builder = new StringBuilder();
            builder.append("Validation failed for classes ");
            builder.append(classNames);
            builder.append(" during ");
            builder.append(operation.getName());
            builder.append(" time for groups ");
            builder.append(toString(groups));
            builder.append("\nList of constraint violations:[\n");
            for (ConstraintViolation<?> violation : constraintViolations) {
                builder.append("\t").append(violation.toString()).append("\n");
            }
            builder.append("]");
            throw new ConstraintViolationException(builder.toString(), propagatedViolations);
        }
    }
}
Also used : TraversableResolver(javax.validation.TraversableResolver) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) Validator(javax.validation.Validator) HashSet(java.util.HashSet)

Example 7 with Validator

use of javax.validation.Validator in project fb-botmill by BotMill.

the class FbBotMillBean method validate.

/**
	 * Validates the {@link FbBotMillResponse}.
	 *
	 * @param response
	 *            the response
	 * @return true if the response is valid, false otherwise.
	 */
protected boolean validate(FbBotMillResponse response) {
    // If validations are not enabled, returns true.
    if (!FbBotMillContext.getInstance().isValidationEnabled()) {
        return true;
    }
    boolean valid = true;
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<FbBotMillResponse>> violations = validator.validate(response);
    for (ConstraintViolation<FbBotMillResponse> v : violations) {
        valid = false;
        logger.error("FbBotMillResponse validation error. Message: [{}] Value: [{}], Class: [{}], Field: [{}]", v.getMessage(), v.getInvalidValue(), v.getRootBean(), v.getPropertyPath());
    }
    if (valid == false) {
        // Sends the constraint violations through the callback.
        List<FbBotMillMonitor> registeredMonitors = FbBotMillContext.getInstance().getRegisteredMonitors();
        for (FbBotMillMonitor monitor : registeredMonitors) {
            monitor.onValidationError(response, violations);
        }
    }
    return valid;
}
Also used : ValidatorFactory(javax.validation.ValidatorFactory) FbBotMillResponse(co.aurasphere.botmill.fb.model.outcoming.FbBotMillResponse) ConstraintViolation(javax.validation.ConstraintViolation) FbBotMillMonitor(co.aurasphere.botmill.fb.support.FbBotMillMonitor) Validator(javax.validation.Validator)

Example 8 with Validator

use of javax.validation.Validator in project apex-core by apache.

the class LogicalPlan method validate.

/**
   * Validate the plan. Includes checks that required ports are connected,
   * required configuration parameters specified, graph free of cycles etc.
   *
   * @throws ConstraintViolationException
   */
public void validate() throws ConstraintViolationException {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    checkAttributeValueSerializable(this.getAttributes(), DAG.class.getName());
    // clear oioRoot values in all operators
    for (OperatorMeta n : operators.values()) {
        n.oioRoot = null;
    }
    // clear visited on all operators
    for (OperatorMeta n : operators.values()) {
        n.nindex = null;
        n.lowlink = null;
        // validate configuration
        Set<ConstraintViolation<Operator>> constraintViolations = validator.validate(n.getOperator());
        if (!constraintViolations.isEmpty()) {
            Set<ConstraintViolation<?>> copySet = new HashSet<>(constraintViolations.size());
            // (should be public <T> ConstraintViolationException(String message, Set<ConstraintViolation<T>> constraintViolations) { ... })
            for (ConstraintViolation<Operator> cv : constraintViolations) {
                copySet.add(cv);
            }
            throw new ConstraintViolationException("Operator " + n.getName() + " violates constraints " + copySet, copySet);
        }
        OperatorMeta.PortMapping portMapping = n.getPortMapping();
        checkAttributeValueSerializable(n.getAttributes(), n.getName());
        // Check operator annotation
        if (n.operatorAnnotation != null) {
            // Check if partition property of the operator is being honored
            if (!n.operatorAnnotation.partitionable()) {
                // Check if any of the input ports have partition attributes set
                for (InputPortMeta pm : portMapping.inPortMap.values()) {
                    Boolean paralellPartition = pm.getValue(PortContext.PARTITION_PARALLEL);
                    if (paralellPartition) {
                        throw new ValidationException("Operator " + n.getName() + " is not partitionable but PARTITION_PARALLEL attribute is set");
                    }
                }
                // Check if the operator implements Partitioner
                if (n.getValue(OperatorContext.PARTITIONER) != null || n.attributes != null && !n.attributes.contains(OperatorContext.PARTITIONER) && Partitioner.class.isAssignableFrom(n.getOperator().getClass())) {
                    throw new ValidationException("Operator " + n.getName() + " provides partitioning capabilities but the annotation on the operator class declares it non partitionable!");
                }
            }
            // a multiple of application window count
            if (!n.operatorAnnotation.checkpointableWithinAppWindow()) {
                if (n.getValue(OperatorContext.CHECKPOINT_WINDOW_COUNT) % n.getValue(OperatorContext.APPLICATION_WINDOW_COUNT) != 0) {
                    throw new ValidationException("Operator " + n.getName() + " cannot be check-pointed between an application window " + "but the checkpoint-window-count " + n.getValue(OperatorContext.CHECKPOINT_WINDOW_COUNT) + " is not a multiple application-window-count " + n.getValue(OperatorContext.APPLICATION_WINDOW_COUNT));
                }
            }
        }
        // check that non-optional ports are connected
        for (InputPortMeta pm : portMapping.inPortMap.values()) {
            checkAttributeValueSerializable(pm.getAttributes(), n.getName() + "." + pm.getPortName());
            StreamMeta sm = n.inputStreams.get(pm);
            if (sm == null) {
                if ((pm.portAnnotation == null || !pm.portAnnotation.optional()) && pm.classDeclaringHiddenPort == null) {
                    throw new ValidationException("Input port connection required: " + n.name + "." + pm.getPortName());
                }
            } else {
                if (pm.classDeclaringHiddenPort != null) {
                    throw new ValidationException(String.format("Invalid port connected: %s.%s is hidden by %s.%s", pm.classDeclaringHiddenPort.getName(), pm.getPortName(), pm.operatorMeta.getOperator().getClass().getName(), pm.getPortName()));
                }
                // check locality constraints
                DAG.Locality locality = sm.getLocality();
                if (locality == DAG.Locality.THREAD_LOCAL) {
                    if (n.inputStreams.size() > 1) {
                        validateThreadLocal(n);
                    }
                }
                if (pm.portAnnotation != null && pm.portAnnotation.schemaRequired()) {
                    //since schema is required, the port attribute TUPLE_CLASS should be present
                    if (pm.attributes.get(PortContext.TUPLE_CLASS) == null) {
                        throw new ValidationException("Attribute " + PortContext.TUPLE_CLASS.getName() + " missing on port : " + n.name + "." + pm.getPortName());
                    }
                }
            }
        }
        for (OutputPortMeta pm : portMapping.outPortMap.values()) {
            checkAttributeValueSerializable(pm.getAttributes(), n.getName() + "." + pm.getPortName());
            if (!n.outputStreams.containsKey(pm)) {
                if ((pm.portAnnotation != null && !pm.portAnnotation.optional()) && pm.classDeclaringHiddenPort == null) {
                    throw new ValidationException("Output port connection required: " + n.name + "." + pm.getPortName());
                }
            } else {
                //port is connected
                if (pm.classDeclaringHiddenPort != null) {
                    throw new ValidationException(String.format("Invalid port connected: %s.%s is hidden by %s.%s", pm.classDeclaringHiddenPort.getName(), pm.getPortName(), pm.operatorMeta.getOperator().getClass().getName(), pm.getPortName()));
                }
                if (pm.portAnnotation != null && pm.portAnnotation.schemaRequired()) {
                    //since schema is required, the port attribute TUPLE_CLASS should be present
                    if (pm.attributes.get(PortContext.TUPLE_CLASS) == null) {
                        throw new ValidationException("Attribute " + PortContext.TUPLE_CLASS.getName() + " missing on port : " + n.name + "." + pm.getPortName());
                    }
                }
            }
        }
    }
    ValidationContext validatonContext = new ValidationContext();
    for (OperatorMeta n : operators.values()) {
        if (n.nindex == null) {
            findStronglyConnected(n, validatonContext);
        }
    }
    if (!validatonContext.invalidCycles.isEmpty()) {
        throw new ValidationException("Loops in graph: " + validatonContext.invalidCycles);
    }
    List<List<String>> invalidDelays = new ArrayList<>();
    for (OperatorMeta n : rootOperators) {
        findInvalidDelays(n, invalidDelays, new Stack<OperatorMeta>());
    }
    if (!invalidDelays.isEmpty()) {
        throw new ValidationException("Invalid delays in graph: " + invalidDelays);
    }
    for (StreamMeta s : streams.values()) {
        if (s.source == null) {
            throw new ValidationException("Stream source not connected: " + s.getName());
        }
        if (s.sinks.isEmpty()) {
            throw new ValidationException("Stream sink not connected: " + s.getName());
        }
    }
    // Validate root operators are input operators
    for (OperatorMeta om : this.rootOperators) {
        if (!(om.getOperator() instanceof InputOperator)) {
            throw new ValidationException(String.format("Root operator: %s is not a Input operator", om.getName()));
        }
    }
    // processing mode
    Set<OperatorMeta> visited = Sets.newHashSet();
    for (OperatorMeta om : this.rootOperators) {
        validateProcessingMode(om, visited);
    }
    validateAffinityRules();
}
Also used : Operator(com.datatorrent.api.Operator) InputOperator(com.datatorrent.api.InputOperator) ValidationException(javax.validation.ValidationException) ArrayList(java.util.ArrayList) ConstraintViolationException(javax.validation.ConstraintViolationException) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) ValidatorFactory(javax.validation.ValidatorFactory) DAG(com.datatorrent.api.DAG) ConstraintViolation(javax.validation.ConstraintViolation) InputOperator(com.datatorrent.api.InputOperator) Validator(javax.validation.Validator)

Example 9 with Validator

use of javax.validation.Validator in project apex-core by apache.

the class LogicalPlanTest method testOperatorValidation.

@Test
public void testOperatorValidation() {
    ValidationTestOperator bean = new ValidationTestOperator();
    bean.stringField1 = "malhar1";
    bean.intField1 = 1;
    // ensure validation standalone produces expected results
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<ValidationTestOperator>> constraintViolations = validator.validate(bean);
    Assert.assertEquals("" + constraintViolations, 1, constraintViolations.size());
    ConstraintViolation<ValidationTestOperator> cv = constraintViolations.iterator().next();
    Assert.assertEquals("", bean.intField1, cv.getInvalidValue());
    Assert.assertEquals("", "intField1", cv.getPropertyPath().toString());
    // ensure DAG validation produces matching results
    bean = dag.addOperator("testOperator", bean);
    try {
        dag.validate();
        Assert.fail("should throw ConstraintViolationException");
    } catch (ConstraintViolationException e) {
        Assert.assertEquals("violation details", constraintViolations, e.getConstraintViolations());
        String expRegex = ".*ValidationTestOperator\\{name=null}, propertyPath='intField1', message='must be greater than or equal to 2',.*value=1}]";
        Assert.assertThat("exception message", e.getMessage(), RegexMatcher.matches(expRegex));
    }
    try {
        bean.intField1 = 3;
        dag.validate();
        Assert.fail("should throw ConstraintViolationException");
    } catch (ConstraintViolationException e) {
        ConstraintViolation<?> cv2 = e.getConstraintViolations().iterator().next();
        Assert.assertEquals("" + e.getConstraintViolations(), 1, constraintViolations.size());
        Assert.assertEquals("", false, cv2.getInvalidValue());
        Assert.assertEquals("", "validConfiguration", cv2.getPropertyPath().toString());
    }
    bean.stringField1 = "malhar3";
    // annotated getter
    try {
        bean.getterProperty2 = null;
        dag.validate();
        Assert.fail("should throw ConstraintViolationException");
    } catch (ConstraintViolationException e) {
        ConstraintViolation<?> cv2 = e.getConstraintViolations().iterator().next();
        Assert.assertEquals("" + e.getConstraintViolations(), 1, constraintViolations.size());
        Assert.assertEquals("", null, cv2.getInvalidValue());
        Assert.assertEquals("", "property2", cv2.getPropertyPath().toString());
    }
    bean.getterProperty2 = "";
    // nested property
    try {
        bean.nestedBean.property = null;
        dag.validate();
        Assert.fail("should throw ConstraintViolationException");
    } catch (ConstraintViolationException e) {
        ConstraintViolation<?> cv2 = e.getConstraintViolations().iterator().next();
        Assert.assertEquals("" + e.getConstraintViolations(), 1, constraintViolations.size());
        Assert.assertEquals("", null, cv2.getInvalidValue());
        Assert.assertEquals("", "nestedBean.property", cv2.getPropertyPath().toString());
    }
    bean.nestedBean.property = "";
    // all valid
    dag.validate();
}
Also used : ValidatorFactory(javax.validation.ValidatorFactory) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) Validator(javax.validation.Validator) Test(org.junit.Test)

Example 10 with Validator

use of javax.validation.Validator in project wildfly by wildfly.

the class GroupandGroupSequenceValidationTestCase method testGroupValidation.

@Test
public void testGroupValidation() throws NamingException {
    Validator validator = (Validator) new InitialContext().lookup("java:comp/Validator");
    // create first passenger
    UserBean user1 = new UserBean("MADHUMITA", "SADHUKHAN");
    user1.setEmail("madhu@gmail.com");
    user1.setAddress("REDHAT Brno");
    // create second passenger
    UserBean user2 = new UserBean("Mickey", "Mouse");
    user2.setEmail("mickey@gmail.com");
    user2.setAddress("DISNEY CA USA");
    List<UserBean> passengers = new ArrayList<UserBean>();
    passengers.add(user1);
    passengers.add(user2);
    // Create a Car
    Car car = new Car("CET5678", passengers);
    car.setModel("SKODA Octavia");
    // validate Car with default group as per GroupSequenceProvider
    Set<ConstraintViolation<Car>> result = validator.validate(car);
    assertEquals(1, result.size());
    assertEquals("The Car has to pass the fuel test and inspection test before being driven", result.iterator().next().getMessage());
    Driver driver = new Driver("Sebastian", "Vettel");
    driver.setAge(25);
    driver.setAddress("ABC");
    result = validator.validate(car);
    assertEquals(1, result.size());
    assertEquals("The Car has to pass the fuel test and inspection test before being driven", result.iterator().next().getMessage());
    car.setPassedVehicleInspection(true);
    result = validator.validate(car);
    // New group set in defaultsequence for Car as per CarGroupSequenceProvider should be implemented now
    assertEquals(2, result.size());
    car.setDriver(driver);
    // implementing validation for group associated with associated objects of Car(in this case Driver)
    Set<ConstraintViolation<Car>> driverResult = validator.validate(car, DriverChecks.class);
    assertEquals(1, driverResult.size());
    driver.setHasValidDrivingLicense(true);
    assertEquals(0, validator.validate(car, DriverChecks.class).size());
    car.setSeats(5);
    car.setHasBeenPaid(true);
    assertEquals(0, validator.validate(car).size());
}
Also used : ConstraintViolation(javax.validation.ConstraintViolation) ArrayList(java.util.ArrayList) Validator(javax.validation.Validator) InitialContext(javax.naming.InitialContext) Test(org.junit.Test)

Aggregations

Validator (javax.validation.Validator)42 Test (org.junit.Test)25 ConstraintViolation (javax.validation.ConstraintViolation)19 ValidatorFactory (javax.validation.ValidatorFactory)13 InitialContext (javax.naming.InitialContext)8 ArrayList (java.util.ArrayList)5 HibernateValidator (org.hibernate.validator.HibernateValidator)5 File (java.io.File)4 NamingException (javax.naming.NamingException)4 ConstraintViolationException (javax.validation.ConstraintViolationException)4 Title (net.thucydides.core.annotations.Title)4 HibernateValidatorConfiguration (org.hibernate.validator.HibernateValidatorConfiguration)4 PodamFactory (uk.co.jemos.podam.api.PodamFactory)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 HashSet (java.util.HashSet)3 Context (javax.naming.Context)3 OpenEJBException (org.apache.openejb.OpenEJBException)3 HibernateValidatorFactory (org.hibernate.validator.HibernateValidatorFactory)3 IOException (java.io.IOException)2 MalformedURLException (java.net.MalformedURLException)2