You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tomee.apache.org by ra...@apache.org on 2018/10/12 15:00:51 UTC
svn commit: r1843674 [18/22] - in /tomee/deps/branches/bval-2: ./ bundle/
bundle/src/ bundle/src/main/ bundle/src/main/appended-resources/
bundle/src/main/appended-resources/META-INF/ bval-extras/ bval-extras/src/
bval-extras/src/main/ bval-extras/src/...
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/constraints/ZipCodeCityCoherenceValidator.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/constraints/ZipCodeCityCoherenceValidator.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/constraints/ZipCodeCityCoherenceValidator.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/constraints/ZipCodeCityCoherenceValidator.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bval.constraints;
+
+import org.apache.bval.jsr.example.ZipCodeCityCarrier;
+
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+/**
+ * Description: Class not implemented! simple dummy implemenation for tests only! <br/>
+ * User: roman.stumm <br/>
+ * Date: 01.04.2008 <br/>
+ * Time: 11:45:22 <br/>
+ */
+public class ZipCodeCityCoherenceValidator implements ConstraintValidator<ZipCodeCityCoherence, ZipCodeCityCarrier> {
+ @Override
+ public void initialize(ZipCodeCityCoherence constraintAnnotation) {
+ }
+
+ @Override
+ public boolean isValid(ZipCodeCityCarrier adr, ConstraintValidatorContext context) {
+ boolean r = true;
+ if ("error".equals(adr.getZipCode())) {
+ context.disableDefaultConstraintViolation();
+ context.buildConstraintViolationWithTemplate("zipcode not OK").addConstraintViolation();
+ r = false;
+ }
+ if ("error".equals(adr.getCity())) {
+ context.disableDefaultConstraintViolation();
+ context.buildConstraintViolationWithTemplate("city not OK").addPropertyNode("city")
+ .addConstraintViolation();
+ r = false;
+ }
+ return r;
+ }
+}
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/BeanDescriptorTest.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/BeanDescriptorTest.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/BeanDescriptorTest.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/BeanDescriptorTest.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,213 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bval.jsr;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import java.util.Set;
+
+import javax.validation.Constraint;
+import javax.validation.Payload;
+import javax.validation.constraints.NotNull;
+import javax.validation.groups.Default;
+import javax.validation.metadata.BeanDescriptor;
+import javax.validation.metadata.ConstraintDescriptor;
+import javax.validation.metadata.ElementDescriptor;
+import javax.validation.metadata.ElementDescriptor.ConstraintFinder;
+import javax.validation.metadata.PropertyDescriptor;
+import javax.validation.metadata.Scope;
+
+import org.apache.bval.jsr.util.TestUtils;
+import org.junit.Test;
+
+/**
+ * Tests the implementation of {@link BeanDescriptor} and its dependent
+ * interfaces.
+ *
+ * @author Carlos Vara
+ */
+public class BeanDescriptorTest extends ValidationTestBase {
+
+ /**
+ * Check that groups(), message() and payload() are always in the
+ * attributes.
+ */
+ @Test
+ public void testMandatoryAttributesPresentInConstraintDescriptor() {
+ Set<ConstraintDescriptor<?>> nameDescriptors =
+ validator.getConstraintsForClass(Form.class).getConstraintsForProperty("name").getConstraintDescriptors();
+ assertEquals("Incorrect number of descriptors", 1, nameDescriptors.size());
+ ConstraintDescriptor<?> nameDescriptor = nameDescriptors.iterator().next();
+ assertTrue("groups attribute not present", nameDescriptor.getAttributes().containsKey("groups"));
+ assertTrue("payload attribute not present", nameDescriptor.getAttributes().containsKey("payload"));
+ assertTrue("message attribute not present", nameDescriptor.getAttributes().containsKey("message"));
+ }
+
+ /**
+ * Check that the groups() attribute value has the correct value when
+ * inheriting groups.
+ */
+ @Test
+ public void testCorrectValueForInheritedGroupsAttribute() {
+ Set<ConstraintDescriptor<?>> passwordDescriptors = validator.getConstraintsForClass(Account.class)
+ .getConstraintsForProperty("password").getConstraintDescriptors();
+ assertEquals("Incorrect number of descriptors", 1, passwordDescriptors.size());
+ ConstraintDescriptor<?> passwordDescriptor = passwordDescriptors.iterator().next();
+ assertEquals("Incorrect number of composing constraints", 1,
+ passwordDescriptor.getComposingConstraints().size());
+ ConstraintDescriptor<?> notNullDescriptor = passwordDescriptor.getComposingConstraints().iterator().next();
+
+ // Check that the groups value containts Group1.class
+ Class<?>[] notNullGroups = (Class<?>[]) notNullDescriptor.getAttributes().get("groups");
+ boolean found = false;
+ for (Class<?> group : notNullGroups) {
+ if (group == Group1.class) {
+ found = true;
+ break;
+ }
+ }
+ assertTrue("Group1 not present in groups attribute", found);
+ }
+
+ /**
+ * Check that the groups() attribute value contains the correct interface as
+ * implicit group when the constraint is defined in that interface instead
+ * of the queried class.
+ */
+ @Test
+ public void testImplicitGroupIsPresent() {
+ Set<ConstraintDescriptor<?>> nameDescriptors =
+ validator.getConstraintsForClass(Woman.class).getConstraintsForProperty("name").getConstraintDescriptors();
+ assertEquals("Incorrect number of descriptors", 1, nameDescriptors.size());
+ ConstraintDescriptor<?> notNullDescriptor = nameDescriptors.iterator().next();
+
+ // Check that the groups attribute value contains the implicit group
+ // Person and the Default group
+ Class<?>[] notNullGroups = (Class<?>[]) notNullDescriptor.getAttributes().get("groups");
+ assertEquals("Incorrect number of groups", 2, notNullGroups.length);
+ assertTrue("Default group not present",
+ notNullGroups[0].equals(Default.class) || notNullGroups[1].equals(Default.class));
+ assertTrue("Implicit group not present",
+ notNullGroups[0].equals(Person.class) || notNullGroups[1].equals(Person.class));
+ }
+
+ /**
+ * Check that the groups() attribute value does not contain the implicit
+ * interface group when querying the interface directly.
+ */
+ @Test
+ public void testNoImplicitGroupWhenQueryingInterfaceDirectly() {
+ Set<ConstraintDescriptor<?>> nameDescriptors =
+ validator.getConstraintsForClass(Person.class).getConstraintsForProperty("name").getConstraintDescriptors();
+ assertEquals("Incorrect number of descriptors", 1, nameDescriptors.size());
+ ConstraintDescriptor<?> notNullDescriptor = nameDescriptors.iterator().next();
+
+ // Check that only the default group is present
+ Class<?>[] notNullGroups = (Class<?>[]) notNullDescriptor.getAttributes().get("groups");
+ assertEquals("Incorrect number of groups", 1, notNullGroups.length);
+ assertTrue("Default group not present", notNullGroups[0].equals(Default.class));
+ }
+
+ /**
+ * Check that the implementations of
+ * {@link ElementDescriptor#getElementClass()} work as defined in the spec.
+ */
+ @Test
+ public void testElementDescriptorGetElementClass() {
+ BeanDescriptor beanDescriptor = validator.getConstraintsForClass(Person.class);
+ assertEquals("Incorrect class returned", Person.class, beanDescriptor.getElementClass());
+
+ PropertyDescriptor nameDescriptor = beanDescriptor.getConstraintsForProperty("name");
+ assertEquals("Incorrect class returned", String.class, nameDescriptor.getElementClass());
+ }
+
+ /**
+ * Check the correct behavior of
+ * {@link ConstraintFinder#lookingAt(javax.validation.metadata.Scope)}.
+ */
+ @Test
+ public void testConstraintFinderLookingAt() {
+ PropertyDescriptor nameDescriptor =
+ validator.getConstraintsForClass(Woman.class).getConstraintsForProperty("name");
+ Set<ConstraintDescriptor<?>> constraints =
+ nameDescriptor.findConstraints().lookingAt(Scope.HIERARCHY).getConstraintDescriptors();
+ assertEquals("Incorrect number of descriptors", 1, constraints.size());
+
+ constraints = nameDescriptor.findConstraints().lookingAt(Scope.LOCAL_ELEMENT).getConstraintDescriptors();
+ assertEquals("Incorrect number of descriptors", 0, constraints.size());
+ TestUtils.failOnModifiable(constraints, "constraintFinder constraintDescriptors");
+ //verify that changes to one ConstraintFinder don't affect the base:
+ constraints = nameDescriptor.getConstraintDescriptors();
+ assertEquals("Incorrect number of descriptors", 1, constraints.size());
+ }
+
+ public static class Form {
+ @NotNull
+ public String name;
+ }
+
+ public static class Account {
+ @Password(groups = { Group1.class })
+ public String password;
+ }
+
+ @NotNull(groups = {})
+ @Constraint(validatedBy = {})
+ @Documented
+ @Target({ METHOD, FIELD, TYPE })
+ @Retention(RUNTIME)
+ public static @interface Password {
+ String message() default "Invalid password";
+
+ Class<?>[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ public static interface Group1 {
+ }
+
+ public static class Woman implements Person {
+
+ private String name;
+
+ @Override
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+ }
+
+ public static interface Person {
+ @NotNull
+ String getName();
+ }
+
+}
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/BootstrapTest.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/BootstrapTest.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/BootstrapTest.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/BootstrapTest.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,201 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bval.jsr;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+import javax.validation.Configuration;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.ConstraintViolation;
+import javax.validation.Validation;
+import javax.validation.ValidationException;
+import javax.validation.ValidationProviderResolver;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.bootstrap.ProviderSpecificBootstrap;
+import javax.validation.spi.ValidationProvider;
+
+import org.apache.bval.constraints.NotNullValidator;
+import org.apache.bval.jsr.example.Customer;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+/**
+ * Description: <br/>
+ */
+public class BootstrapTest {
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testDirectBootstrap() {
+ Validator validator = ApacheValidatorFactory.getDefault().getValidator();
+ assertNotNull(validator);
+ assertTrue(ApacheValidatorFactory.getDefault() == ApacheValidatorFactory.getDefault());
+ }
+
+ @Test
+ public void testEverydayBootstrap() {
+ ApacheValidatorFactory factory = (ApacheValidatorFactory) Validation.buildDefaultValidatorFactory();
+ Validator validator = factory.getValidator();
+ assertNotNull(validator);
+
+ // each call to Validation.getValidationBuilder() returns a new builder
+ // with new state
+ ApacheValidatorFactory factory2 = (ApacheValidatorFactory) Validation.buildDefaultValidatorFactory();
+ assertTrue(factory2 != factory);
+ assertTrue(factory2.getMessageInterpolator() != factory.getMessageInterpolator());
+
+ }
+
+ @Test
+ public void testLocalizedMessageInterpolatorFactory() {
+ Configuration<?> builder = Validation.byDefaultProvider().configure();
+ // changing the builder allows to create different factories
+ DefaultMessageInterpolator interpolator = new DefaultMessageInterpolator();
+ builder.messageInterpolator(interpolator);
+ ApacheValidatorFactory factory = (ApacheValidatorFactory) builder.buildValidatorFactory();
+
+ ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
+ // now factory's message resolver is using the english locale
+ }
+
+ /**
+ * some tests based on RI tested behaviors to ensure our implementation
+ * works as the reference implementation
+ */
+ @Test
+ public void testCustomConstraintFactory() {
+
+ Configuration<?> builder = Validation.byDefaultProvider().configure();
+ assertDefaultBuilderAndFactory(builder);
+
+ ValidatorFactory factory = builder.buildValidatorFactory();
+ Validator validator = factory.getValidator();
+
+ Customer customer = new Customer();
+ customer.setFirstName("John");
+
+ Set<ConstraintViolation<Customer>> ConstraintViolations = validator.validate(customer);
+ assertFalse(ConstraintViolations.isEmpty());
+
+ builder = Validation.byDefaultProvider().configure();
+ builder.constraintValidatorFactory(new ConstraintValidatorFactory() {
+ @Override
+ public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
+ if (key == NotNullValidator.class) {
+ @SuppressWarnings("unchecked")
+ final T result = (T) new BadlyBehavedNotNullValidator();
+ return result;
+ }
+ return new DefaultConstraintValidatorFactory().getInstance(key);
+ }
+
+ @Override
+ public void releaseInstance(ConstraintValidator<?, ?> instance) {
+ // no-op
+ }
+ });
+ factory = builder.buildValidatorFactory();
+ validator = factory.getValidator();
+ Set<ConstraintViolation<Customer>> ConstraintViolations2 = validator.validate(customer);
+ assertTrue("Wrong number of constraints", ConstraintViolations.size() > ConstraintViolations2.size());
+ }
+
+ @Test
+ public void testCustomResolverAndType() {
+ ValidationProviderResolver resolver = new ValidationProviderResolver() {
+
+ @Override
+ public List<ValidationProvider<?>> getValidationProviders() {
+ List<ValidationProvider<?>> list = new ArrayList<ValidationProvider<?>>(1);
+ list.add(new ApacheValidationProvider());
+ return list;
+ }
+ };
+
+ ApacheValidatorConfiguration builder =
+ Validation.byProvider(ApacheValidationProvider.class).providerResolver(resolver).configure();
+ assertDefaultBuilderAndFactory(builder);
+ }
+
+ @Test
+ public void testCustomResolver() {
+ ValidationProviderResolver resolver = new ValidationProviderResolver() {
+
+ @Override
+ public List<ValidationProvider<?>> getValidationProviders() {
+ return Collections.<ValidationProvider<?>> singletonList(new ApacheValidationProvider());
+ }
+ };
+
+ Configuration<?> builder = Validation.byDefaultProvider().providerResolver(resolver).configure();
+ assertDefaultBuilderAndFactory(builder);
+ }
+
+ private void assertDefaultBuilderAndFactory(Configuration<?> builder) {
+ assertNotNull(builder);
+ assertTrue(builder instanceof ConfigurationImpl);
+
+ ValidatorFactory factory = builder.buildValidatorFactory();
+ assertNotNull(factory);
+ assertTrue(factory instanceof ApacheValidatorFactory);
+ }
+
+ @Test
+ public void testFailingCustomResolver() {
+ ValidationProviderResolver resolver = new ValidationProviderResolver() {
+
+ @Override
+ public List<ValidationProvider<?>> getValidationProviders() {
+ return Collections.emptyList();
+ }
+ };
+
+ ProviderSpecificBootstrap<ApacheValidatorConfiguration> type =
+ Validation.byProvider(ApacheValidationProvider.class);
+
+ final ProviderSpecificBootstrap<ApacheValidatorConfiguration> specializedBuilderFactory =
+ type.providerResolver(resolver);
+
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("provider");
+ thrown.expectMessage(ApacheValidationProvider.class.getName());
+
+ specializedBuilderFactory.configure();
+ }
+
+ class BadlyBehavedNotNullValidator extends NotNullValidator {
+ @Override
+ public boolean isValid(Object object, ConstraintValidatorContext context) {
+ return true;
+ }
+ }
+}
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/CircularReferencesTest.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/CircularReferencesTest.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/CircularReferencesTest.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/CircularReferencesTest.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.bval.jsr;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Set;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.Valid;
+import javax.validation.constraints.Size;
+
+import org.junit.Test;
+
+/**
+ * Checks that circular references in the bean graph are correctly detected when
+ * validating.
+ *
+ * @author Carlos Vara
+ */
+public class CircularReferencesTest extends ValidationTestBase {
+
+ /**
+ * Checks that validation correctly stops when finding a circular
+ * dependency.
+ */
+ @Test
+ public void testAutoreferringBean() {
+ Person p1 = new Person();
+ p1.name = "too-long-name";
+ p1.sibling = p1;
+
+ Set<ConstraintViolation<Person>> violations = validator.validate(p1);
+
+ assertEquals("Only 1 violation should be reported", 1, violations.size());
+ ConstraintViolation<Person> violation = violations.iterator().next();
+ assertEquals("Incorrect violation path", "name", violation.getPropertyPath().toString());
+ }
+
+ /**
+ * Checks that a bean is always validated when appearing in non-circular
+ * paths inside the bean graph.
+ */
+ @Test
+ public void testNonCircularArrayOfSameBean() {
+ Boss boss = new Boss();
+ Person p1 = new Person();
+ p1.name = "too-long-name";
+
+ boss.employees = new Person[] { p1, p1, p1, p1 };
+
+ Set<ConstraintViolation<Boss>> violations = validator.validate(boss);
+
+ assertEquals("A total of 4 violations should be reported", 4, violations.size());
+ }
+
+ public static class Person {
+
+ @Valid
+ public Person sibling;
+
+ @Size(max = 10)
+ public String name;
+
+ }
+
+ public static class Boss {
+
+ @Valid
+ public Person[] employees;
+
+ }
+
+}
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ComposedConstraintsTest.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ComposedConstraintsTest.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ComposedConstraintsTest.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ComposedConstraintsTest.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bval.jsr;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Set;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.constraints.Size;
+import javax.validation.metadata.ConstraintDescriptor;
+import javax.validation.metadata.ElementDescriptor;
+
+import org.apache.bval.jsr.example.CompanyAddress;
+import org.apache.bval.jsr.example.FrenchAddress;
+import org.apache.bval.jsr.util.TestUtils;
+import org.junit.Test;
+
+/**
+ * Description: <br/>
+ */
+public class ComposedConstraintsTest extends ValidationTestBase {
+
+ @Test
+ public void testMetaDataAPI_ComposedConstraints() {
+ ElementDescriptor ed =
+ validator.getConstraintsForClass(FrenchAddress.class).getConstraintsForProperty("zipCode");
+ assertEquals(1, ed.getConstraintDescriptors().size());
+ for (ConstraintDescriptor<?> cd : ed.getConstraintDescriptors()) {
+ assertTrue(cd.isReportAsSingleViolation());
+ assertEquals(3, cd.getComposingConstraints().size());
+ assertTrue("no composing constraints found!!", !cd.getComposingConstraints().isEmpty());
+ processConstraintDescriptor(cd); // check all constraints on zip code
+ }
+ }
+
+ private void processConstraintDescriptor(ConstraintDescriptor<?> cd) {
+ //Size.class is understood by the tool
+ if (Size.class.equals(cd.getAnnotation().annotationType())) {
+ Size.class.cast(cd.getAnnotation());
+ }
+ for (ConstraintDescriptor<?> composingCd : cd.getComposingConstraints()) {
+ //check composing constraints recursively
+ processConstraintDescriptor(composingCd);
+ }
+ }
+
+ @Test
+ public void testValidateComposed() {
+ FrenchAddress adr = new FrenchAddress();
+
+ {
+ Set<ConstraintViolation<FrenchAddress>> findings = validator.validate(adr);
+ assertEquals(1, findings.size()); // with @ReportAsSingleConstraintViolation
+ ConstraintViolation<FrenchAddress> finding = findings.iterator().next();
+ assertEquals("Wrong zipcode", finding.getMessage());
+ }
+
+ adr.setZipCode("1234567");
+ assertTrue(validator.validate(adr).isEmpty());
+
+ adr.setZipCode("1234567234567");
+ assertEquals(1, validator.validate(adr).size());
+
+ adr.setZipCode2(null);
+ assertEquals(2, validator.validate(adr).size());
+ }
+
+ @Test
+ public void testOverridesAttributeConstraintIndex() {
+ Set<ConstraintViolation<CompanyAddress>> findings = validator.validate(new CompanyAddress("invalid-string"));
+ assertEquals(2, findings.size()); // without @ReportAsSingleConstraintViolation
+ assertNotNull(TestUtils.getViolationWithMessage(findings, "Not COMPANY"));
+ assertNotNull(TestUtils.getViolationWithMessage(findings, "Not an email"));
+
+ findings = validator.validate(new CompanyAddress("JOHN_DO@WEB.DE"));
+ assertEquals(1, findings.size());
+ assertNotNull(TestUtils.getViolationWithMessage(findings, "Not COMPANY"));
+
+ findings = validator.validate(new CompanyAddress("JOHN_DO@COMPANY.DE"));
+ assertTrue(findings.isEmpty());
+ }
+
+}
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintCompositionTest.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintCompositionTest.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintCompositionTest.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintCompositionTest.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,278 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.bval.jsr;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.lang.annotation.Annotation;
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import java.util.Set;
+
+import javax.validation.Constraint;
+import javax.validation.ConstraintViolation;
+import javax.validation.OverridesAttribute;
+import javax.validation.Payload;
+import javax.validation.ReportAsSingleViolation;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Pattern;
+import javax.validation.constraints.Size;
+import javax.validation.metadata.ConstraintDescriptor;
+
+import org.junit.Test;
+
+/**
+ * Checks that groups are correctly inherited from the root constraint to its
+ * compositing constraints.
+ *
+ * @author Carlos Vara
+ */
+public class ConstraintCompositionTest extends ValidationTestBase {
+
+ /**
+ * Check correct group inheritance on constraint composition on a 1 level
+ * hierarchy.
+ */
+ @Test
+ public void test1LevelInheritance() {
+ Set<ConstraintViolation<Person>> violations = validator.validate(new Person());
+
+ assertEquals("Wrong number of violations detected", 1, violations.size());
+ String msg = violations.iterator().next().getMessage();
+ assertEquals("Incorrect violation message", "A person needs a non null name", msg);
+
+ violations = validator.validate(new Person(), Group1.class);
+ assertEquals("Wrong number of violations detected", 0, violations.size());
+ }
+
+ /**
+ * Check correct group inheritance on constraint composition on a 2 level
+ * hierarchy.
+ */
+ @Test
+ public void test2LevelInheritance() {
+ Set<ConstraintViolation<Man>> violations = validator.validate(new Man());
+
+ assertEquals("Wrong number of violations detected", 0, violations.size());
+
+ violations = validator.validate(new Man(), Group1.class);
+ assertEquals("Wrong number of violations detected", 1, violations.size());
+ String msg = violations.iterator().next().getMessage();
+ assertEquals("Incorrect violation message", "A person needs a non null name", msg);
+ }
+
+ /**
+ * Checks that the groups() value of the constraint annotations are
+ * correctly set to the inherited ones.
+ */
+ @Test
+ public void testAnnotationGroupsAreInherited() {
+ // Check that the groups() value is right when querying the metadata
+ ConstraintDescriptor<?> manNameDesc = validator.getConstraintsForClass(Man.class)
+ .getConstraintsForProperty("name").getConstraintDescriptors().iterator().next();
+ ConstraintDescriptor<?> personNameDesc = manNameDesc.getComposingConstraints().iterator().next();
+ ConstraintDescriptor<?> notNullDesc = personNameDesc.getComposingConstraints().iterator().next();
+ assertEquals("There should only be 1 group", 1, manNameDesc.getGroups().size());
+ assertTrue("Group1 should be present", manNameDesc.getGroups().contains(Group1.class));
+ assertEquals("There should only be 1 group", 1, personNameDesc.getGroups().size());
+ assertTrue("Group1 should be present", personNameDesc.getGroups().contains(Group1.class));
+ assertEquals("There should only be 1 group", 1, personNameDesc.getGroups().size());
+ assertTrue("Group1 should be present", notNullDesc.getGroups().contains(Group1.class));
+
+ // Check that the groups() value is right when accessing it from an
+ // error
+ Set<ConstraintViolation<Man>> violations = validator.validate(new Man(), Group1.class);
+ Set<Class<?>> notNullGroups = violations.iterator().next().getConstraintDescriptor().getGroups();
+ assertEquals("There should only be 1 group", 1, notNullGroups.size());
+ assertTrue("Group1 should be the only group", notNullGroups.contains(Group1.class));
+ }
+
+ /**
+ * Checks that the payload() value of the constraint annotations are
+ * correctly set to the inherited ones.
+ */
+ @Test
+ public void testAnnotationPayloadsAreInherited() {
+ // Check that the payload() value is right when querying the metadata
+ ConstraintDescriptor<?> manNameDesc = validator.getConstraintsForClass(Man.class)
+ .getConstraintsForProperty("name").getConstraintDescriptors().iterator().next();
+ ConstraintDescriptor<?> personNameDesc = manNameDesc.getComposingConstraints().iterator().next();
+ ConstraintDescriptor<?> notNullDesc = personNameDesc.getComposingConstraints().iterator().next();
+ assertEquals("There should only be 1 payload class", 1, manNameDesc.getPayload().size());
+ assertTrue("Payload1 should be present", manNameDesc.getPayload().contains(Payload1.class));
+ assertEquals("There should only be 1 payload class", 1, personNameDesc.getPayload().size());
+ assertTrue("Payload1 should be present", personNameDesc.getPayload().contains(Payload1.class));
+ assertEquals("There should only be 1 payload class", 1, personNameDesc.getPayload().size());
+ assertTrue("Payload1 should be present", notNullDesc.getPayload().contains(Payload1.class));
+
+ // Check that the payload() value is right when accessing it from an
+ // error
+ Set<ConstraintViolation<Man>> violations = validator.validate(new Man(), Group1.class);
+ Set<Class<? extends Payload>> notNullPayload =
+ violations.iterator().next().getConstraintDescriptor().getPayload();
+ assertEquals("There should only be 1 payload class", 1, notNullPayload.size());
+ assertTrue("Payload1 should be the only payload", notNullPayload.contains(Payload1.class));
+ }
+
+ /**
+ * Checks that {@link OverridesAttribute#constraintIndex()} parsing and
+ * applying works.
+ */
+ @Test
+ public void testIndexedOverridesAttributes() {
+ Person p = new Person();
+ p.name = "valid";
+
+ // With a valid id, no errors expected
+ p.id = "1234";
+ Set<ConstraintViolation<Person>> constraintViolations = validator.validate(p);
+ assertTrue("No violations should be reported on valid id", constraintViolations.isEmpty());
+
+ // With a short id, only 1 error expected
+ p.id = "1";
+ constraintViolations = validator.validate(p);
+ assertEquals("Only 1 violation expected", 1, constraintViolations.size());
+ ConstraintViolation<Person> violation = constraintViolations.iterator().next();
+ assertEquals("Wrong violation", "Id is too short", violation.getMessage());
+
+ // With a long id, only 1 error expected
+ p.id = "loooooong id";
+ constraintViolations = validator.validate(p);
+ assertEquals("Only 1 violation expected", 1, constraintViolations.size());
+ violation = constraintViolations.iterator().next();
+ assertEquals("Wrong violation", "Id is too long", violation.getMessage());
+ }
+
+ /**
+ * Checks that errors are reported correctly when using
+ * {@link ReportAsSingleViolation}.
+ */
+ @Test
+ public void testReportAsAsingleViolation() {
+ Code c = new Code();
+ c.code = "very invalid code";
+ Set<ConstraintViolation<Code>> constraintViolations = validator.validate(c);
+
+ // Only 1 error expected
+ assertEquals("Only 1 violation expected", 1, constraintViolations.size());
+ ConstraintViolation<Code> violation = constraintViolations.iterator().next();
+ assertEquals("Wrong violation message", "Invalid code", violation.getMessage());
+ assertEquals("Wrong violation type", ElevenDigitsCode.class,
+ ((Annotation) violation.getConstraintDescriptor().getAnnotation()).annotationType());
+ }
+
+ public static class Person {
+ @PersonName
+ String name;
+
+ @PersonId
+ String id;
+ }
+
+ public static class Man {
+ @ManName(groups = { Group1.class }, payload = { Payload1.class })
+ String name;
+ }
+
+ public static class Code {
+ @ElevenDigitsCode
+ String code;
+ }
+
+ @NotNull(message = "A person needs a non null name", groups = { Group1.class }, payload = {})
+ @Constraint(validatedBy = {})
+ @Documented
+ @Target({ METHOD, FIELD, TYPE })
+ @Retention(RUNTIME)
+ public static @interface PersonName {
+ String message() default "Wrong person name";
+
+ Class<?>[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ @PersonName(groups = { Group2.class }, payload = { Payload1.class, Payload2.class })
+ @Constraint(validatedBy = {})
+ @Documented
+ @Target({ METHOD, FIELD, TYPE })
+ @Retention(RUNTIME)
+ public static @interface ManName {
+ String message() default "Wrong man name";
+
+ Class<?>[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ @Size.List({ @Size(min = 3, max = 3, message = "Id is too short"),
+ @Size(min = 5, max = 5, message = "Id is too long") })
+ @Constraint(validatedBy = {})
+ @Documented
+ @Target({ METHOD, FIELD, TYPE })
+ @Retention(RUNTIME)
+ public static @interface PersonId {
+ String message() default "Wrong person id";
+
+ Class<?>[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+
+ @OverridesAttribute(constraint = Size.class, constraintIndex = 0, name = "max")
+ int maxSize() default 1000;
+
+ @OverridesAttribute(constraint = Size.class, constraintIndex = 1, name = "min")
+ int minSize() default 0;
+ }
+
+ @Size(min = 11, max = 11)
+ @Pattern(regexp = "\\d*")
+ @Constraint(validatedBy = {})
+ @ReportAsSingleViolation
+ @Documented
+ @Target({ METHOD, FIELD, TYPE })
+ @Retention(RUNTIME)
+ public static @interface ElevenDigitsCode {
+ String message() default "Invalid code";
+
+ Class<?>[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ public static interface Group1 {
+ }
+
+ public static interface Group2 {
+ }
+
+ public static class Payload1 implements Payload {
+ }
+
+ public static class Payload2 implements Payload {
+ }
+
+}
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintDefinitionsTest.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintDefinitionsTest.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintDefinitionsTest.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintDefinitionsTest.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,261 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bval.jsr;
+
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import static org.junit.Assert.assertEquals;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import java.util.Set;
+
+import javax.validation.Constraint;
+import javax.validation.ConstraintDefinitionException;
+import javax.validation.Payload;
+import javax.validation.constraints.Min;
+import javax.validation.metadata.BeanDescriptor;
+import javax.validation.metadata.ConstraintDescriptor;
+
+import org.apache.bval.constraints.NotNullValidator;
+import org.junit.Test;
+
+/**
+ * Checks the correct parsing of constraint definitions.
+ *
+ * @author Carlos Vara
+ */
+public class ConstraintDefinitionsTest extends ValidationTestBase {
+
+ /**
+ * Checks the correct parsing of a constraint with an array of constraints
+ * as attributes.
+ */
+ @Test
+ public void testCustomAttributes() {
+ BeanDescriptor constraints = validator.getConstraintsForClass(Person.class);
+ Set<ConstraintDescriptor<?>> ageConstraints =
+ constraints.getConstraintsForProperty("age").getConstraintDescriptors();
+
+ assertEquals("There should be 2 constraints in 'age'", ageConstraints.size(), 2);
+ for (ConstraintDescriptor<?> cd : ageConstraints) {
+ assertEquals("Annotation should be @Min", cd.getAnnotation().annotationType().getName(),
+ Min.class.getName());
+ }
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with no <code>groups()</code> method.
+ */
+ @Test(expected = ConstraintDefinitionException.class)
+ public void testNoGroupsConstraint() {
+ validator.validate(new NoGroups());
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with an invalid <code>groups()</code>
+ * method.
+ */
+ @Test(expected = ConstraintDefinitionException.class)
+ public void testInvalidDefaultGroupsConstraint() {
+ validator.validate(new InvalidGroups());
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with no <code>payload()</code> method.
+ */
+ @Test(expected = ConstraintDefinitionException.class)
+ public void testNoPayloadConstraint() {
+ validator.validate(new NoPayload());
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with an invalid <code>payload()</code>
+ * method.
+ */
+ @Test(expected = ConstraintDefinitionException.class)
+ public void testInvalidDefaultPayloadConstraint() {
+ validator.validate(new InvalidPayload());
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with no <code>message()</code> method.
+ */
+ @Test(expected = ConstraintDefinitionException.class)
+ public void testNoMessageConstraint() {
+ validator.validate(new NoMessage());
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with an invalid <code>message()</code>
+ * method.
+ */
+ @Test(expected = ConstraintDefinitionException.class)
+ public void testInvalidDefaultMessageConstraint() {
+ validator.validate(new InvalidMessage());
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with a method starting with 'valid'.
+ */
+ @Test(expected = ConstraintDefinitionException.class)
+ public void testInvalidAttributeConstraint() {
+ validator.validate(new InvalidAttribute());
+ }
+
+ public static class Person {
+ @MinList({ @Min(value = 20), @Min(value = 30) })
+ public Integer age;
+ }
+
+ @Target({ METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ public static @interface MinList {
+ Min[] value();
+ }
+
+ public static class NoGroups {
+ @NoGroupsConstraint
+ public String prop;
+ }
+
+ @Target({ METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface NoGroupsConstraint {
+ String message() default "def msg";
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ public static class InvalidGroups {
+ @InvalidGroupsConstraint
+ public String prop;
+ }
+
+ @Target({ METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface InvalidGroupsConstraint {
+ String message() default "def msg";
+
+ String[] groups() default { "Group1" };
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ public static class NoPayload {
+ @NoPayloadConstraint
+ public String prop;
+ }
+
+ @Target({ METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface NoPayloadConstraint {
+ String message() default "def msg";
+
+ String[] groups() default {};
+ }
+
+ public static class InvalidPayload {
+ @InvalidPayloadConstraint
+ public String prop;
+ }
+
+ @Target({ METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface InvalidPayloadConstraint {
+ String message() default "def msg";
+
+ String[] groups() default {};
+
+ Class<? extends Payload>[] payload() default { Payload1.class };
+
+ public static class Payload1 implements Payload {
+ }
+ }
+
+ public static class NoMessage {
+ @NoMessageConstraint
+ public String prop;
+ }
+
+ @Target({ METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface NoMessageConstraint {
+ String[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ public static class InvalidMessage {
+ @InvalidMessageConstraint(message = 2)
+ public String prop;
+ }
+
+ @Target({ METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface InvalidMessageConstraint {
+ int message();
+
+ String[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ public static class InvalidAttribute {
+ @InvalidAttributeConstraint
+ public String prop;
+ }
+
+ @Target({ METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface InvalidAttributeConstraint {
+ String message() default "def msg";
+
+ String[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+
+ String validValue() default "1";
+ }
+}
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ContextConstraintValidatorFactoryTest.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ContextConstraintValidatorFactoryTest.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ContextConstraintValidatorFactoryTest.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ContextConstraintValidatorFactoryTest.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bval.jsr;
+
+import static org.junit.Assert.assertTrue;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.util.Set;
+
+import javax.validation.Constraint;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.ConstraintViolation;
+import javax.validation.Payload;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+
+import org.junit.Test;
+
+/**
+ * <a href="https://issues.apache.org/jira/browse/BVAL-111">https://issues.apache.org/jira/browse/BVAL-111</a>
+ * was a serious regression that resulted in BVal's bypassing the context-specific {@link ConstraintValidatorFactory},
+ * rather using the instance available from the {@link ValidatorFactory}. Thus any solutions to e.g. inject
+ * collaborators into {@link ConstraintValidator} implementations would fail.
+ */
+public class ContextConstraintValidatorFactoryTest extends ValidationTestBase {
+
+ @Documented
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD })
+ @Constraint(validatedBy = { Contrived.Validator.class })
+ public @interface Contrived {
+ String message() default "{org.apache.bval.constraints.Contrived.message}";
+
+ Class<?>[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+
+ public static class Validator implements ConstraintValidator<Contrived, Object> {
+ private Object requiredCollaborator;
+
+ public Object getRequiredCollaborator() {
+ return requiredCollaborator;
+ }
+
+ public void setRequiredCollaborator(Object requiredCollaborator) {
+ this.requiredCollaborator = requiredCollaborator;
+ }
+
+ @Override
+ public void initialize(Contrived constraintAnnotation) {
+ }
+
+ @Override
+ public boolean isValid(Object value, ConstraintValidatorContext context) {
+ getRequiredCollaborator().toString();
+ return true;
+ }
+
+ }
+
+ }
+
+ @Contrived
+ public static class Example {
+ }
+
+ @Override
+ protected Validator createValidator() {
+ final ConstraintValidatorFactory constraintValidatorFactory = new ConstraintValidatorFactory() {
+
+ @Override
+ public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
+ if (key.equals(Contrived.Validator.class)) {
+ final Contrived.Validator result = new Contrived.Validator();
+ result.setRequiredCollaborator(new Object());
+ @SuppressWarnings("unchecked")
+ final T t = (T) result;
+ return t;
+ }
+ return null;
+ }
+
+ @Override
+ public void releaseInstance(ConstraintValidator<?, ?> instance) {
+ // no-op
+ }
+ };
+ return factory.usingContext().constraintValidatorFactory(constraintValidatorFactory).getValidator();
+ }
+
+ @Test
+ public void testContextBoundConstraintValidatorFactory() {
+ final Set<ConstraintViolation<Example>> violations = validator.validate(new Example());
+ assertTrue(violations.isEmpty());
+ }
+}
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/CustomConstraintValidatorFactoryTest.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/CustomConstraintValidatorFactoryTest.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/CustomConstraintValidatorFactoryTest.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/CustomConstraintValidatorFactoryTest.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bval.jsr;
+
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import javax.validation.Constraint;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.Payload;
+import javax.validation.Validation;
+import javax.validation.ValidationException;
+import javax.validation.Validator;
+
+import org.apache.bval.jsr.CustomConstraintValidatorFactoryTest.GoodPerson.GoodPersonValidator;
+import org.junit.Test;
+
+/**
+ * Checks that overriding the default {@link ConstraintValidatorFactory} works
+ * as expected.
+ *
+ * @author Carlos Vara
+ */
+public class CustomConstraintValidatorFactoryTest {
+
+ /**
+ * If the custom ConstraintValidatorFactory returns <code>null</code> for a
+ * valid {@link ConstraintValidatorFactory#getInstance(Class)} call, a
+ * validation exception should be thrown.
+ */
+ @Test(expected = ValidationException.class)
+ public void testValidationExceptionWhenFactoryReturnsNullValidator() {
+
+ ConstraintValidatorFactory customFactory = new ConstraintValidatorFactory() {
+ @Override
+ public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
+ return null; // always return null
+ }
+
+ @Override
+ public void releaseInstance(ConstraintValidator<?, ?> instance) {
+ // no-op
+ }
+ };
+
+ // Create a validator with this factory
+ ApacheValidatorConfiguration customConfig =
+ Validation.byProvider(ApacheValidationProvider.class).configure().constraintValidatorFactory(customFactory);
+ Validator validator = customConfig.buildValidatorFactory().getValidator();
+
+ validator.validate(new Person());
+ }
+
+ @GoodPerson
+ public static class Person {
+ }
+
+ @Constraint(validatedBy = { GoodPersonValidator.class })
+ @Target({ METHOD, FIELD, ANNOTATION_TYPE, TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ public static @interface GoodPerson {
+
+ String message() default "Not a good person";
+
+ Class<?>[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+
+ public static class GoodPersonValidator implements ConstraintValidator<GoodPerson, Person> {
+ @Override
+ public void initialize(GoodPerson constraintAnnotation) {
+ }
+
+ @Override
+ public boolean isValid(Person value, ConstraintValidatorContext context) {
+ return true;
+ }
+ }
+ }
+
+}
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/CustomValidatorFactoryTest.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/CustomValidatorFactoryTest.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/CustomValidatorFactoryTest.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/CustomValidatorFactoryTest.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,156 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bval.jsr;
+
+import static org.hamcrest.CoreMatchers.isA;
+
+import javax.validation.ClockProvider;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.MessageInterpolator;
+import javax.validation.ParameterNameProvider;
+import javax.validation.TraversableResolver;
+import javax.validation.Validation;
+import javax.validation.ValidationException;
+import javax.validation.Validator;
+import javax.validation.ValidatorContext;
+import javax.validation.ValidatorFactory;
+import javax.validation.spi.ConfigurationState;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+/**
+ * Test the ability to force a particular {@link ValidatorFactory}
+ * implementation class.
+ */
+public class CustomValidatorFactoryTest {
+
+ public static class CustomValidatorFactory extends ApacheValidatorFactory {
+
+ /**
+ * Create a new CustomValidatorFactory instance.
+ *
+ * @param configurationState
+ */
+ public CustomValidatorFactory(ConfigurationState configurationState) {
+ super(configurationState);
+ }
+ }
+
+ public static class IncompatibleValidatorFactory implements ValidatorFactory {
+
+ @Override
+ public ConstraintValidatorFactory getConstraintValidatorFactory() {
+ return null;
+ }
+
+ @Override
+ public ParameterNameProvider getParameterNameProvider() {
+ return null;
+ }
+
+ @Override
+ public MessageInterpolator getMessageInterpolator() {
+ return null;
+ }
+
+ @Override
+ public TraversableResolver getTraversableResolver() {
+ return null;
+ }
+
+ @Override
+ public Validator getValidator() {
+ return null;
+ }
+
+ @Override
+ public <T> T unwrap(Class<T> type) {
+ return null;
+ }
+
+ @Override
+ public void close() {
+
+ }
+
+ @Override
+ public ValidatorContext usingContext() {
+ return null;
+ }
+
+ @Override
+ public ClockProvider getClockProvider() {
+ return null;
+ }
+
+ }
+
+ public static class NotAValidatorFactory {
+ public NotAValidatorFactory(ConfigurationState configurationState) {
+ }
+ }
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testDefaultValidatorFactory() {
+ Validation.byProvider(ApacheValidationProvider.class).configure().buildValidatorFactory()
+ .unwrap(ApacheValidatorFactory.class);
+ }
+
+ @Test
+ public void testNoSuchType() {
+ thrown.expect(ValidationException.class);
+ thrown.expectCause(isA(ClassNotFoundException.class));
+
+ Validation.byProvider(ApacheValidationProvider.class).configure()
+ .addProperty(ApacheValidatorConfiguration.Properties.VALIDATOR_FACTORY_CLASSNAME, "no.such.type")
+ .buildValidatorFactory();
+ }
+
+ @Test
+ public void testCustomValidatorFactory() {
+ doTest(CustomValidatorFactory.class, null);
+ }
+
+ @Test
+ public void testInvalidType() {
+ doTest(NotAValidatorFactory.class, ClassCastException.class);
+ doTest(NotAValidatorFactory.class, ClassCastException.class);
+ }
+
+ @Test
+ public void testUnsupportedValidatorFactoryType() {
+ doTest(IncompatibleValidatorFactory.class, NoSuchMethodException.class);
+ }
+
+ private void doTest(Class<?> validatorFactoryType, Class<? extends Exception> expectedFailureCause) {
+ if (expectedFailureCause != null) {
+ thrown.expect(ValidationException.class);
+ thrown.expectCause(isA(expectedFailureCause));
+ }
+ Validation.byProvider(ApacheValidationProvider.class).configure()
+ .addProperty(ApacheValidatorConfiguration.Properties.VALIDATOR_FACTORY_CLASSNAME,
+ validatorFactoryType.getName())
+ .buildValidatorFactory().unwrap(validatorFactoryType);
+ }
+}
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/DefaultMessageInterpolatorTest.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/DefaultMessageInterpolatorTest.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/DefaultMessageInterpolatorTest.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/DefaultMessageInterpolatorTest.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.bval.jsr;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+
+import java.util.Locale;
+
+import javax.validation.MessageInterpolator;
+import javax.validation.Validator;
+import javax.validation.constraints.Pattern;
+import javax.validation.metadata.ConstraintDescriptor;
+
+import org.apache.bval.jsr.example.Author;
+import org.apache.bval.jsr.example.PreferredGuest;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * MessageResolverImpl Tester.
+ */
+public class DefaultMessageInterpolatorTest {
+
+ private DefaultMessageInterpolator interpolator;
+
+ @Before
+ public void setUp() throws Exception {
+ interpolator = new DefaultMessageInterpolator();
+ interpolator.setLocale(Locale.ENGLISH);
+ }
+
+ @Test
+ public void testCreateResolver() {
+
+ final Validator gvalidator = getValidator();
+
+ assertFalse(gvalidator.getConstraintsForClass(PreferredGuest.class)
+ .getConstraintsForProperty("guestCreditCardNumber").getConstraintDescriptors().isEmpty());
+
+ MessageInterpolator.Context ctx = new MessageInterpolator.Context() {
+
+ @Override
+ public ConstraintDescriptor<?> getConstraintDescriptor() {
+ return gvalidator.getConstraintsForClass(PreferredGuest.class)
+ .getConstraintsForProperty("guestCreditCardNumber").getConstraintDescriptors().iterator().next();
+ }
+
+ @Override
+ public Object getValidatedValue() {
+ return "12345678";
+ }
+
+ @Override
+ public <T> T unwrap(Class<T> type) {
+ return null;
+ }
+ };
+ String msg = interpolator.interpolate("{validator.creditcard}", ctx);
+ assertEquals("credit card is not valid", msg);
+
+ ctx = new MessageInterpolator.Context() {
+ @Override
+ public ConstraintDescriptor<?> getConstraintDescriptor() {
+ return gvalidator.getConstraintsForClass(Author.class).getConstraintsForProperty("lastName")
+ .getConstraintDescriptors().iterator().next();
+ }
+
+ @Override
+ public Object getValidatedValue() {
+ return "";
+ }
+
+ @Override
+ public <T> T unwrap(Class<T> type) {
+ return null;
+ }
+ };
+
+ msg = interpolator.interpolate("{org.apache.bval.constraints.NotEmpty.message}", ctx);
+ assertEquals("may not be empty", msg);
+ }
+
+ /**
+ * Checks that strings containing special characters are correctly
+ * substituted when interpolating.
+ */
+ @Test
+ public void testReplacementWithSpecialChars() {
+
+ final Validator validator = getValidator();
+ MessageInterpolator.Context ctx;
+
+ // Try to interpolate an annotation attribute containing $
+ ctx = new MessageInterpolator.Context() {
+
+ @Override
+ public ConstraintDescriptor<?> getConstraintDescriptor() {
+ return validator.getConstraintsForClass(Person.class).getConstraintsForProperty("idNumber")
+ .getConstraintDescriptors().iterator().next();
+ }
+
+ @Override
+ public Object getValidatedValue() {
+ return "12345678";
+ }
+
+ @Override
+ public <T> T unwrap(Class<T> type) {
+ return null;
+ }
+ };
+
+ String result = this.interpolator.interpolate("Id number should match {regexp}", ctx);
+ assertEquals("Incorrect message interpolation when $ is in an attribute", "Id number should match ....$",
+ result);
+
+ // Try to interpolate an annotation attribute containing \
+ ctx = new MessageInterpolator.Context() {
+
+ @Override
+ public ConstraintDescriptor<?> getConstraintDescriptor() {
+ return validator.getConstraintsForClass(Person.class).getConstraintsForProperty("otherId")
+ .getConstraintDescriptors().iterator().next();
+ }
+
+ @Override
+ public Object getValidatedValue() {
+ return "12345678";
+ }
+
+ @Override
+ public <T> T unwrap(Class<T> type) {
+ return null;
+ }
+ };
+
+ result = this.interpolator.interpolate("Other id should match {regexp}", ctx);
+ assertEquals("Incorrect message interpolation when \\ is in an attribute value", "Other id should match .\\n",
+ result);
+ }
+
+ public static class Person {
+
+ @Pattern(message = "Id number should match {regexp}", regexp = "....$")
+ public String idNumber;
+
+ @Pattern(message = "Other id should match {regexp}", regexp = ".\\n")
+ public String otherId;
+
+ }
+
+ private Validator getValidator() {
+ return ApacheValidatorFactory.getDefault().getValidator();
+ }
+}
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ExceptionsContractTest.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ExceptionsContractTest.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ExceptionsContractTest.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/ExceptionsContractTest.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bval.jsr;
+
+import javax.validation.ValidationException;
+import javax.validation.Validator;
+import javax.validation.constraints.Min;
+import javax.validation.constraints.NotNull;
+import javax.validation.metadata.BeanDescriptor;
+
+import org.junit.Test;
+
+/**
+ * Several checks to validate that the implementations of {@link Validator} and
+ * {@link BeanDescriptor} throw the correct exceptions as per the spec.
+ *
+ * @author Carlos Vara
+ */
+public class ExceptionsContractTest extends ValidationTestBase {
+
+ /**
+ * Checks that the correct exception is thrown when validating a bean whose
+ * getter throws an exception.
+ */
+ @Test(expected = ValidationException.class)
+ public void testExceptionThrowingBean() {
+ validator.validate(new ExceptionThrowingBean());
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when passing
+ * <code>null</code> as group array.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateNullGroup() {
+ validator.validate(new String(), (Class<?>[]) null);
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when passing a
+ * {@code null} property name.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateNullPropertyName() {
+ validator.validateProperty(new Person(), null);
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when passing an
+ * empty property name.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateEmptyPropertyName() {
+ validator.validateProperty(new Person(), "");
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when passing an
+ * invalid property name.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateInvalidPropertyName() {
+ validator.validateProperty(new Person(), "surname");
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when trying to
+ * validate a property on a null object.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidatePropertyOnNullBean() {
+ validator.validateProperty(null, "class");
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when passing
+ * <code>null</code> as group array in a
+ * {@link Validator#validateProperty(Object, String, Class...)} call.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidatePropertyNullGroup() {
+ validator.validateProperty(new Person(), "name", (Class<?>[]) null);
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when calling
+ * {@link Validator#validateValue(Class, String, Object, Class...)} with a
+ * <code>null</code> class.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateValueOnNullClass() {
+ validator.validateValue(null, "class", Object.class);
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when passing a
+ * {@code null} property name to
+ * {@link Validator#validateValue(Class, String, Object, Class...)}.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateValueNullPropertyName() {
+ validator.validateValue(Person.class, null, "John");
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when passing an
+ * empty property name to
+ * {@link Validator#validateValue(Class, String, Object, Class...)}.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateValueEmptyPropertyName() {
+ validator.validateValue(Person.class, "", "John");
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when passing an
+ * invalid property name to
+ * {@link Validator#validateValue(Class, String, Object, Class...)}.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateValueInvalidPropertyName() {
+ validator.validateValue(Person.class, "unexistant", "John");
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when calling
+ * {@link Validator#validateValue(Class, String, Object, Class...)} with a
+ * <code>null</code> group array.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateValueNullGroup() {
+ validator.validateValue(Person.class, "name", "John", (Class<?>[]) null);
+ }
+
+ /**
+ * Enforces the "not a valid object property" part of the {@link IllegalArgumentException}
+ * declaration on {@link Validator#validateValue(Class, String, Object, Class...)}
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateIncompatibleValue() {
+ validator.validateValue(Person.class, "name", 666);
+ }
+
+ /**
+ * Enforces the "not a valid object property" part of the {@link IllegalArgumentException}
+ * declaration on {@link Validator#validateValue(Class, String, Object, Class...)}
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateIncompatiblePrimitiveValue() {
+ validator.validateValue(Person.class, "age", null);
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when calling
+ * {@link BeanDescriptor#getConstraintsForProperty(String)} with an invalid
+ * property name.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testGetConstraintsForNullProperty() {
+ BeanDescriptor personDescriptor = validator.getConstraintsForClass(Person.class);
+ personDescriptor.getConstraintsForProperty(null);
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when calling
+ * {@link BeanDescriptor#getConstraintsForProperty(String)} with an invalid
+ * property name.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testGetConstraintsForEmptyProperty() {
+ BeanDescriptor personDescriptor = validator.getConstraintsForClass(Person.class);
+ personDescriptor.getConstraintsForProperty("");
+ }
+
+ public static class ExceptionThrowingBean {
+
+ @NotNull
+ public String getValue() {
+ throw new IllegalStateException();
+ }
+
+ }
+
+ public static class Person {
+
+ @NotNull
+ public String name;
+
+ @Min(0)
+ public int age;
+ }
+
+}
Added: tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/FooTest.java
URL: http://svn.apache.org/viewvc/tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/FooTest.java?rev=1843674&view=auto
==============================================================================
--- tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/FooTest.java (added)
+++ tomee/deps/branches/bval-2/bval-jsr/src/test/java/org/apache/bval/jsr/FooTest.java Fri Oct 12 15:00:48 2018
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bval.jsr;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Set;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.Valid;
+import javax.validation.constraints.NotNull;
+
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Description: <br/>
+ */
+public class FooTest extends ValidationTestBase {
+
+ @Valid
+ private Collection<Foo> foos = new ArrayList<Foo>();
+
+ @Before
+ public void setup() {
+ foos.add(new Foo("foo1"));
+ foos.add(null);
+ foos.add(new Foo("foo3"));
+ }
+
+ public static class Foo {
+ @NotNull
+ public String bar;
+
+ public Foo(String bar) {
+ this.bar = bar;
+ }
+ }
+
+ @Test
+ public void testValidation() {
+ FooTest t = new FooTest();
+
+ Set<ConstraintViolation<FooTest>> errors = validator.validate(t);
+ System.out.println("got errors:");
+ for (ConstraintViolation<?> error : errors) {
+ System.out.println(error.getPropertyPath());
+ }
+ }
+}
\ No newline at end of file