From 5dee8a390724ceaff0d86d0e02c94a5a54384576 Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Wed, 26 Feb 2014 04:46:38 +0530 Subject: [PATCH 01/15] Added comments(description) for all built-in constraints used for Member bean validation.Also,added dateOfBirth,eventDate,minQuantity and maxQuantity as additional fields to implement several other constraints using @Past,@Future,@Min,@Max as annotations. Signed-off-by: girirajSharma --- .../bean_validation/model/Member.java | 84 ++++++++++++++++++- 1 file changed, 82 insertions(+), 2 deletions(-) diff --git a/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java b/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java index 513dd7c682..cbbb270f0e 100644 --- a/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java +++ b/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java @@ -32,32 +32,80 @@ import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; +//@Entity declares the class as an entity (i.e. a persistent POJO class) @Entity -@Table(name="MEMBER_BEAN_VALIDATION", uniqueConstraints = @UniqueConstraint(columnNames = "email")) +/* + * @Table annotation specifies the primary table for the annotated entity. Additional tables may be specified using + * SecondaryTable or SecondaryTables annotation. + * + * @UniqueConstraint Specifies that a unique constraint is to be included in the generated DDL for a primary or secondary table. + */ +@Table(name = "MEMBER_BEAN_VALIDATION", uniqueConstraints = @UniqueConstraint(columnNames = "email")) public class Member implements Serializable { /** Default value included to remove warning. Remove or modify at will. **/ private static final long serialVersionUID = 1L; + // @Id declares the identifier property of the entity. @Id + /* + * @GeneratedValue Provides for the specification of generation strategies for the values of primary keys. The + * GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in + * conjunction with the Id annotation. + */ @GeneratedValue private Long id; + // The value of the field or property must not be null. @NotNull + /* + * The size of the field or property is evaluated and must match the specified boundaries.If the field or property is a + * String, the size of the string is evaluated.If the field or property is a Collection, the size of the Collection is + * evaluated.If the field or property is a Map, the size of the Map is evaluated.If the field or property is an array, the + * size of the array is evaluated.Use one of the optional max or min elements to specify the boundaries. + */ @Size(min = 1, max = 25) - @Pattern(regexp = "[A-Za-z ]*", message = "must contain only letters and spaces") + /* The value of the field or property must match the regular expression defined in the regexp element. */ + @Pattern(regexp = "[A-Za-z ]*", message = "Must contain only letters and spaces") private String name; @NotNull + // Asserts that the annotated string, collection, map or array is not null or empty. @NotEmpty @Email private String email; @NotNull @Size(min = 10, max = 12) + /* + * The value of the field or property must be a number within a specified range. The integer element specifies the maximum + * integral digits for the number, and the fraction element specifies the maximum fractional digits for the number. + */ @Digits(fraction = 0, integer = 12) @Column(name = "phone_number") private String phoneNumber; + @NotNull + @NotEmpty + // The value of the field or property must be a date in the past. + @Past + private Date dateOfBirth; + + @NotNull + @NotEmpty + // The value of the field or property must be a date in the future. + @Future + private Date eventDate; + + @NotNull + // The value of the field or property must be an integer value lower than or equal to the number in the value element. + @Max(10) + private int maxQuantity; + + @NotNull + // The value of the field or property must be an integer value greater than or equal to the number in the value element. + @Min(10) + private Date minQuantity; + public Long getId() { return id; } @@ -89,4 +137,36 @@ public String getPhoneNumber() { public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } + + public Date getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(Date dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + public Date getEventDate() { + return eventDate; + } + + public void setEventDate(Date eventDate) { + this.eventDate = eventDate; + } + + public int getMaxQuantity() { + return maxQuantity; + } + + public void setMaxQuantity(int maxQuantity) { + this.maxQuantity = maxQuantity; + } + + public int getMinQuantity() { + return minQuantity; + } + + public void setMinQuantity(int minQuantity) { + this.minQuantity = minQuantity; + } } From a932f63e84c22777db6f3ad3b0c8add0477d0bff Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Wed, 26 Feb 2014 13:53:32 +0530 Subject: [PATCH 02/15] Added comments(description) for bean validation annotations.Also, added dateOfBirth,eventDate,minQuantity,maxQuantity as new fields with @Past,@Future,@Min,@Max as respective annotations. Signed-off-by: girirajSharma --- .../as/quickstarts/bean_validation/model/Member.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java b/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java index cbbb270f0e..59f49fdd41 100644 --- a/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java +++ b/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java @@ -17,6 +17,7 @@ package org.jboss.as.quickstarts.bean_validation.model; import java.io.Serializable; +import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; @@ -32,7 +33,7 @@ import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; -//@Entity declares the class as an entity (i.e. a persistent POJO class) +/*@Entity declares the class as an entity (i.e. a persistent POJO class) */ @Entity /* * @Table annotation specifies the primary table for the annotated entity. Additional tables may be specified using @@ -45,7 +46,7 @@ public class Member implements Serializable { /** Default value included to remove warning. Remove or modify at will. **/ private static final long serialVersionUID = 1L; - // @Id declares the identifier property of the entity. + /* @Id declares the identifier property of the entity.*/ @Id /* * @GeneratedValue Provides for the specification of generation strategies for the values of primary keys. The @@ -55,7 +56,7 @@ public class Member implements Serializable { @GeneratedValue private Long id; - // The value of the field or property must not be null. + /* The value of the field or property must not be null. */ @NotNull /* * The size of the field or property is evaluated and must match the specified boundaries.If the field or property is a @@ -69,7 +70,7 @@ public class Member implements Serializable { private String name; @NotNull - // Asserts that the annotated string, collection, map or array is not null or empty. + /* Asserts that the annotated string, collection, map or array is not null or empty. */ @NotEmpty @Email private String email; @@ -104,7 +105,7 @@ public class Member implements Serializable { @NotNull // The value of the field or property must be an integer value greater than or equal to the number in the value element. @Min(10) - private Date minQuantity; + private int minQuantity; public Long getId() { return id; From 341d79c4a5912c16b7d794ada1c392ee99a4d629 Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Wed, 26 Feb 2014 14:01:03 +0530 Subject: [PATCH 03/15] Added two new tests for bean validation namely testDateOfBirthViolation and testMinQuantityViolation to test for constraints on dateOfBirth and minQuantity fields of Member.Also,createValidMember method was modified to initialize new fields of Member class object(member) with valid values. Signed-off-by: girirajSharma --- .../test/MemberValidationTest.java | 68 ++++++++++++++++--- 1 file changed, 57 insertions(+), 11 deletions(-) diff --git a/bean-validation/src/test/java/org/jboss/as/quickstarts/bean_validation/test/MemberValidationTest.java b/bean-validation/src/test/java/org/jboss/as/quickstarts/bean_validation/test/MemberValidationTest.java index 9270b1389b..d5f9d26fe2 100644 --- a/bean-validation/src/test/java/org/jboss/as/quickstarts/bean_validation/test/MemberValidationTest.java +++ b/bean-validation/src/test/java/org/jboss/as/quickstarts/bean_validation/test/MemberValidationTest.java @@ -16,6 +16,7 @@ */ package org.jboss.as.quickstarts.bean_validation.test; +import java.util.Calendar; import java.util.Set; import javax.inject.Inject; @@ -55,14 +56,14 @@ public class MemberValidationTest { @Deployment public static Archive createTestArchive() { return ShrinkWrap.create(WebArchive.class, "test.war").addClasses(Member.class) - // enable JPA - .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml") - // add sample data - .addAsResource("import.sql") - // enable CDI - .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") - // Deploy our test datasource - .addAsWebInfResource("test-ds.xml", "test-ds.xml"); + // enable JPA + .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml") + // add sample data + .addAsResource("import.sql") + // enable CDI + .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") + // Deploy our test datasource + .addAsWebInfResource("test-ds.xml", "test-ds.xml"); } // Get configured validator directly from JBoss EAP 6 environment @@ -74,9 +75,11 @@ public static Archive createTestArchive() { * *
    *
  • @NotNull
  • - *
  • @NotNull
  • + *
  • @Pattern
  • *
  • @Email
  • *
  • @Size
  • + *
  • @Past
  • + *
  • @Min
  • *
*/ @Test @@ -109,7 +112,7 @@ public void testNameViolation() { Assert.assertEquals("One violation was found", 1, violations.size()); Assert.assertEquals("Name was invalid", "must contain only letters and spaces", violations.iterator().next() - .getMessage()); + .getMessage()); } /** @@ -136,7 +139,39 @@ public void testPhoneViolation() { Assert.assertEquals("One violation was found", 1, violations.size()); Assert.assertEquals("Phone number was invalid", "size must be between 10 and 12", violations.iterator().next() - .getMessage()); + .getMessage()); + } + + /** + * Tests {@code @Past} constraint + */ + @Test + public void testDateOfBirthViolation() { + Member member = createValidMember(); + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.DATE, 7); + member.setDateOfBirth(cal.getTime()); + + Set> violations = validator.validate(member); + + Assert.assertEquals("One violation was found", 1, violations.size()); + Assert.assertEquals("DateOfBirth was invalid", "DateOfBirth must be a Past date", violations.iterator().next() + .getMessage()); + } + + /** + * Tests {@code @Min} constraint + */ + @Test + public void testMinQuantityViolation() { + Member member = createValidMember(); + member.setMinQuantity(5); + + Set> violations = validator.validate(member); + + Assert.assertEquals("One violation was found", 1, violations.size()); + Assert.assertEquals("MinQuantity was invalid", "must be an integer value greater than or equal to 10", violations.iterator().next() + .getMessage()); } private Member createValidMember() { @@ -144,6 +179,17 @@ private Member createValidMember() { member.setEmail("jdoe@test.org"); member.setName("John Doe"); member.setPhoneNumber("1234567890"); + + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.DATE, -7); + member.setDateOfBirth(cal.getTime()); + + cal = Calendar.getInstance(); + cal.add(Calendar.DATE, 7); + member.setEventDate(cal.getTime()); + + member.setMaxQuantity(5); + member.setMinQuantity(15); return member; } From b1f898a7dcd35f9f5e6ef5c113568ccc4d6231d2 Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Thu, 27 Feb 2014 02:16:36 +0530 Subject: [PATCH 04/15] Changed ${version.jboss.bom.eap} from 6.2.0-build-7 to 6.2.1.GA as it is the latest version available from the jboss-ga-repository(http://maven.repository.redhat.com/techpreview/all). --- bean-validation/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bean-validation/pom.xml b/bean-validation/pom.xml index ef3c46132e..e491609751 100644 --- a/bean-validation/pom.xml +++ b/bean-validation/pom.xml @@ -45,7 +45,7 @@ 7.4.Final - 6.2.0-build-7 + 6.2.1.GA 2.10 From 9d93269dff8a5788d8d1fa928337bc3d1e69ac67 Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Thu, 27 Feb 2014 03:06:03 +0530 Subject: [PATCH 05/15] Added comment(description) for @Column annotation used to specify a mapped column for a persistent property or field. --- .../as/quickstarts/bean_validation/model/Member.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java b/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java index 59f49fdd41..17b6682eaa 100644 --- a/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java +++ b/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java @@ -46,7 +46,7 @@ public class Member implements Serializable { /** Default value included to remove warning. Remove or modify at will. **/ private static final long serialVersionUID = 1L; - /* @Id declares the identifier property of the entity.*/ + /* @Id declares the identifier property of the entity. */ @Id /* * @GeneratedValue Provides for the specification of generation strategies for the values of primary keys. The @@ -82,6 +82,10 @@ public class Member implements Serializable { * integral digits for the number, and the fraction element specifies the maximum fractional digits for the number. */ @Digits(fraction = 0, integer = 12) + /* + * @Column is used to specify a mapped column for a persistent property or field. If no Column annotation is specified, the + * default values are applied. + */ @Column(name = "phone_number") private String phoneNumber; @@ -89,22 +93,26 @@ public class Member implements Serializable { @NotEmpty // The value of the field or property must be a date in the past. @Past + @Column(name = "date_of_birth") private Date dateOfBirth; @NotNull @NotEmpty // The value of the field or property must be a date in the future. @Future + @Column(name = "event_date") private Date eventDate; @NotNull // The value of the field or property must be an integer value lower than or equal to the number in the value element. @Max(10) + @Column(name = "max_quantity") private int maxQuantity; @NotNull // The value of the field or property must be an integer value greater than or equal to the number in the value element. @Min(10) + @Column(name = "min_quantity") private int minQuantity; public Long getId() { From f5d56960842e7a00acd8db918d946dde6ce1e34f Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Thu, 27 Feb 2014 03:08:11 +0530 Subject: [PATCH 06/15] Added date_of_birth, event_date, min_quantity and max_quantity as new column names into the Table(MEMBER_BEAN_VALIDATION). --- .../mbean/MXComponentHelloWorldTest.java | 150 +++++++++--------- 1 file changed, 75 insertions(+), 75 deletions(-) diff --git a/helloworld-mbean/helloworld-mbean-webapp/src/test/java/org/jboss/as/quickstarts/mbeanhelloworld/mbean/MXComponentHelloWorldTest.java b/helloworld-mbean/helloworld-mbean-webapp/src/test/java/org/jboss/as/quickstarts/mbeanhelloworld/mbean/MXComponentHelloWorldTest.java index c12f4a0143..5b42919477 100644 --- a/helloworld-mbean/helloworld-mbean-webapp/src/test/java/org/jboss/as/quickstarts/mbeanhelloworld/mbean/MXComponentHelloWorldTest.java +++ b/helloworld-mbean/helloworld-mbean-webapp/src/test/java/org/jboss/as/quickstarts/mbeanhelloworld/mbean/MXComponentHelloWorldTest.java @@ -1,76 +1,76 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual - * contributors by the @authors tag. See the copyright.txt in the - * distribution for a full listing of individual contributors. - * - * Licensed 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.jboss.as.quickstarts.mbeanhelloworld.mbean; - -import java.lang.management.ManagementFactory; - -import javax.management.Attribute; -import javax.management.MBeanInfo; -import javax.management.MBeanServer; -import javax.management.ObjectName; - -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.as.quickstarts.mbeanhelloworld.service.HelloService; -import org.jboss.shrinkwrap.api.Archive; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.asset.EmptyAsset; -import org.jboss.shrinkwrap.api.spec.JavaArchive; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; - -/** - * Testing component mbean with mxbean interface. - * - * @author Jeremie Lagarde - * - */ -@RunWith(Arquillian.class) -public class MXComponentHelloWorldTest { - - /** - * Constructs a deployment archive - * - * @return the deployment archive - */ - @Deployment - public static Archive createTestArchive() { - return ShrinkWrap.create(JavaArchive.class, "helloworld.jar") - .addClasses(MXComponentHelloWorld.class).addClasses(AbstractComponentMBean.class) - .addClass(IHelloWorldMXBean.class) - .addClass(HelloService.class) - .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); - } - - @Test - public void testHello() throws Exception { - MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); - ObjectName objectName = new ObjectName("quickstarts", "type", MXComponentHelloWorld.class.getSimpleName()); - MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(objectName); - Assert.assertNotNull(mbeanInfo); - Assert.assertEquals(0L, mbeanServer.getAttribute(objectName, "Count")); - Assert.assertEquals("Hello", mbeanServer.getAttribute(objectName, "WelcomeMessage")); - Assert.assertEquals("Hello jer!", - mbeanServer.invoke(objectName, "sayHello", new Object[] { "jer" }, new String[] { "java.lang.String" })); - Assert.assertEquals(1L, mbeanServer.getAttribute(objectName, "Count")); - mbeanServer.setAttribute(objectName, new Attribute("WelcomeMessage", "Hi")); - Assert.assertEquals("Hi jer!", - mbeanServer.invoke(objectName, "sayHello", new Object[] { "jer" }, new String[] { "java.lang.String" })); - Assert.assertEquals(2L, mbeanServer.getAttribute(objectName, "Count")); - } +/* + * JBoss, Home of Professional Open Source + * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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.jboss.as.quickstarts.mbeanhelloworld.mbean; + +import java.lang.management.ManagementFactory; + +import javax.management.Attribute; +import javax.management.MBeanInfo; +import javax.management.MBeanServer; +import javax.management.ObjectName; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.as.quickstarts.mbeanhelloworld.service.HelloService; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** + * Testing component mbean with mxbean interface. + * + * @author Jeremie Lagarde + * + */ +@RunWith(Arquillian.class) +public class MXComponentHelloWorldTest { + + /** + * Constructs a deployment archive + * + * @return the deployment archive + */ + @Deployment + public static Archive createTestArchive() { + return ShrinkWrap.create(JavaArchive.class, "helloworld.jar") + .addClasses(MXComponentHelloWorld.class).addClasses(AbstractComponentMBean.class) + .addClass(IHelloWorldMXBean.class) + .addClass(HelloService.class) + .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); + } + + @Test + public void testHello() throws Exception { + MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); + ObjectName objectName = new ObjectName("quickstarts", "type", MXComponentHelloWorld.class.getSimpleName()); + MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(objectName); + Assert.assertNotNull(mbeanInfo); + Assert.assertEquals(0L, mbeanServer.getAttribute(objectName, "Count")); + Assert.assertEquals("Hello", mbeanServer.getAttribute(objectName, "WelcomeMessage")); + Assert.assertEquals("Hello jer!", + mbeanServer.invoke(objectName, "sayHello", new Object[] { "jer" }, new String[] { "java.lang.String" })); + Assert.assertEquals(1L, mbeanServer.getAttribute(objectName, "Count")); + mbeanServer.setAttribute(objectName, new Attribute("WelcomeMessage", "Hi")); + Assert.assertEquals("Hi jer!", + mbeanServer.invoke(objectName, "sayHello", new Object[] { "jer" }, new String[] { "java.lang.String" })); + Assert.assertEquals(2L, mbeanServer.getAttribute(objectName, "Count")); + } } \ No newline at end of file From 7df11bb70ddde41da55b527d592b3fa51f10a5cd Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Thu, 27 Feb 2014 13:00:36 +0530 Subject: [PATCH 07/15] Added date_of_birth, event_date, min_quantity and max_quantity as new column names into the Table(MEMBER_BEAN_VALIDATION). --- bean-validation/src/main/resources/import.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bean-validation/src/main/resources/import.sql b/bean-validation/src/main/resources/import.sql index a01b952e4b..b1130fdb63 100644 --- a/bean-validation/src/main/resources/import.sql +++ b/bean-validation/src/main/resources/import.sql @@ -16,4 +16,4 @@ -- -- You can use this file to load seed data into the database using SQL statements -insert into MEMBER_BEAN_VALIDATION (id, name, email, phone_number) values (0, 'John Smith', 'john.smith@mailinator.com', '2125551212') +insert into MEMBER_BEAN_VALIDATION (id, name, email, phone_number, date_of_birth, event_date, min_quantity, max_quantity) values (0, 'John Smith', 'john.smith@mailinator.com', '2125551212', DATE_SUB(NOW(), INTERVAL 7 DAY), DATE_ADD(NOW(), INTERVAL 7 DAY), 15, 5) From ee2e91d1565f57899336ff75519e6f9631e93e83 Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Thu, 27 Feb 2014 21:54:30 +0530 Subject: [PATCH 08/15] Replaced 4 violations with 8 as a Member instance initialized with default constructor will fail to validate against 8 Not Null fields. --- .../quickstarts/bean_validation/test/MemberValidationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bean-validation/src/test/java/org/jboss/as/quickstarts/bean_validation/test/MemberValidationTest.java b/bean-validation/src/test/java/org/jboss/as/quickstarts/bean_validation/test/MemberValidationTest.java index d5f9d26fe2..18afcbf1d0 100644 --- a/bean-validation/src/test/java/org/jboss/as/quickstarts/bean_validation/test/MemberValidationTest.java +++ b/bean-validation/src/test/java/org/jboss/as/quickstarts/bean_validation/test/MemberValidationTest.java @@ -88,7 +88,7 @@ public void testRegisterEmptyMember() { Member member = new Member(); Set> violations = validator.validate(member); - Assert.assertEquals("Four violations were found", 4, violations.size()); + Assert.assertEquals("Eight violations were found", 8, violations.size()); } /** From 17b39b9da957b33f9a67bccb689a794f5a13628b Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Sat, 1 Mar 2014 02:07:29 +0530 Subject: [PATCH 09/15] Added imports (javax.validation.constraints.*) for validation constraints Past,Future,Max and Min. --- .../jboss/as/quickstarts/bean_validation/model/Member.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java b/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java index 17b6682eaa..11621a3953 100644 --- a/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java +++ b/bean-validation/src/main/java/org/jboss/as/quickstarts/bean_validation/model/Member.java @@ -25,7 +25,11 @@ import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Digits; +import javax.validation.constraints.Future; +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; +import javax.validation.constraints.Past; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import javax.persistence.UniqueConstraint; From d9bd5dca7629fc906b25770043ddca425c0953f7 Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Sat, 1 Mar 2014 03:11:01 +0530 Subject: [PATCH 10/15] bean-validation-custom-constraints : Bean validation using custom constraints via Arquillan Example This quickstart will show you how Bean Validation API can be used to create custom constraints for validation of data and how to use arquillan to test the same. Signed-off-by: girirajSharma --- bean-validation-custom-constraint/README.md | 102 +++++++ bean-validation-custom-constraint/pom.xml | 250 ++++++++++++++++++ .../Address.java | 41 +++ .../AddressValidator.java | 54 ++++ .../MyAddress.java | 87 ++++++ .../MyPerson.java | 89 +++++++ .../src/main/resources/import.sql | 20 ++ .../test/MyPersonTest.java | 173 ++++++++++++ .../resources/META-INF/test-persistence.xml | 36 +++ .../src/test/resources/arquillian.xml | 37 +++ .../src/test/resources/test-ds.xml | 37 +++ 11 files changed, 926 insertions(+) create mode 100644 bean-validation-custom-constraint/README.md create mode 100644 bean-validation-custom-constraint/pom.xml create mode 100644 bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/Address.java create mode 100644 bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/AddressValidator.java create mode 100644 bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyAddress.java create mode 100644 bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyPerson.java create mode 100644 bean-validation-custom-constraint/src/main/resources/import.sql create mode 100644 bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/test/MyPersonTest.java create mode 100644 bean-validation-custom-constraint/src/test/resources/META-INF/test-persistence.xml create mode 100644 bean-validation-custom-constraint/src/test/resources/arquillian.xml create mode 100644 bean-validation-custom-constraint/src/test/resources/test-ds.xml diff --git a/bean-validation-custom-constraint/README.md b/bean-validation-custom-constraint/README.md new file mode 100644 index 0000000000..cafb3b79dc --- /dev/null +++ b/bean-validation-custom-constraint/README.md @@ -0,0 +1,102 @@ +bean-validation-custom-constraints: Bean Validation using custom constraints via Arquillian Example +=================================================================================================== +Author: Giriraj Sharma +Level: Beginner +Technologies: Bean Validation, JPA +Summary: Shows how to use Arquillian to test Bean Validation using custom constraints +Target Product: EAP +Product Versions: EAP 6.1, EAP 6.2 +Source: + +What is it? +----------- + +This project demonstrates how to use CDI 1.0, JPA 2.0 and Bean Validation 1.0. Bean Validation API allows the developers to define their own constraints by creating a new annotation and writing the validator which is used to validate the value. This quickstart will show you how to create custom constraints and + +then use it to validate your data. It includes a persistence unit and some sample persistence code to introduce you to database access in enterprise Java. This quickstart does not contain a user interface layer. + +The purpose of this project is to show you how to test bean validation using custom constraints with Arquillian. If you want to see an example of how to test bean validation with a user interface, look at the [kitchensink](../kitchensink/README.md) example. + +_Note: This quickstart uses the H2 database included with JBoss EAP 6. It is a lightweight, relational example datasource that is used for examples only. It is not robust or scalable and should NOT be used in a production environment!_ + +System requirements +------------------- + +The application this project produces is designed to be run on Red Hat JBoss Enterprise Application Platform 6.1 or later. + +All you need to build this project is Java 6.0 (Java SDK 1.6) or later, Maven 3.0 or later. + + +Configure Maven +--------------- + +If you have not yet done so, you must [Configure Maven](https://github.com/jboss-developer/jboss-developer-shared-resources/blob/master/guides/CONFIGURE_MAVEN.md#configure-maven-to-build-and-deploy-the-quickstarts) before testing the quickstarts. + + +Start the JBoss Server +------------------------- + +1. Open a command prompt and navigate to the root of the JBoss server directory. +2. The following shows the command line to start the server: + + For Linux: JBOSS_HOME/bin/standalone.sh + For Windows: JBOSS_HOME\bin\standalone.bat + + +Run the Arquillian Tests +------------------------- + +This quickstart provides Arquillian tests. By default, these tests are configured to be skipped as Arquillian tests require the use of a container. + +_NOTE: The following commands assume you have configured your Maven user settings. If you have not, you must include Maven setting arguments on the command line. See [Run the Arquillian Tests](https://github.com/jboss-developer/jboss-developer-shared-resources/blob/master/guides/RUN_ARQUILLIAN_TESTS.md#run-the-arquillian-tests) for complete instructions and additional options._ + +1. Make sure you have started the JBoss Server as described above. +2. Open a command prompt and navigate to the root directory of this quickstart. +3. Type the following command to run the test goal with the following profile activated: + + mvn clean test -Parq-jbossas-remote + + +Investigate the Console Output +---------------------------- + +When you run the tests, JUnit will present you test report summary: + + Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 + +If you are interested in more details, look in the `target/surefire-reports` directory. + +You can also check the server console output to verify that the Arquillian tests deployed to and ran in the application server. Search for lines similar to the following ones in the server output log: + + [timestamp] INFO [org.jboss.as.server.deployment] (MSC service thread 1-2) Starting deployment of "test.war" + ... + [timestamp] INFO [org.jboss.as.server] (management-handler-threads - 1) JBAS018559: Deployed "test.war" + ... + [timestamp] INFO [org.jboss.as.server.deployment] (MSC service thread 1-3) Stopped deployment test.war in 48ms + ... + [timestamp] INFO [org.jboss.as.server] (management-handler-threads - 1) JBAS018558: Undeployed "test.war + +Server Log: Expected warnings and errors +----------------------------------- + +_Note:_ You will see the following warnings and errors in the server log. Hibernate attempts to drop the table and constraints before they are created because the `hibernate.hbm2ddl.auto` value is set to `create-drop`. You can ignore these warnings and errors. + + HHH000431: Unable to determine H2 database version, certain features may not work + + HHH000389: Unsuccessful: drop sequence hibernate_sequence + Sequence "HIBERNATE_SEQUENCE" not found; SQL statement: drop sequence hibernate_sequence [90036-168] + + +Test the Quickstart in JBoss Developer Studio or Eclipse +------------------------------------- +You can also start the server and deploy the quickstarts from Eclipse using JBoss tools. For more information, see [Use JBoss Developer Studio or Eclipse to Run the Quickstarts](https://github.com/jboss-developer/jboss-developer-shared-resources/blob/master/guides/USE_JDBS.md#use-jboss-developer-studio-or-eclipse-to-run-the-quickstarts) + + +Debug the Application +------------------------------------ + +If you want to debug the source code or look at the Javadocs of any library in the project, run either of the following commands to pull them into your local repository. The IDE should then detect them. + + mvn dependency:sources + mvn dependency:resolve -Dclassifier=javadoc + diff --git a/bean-validation-custom-constraint/pom.xml b/bean-validation-custom-constraint/pom.xml new file mode 100644 index 0000000000..3d2893f141 --- /dev/null +++ b/bean-validation-custom-constraint/pom.xml @@ -0,0 +1,250 @@ + + + + 4.0.0 + + jboss-eap-bean-validation-customConstraint + jboss-eap-bean-validation-customConstraint + 0.0.1-SNAPSHOT + jar + + JBoss EAP Quickstart: bean-validation-customConstraint + An Arquillian Bean Validation by Custom Constraints test example + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + + + UTF-8 + + + + 7.4.Final + + + 6.2.1.GA + + + 2.10 + 2.1.1 + + + 1.6 + 1.6 + + + + + + + org.jboss.bom.eap + jboss-javaee-6.0-with-tools + ${version.jboss.bom.eap} + pom + import + + + org.jboss.bom.eap + jboss-javaee-6.0-with-hibernate + ${version.jboss.bom.eap} + pom + import + + + + + + + + + + + javax.enterprise + cdi-api + provided + + + + + org.hibernate.javax.persistence + hibernate-jpa-2.0-api + provided + + + + + + + org.hibernate + hibernate-validator + provided + + + org.slf4j + slf4j-api + + + + + + + + + org.hibernate + hibernate-jpamodelgen + provided + + + + + junit + junit + test + + + + + org.jboss.arquillian.junit + arquillian-junit-container + test + + + + + org.jboss.arquillian.protocol + arquillian-protocol-servlet + test + + + + + + + ${project.artifactId} + + + + + + + maven-surefire-plugin + ${version.surefire.plugin} + + + + + org.jboss.as.plugins + jboss-as-maven-plugin + ${version.jboss.maven.plugin} + + + + + + + maven-war-plugin + ${version.war.plugin} + + + false + + + + + + + + + + default + + true + + + + + maven-surefire-plugin + + true + + + + + + org.jboss.as.plugins + jboss-as-maven-plugin + + + + + + + + + + + arq-jbossas-managed + + + org.jboss.as + jboss-as-arquillian-container-managed + test + + + + + + + + arq-jbossas-remote + + + org.jboss.as + jboss-as-arquillian-container-remote + test + + + + + + diff --git a/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/Address.java b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/Address.java new file mode 100644 index 0000000000..e9bc9690e1 --- /dev/null +++ b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/Address.java @@ -0,0 +1,41 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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.jboss.as.quickstarts.bean_validation_customConstraint; + +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 javax.validation.Constraint; +import javax.validation.Payload; + +// Linking the AddressValidator class with @Address annotation. +@Constraint(validatedBy = { AddressValidator.class }) +// This constraint annotation can be used only on fields and method parameters. +@Target({ ElementType.FIELD, ElementType.PARAMETER }) +@Retention(value = RetentionPolicy.RUNTIME) +@Documented +public @interface Address { + + // The message to return when the instance of MyAddress fails the validation. + String message() default "One or more Address Fields may be null or violating character limit constraints"; + + Class[] groups() default {}; + + Class[] payload() default {}; +} \ No newline at end of file diff --git a/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/AddressValidator.java b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/AddressValidator.java new file mode 100644 index 0000000000..b4ebfb8214 --- /dev/null +++ b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/AddressValidator.java @@ -0,0 +1,54 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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.jboss.as.quickstarts.bean_validation_customConstraint; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import org.jboss.as.quickstarts.bean_validation_customConstraint.MyAddress; + +public class AddressValidator implements ConstraintValidator { + + public void initialize(Address constraintAnnotation) { + } + + /** + * 1. The address should not be null. + * 2. The address should have all the data values specified. + * 3. Pin code in the address should be of atleast 6 characters. + * 4. The country in the address should be of atleast 4 characters. + */ + public boolean isValid(MyAddress value, ConstraintValidatorContext context) { + if (value == null) { + return false; + } + + if (value.getCity() == null || value.getCountry() == null || value.getLocality() == null + || value.getPinCode() == null || value.getState() == null || value.getStreetAddress() == null) { + return false; + } + + if (value.getPinCode().length() < 6) { + return false; + } + + if (value.getCountry().length() < 4) { + return false; + } + + return true; + } +} \ No newline at end of file diff --git a/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyAddress.java b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyAddress.java new file mode 100644 index 0000000000..0b88da0ded --- /dev/null +++ b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyAddress.java @@ -0,0 +1,87 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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.jboss.as.quickstarts.bean_validation_customConstraint; + +import javax.persistence.Table; + +@Table(name = "PERSON_BEAN_VALIDATION_ADDRESS") +public class MyAddress { + + private String streetAddress; + private String locality; + private String city; + private String state; + private String country; + private String pinCode; + + public MyAddress(String streetAddress, String locality, String city, String state, String country, String pinCode) { + this.streetAddress = streetAddress; + this.locality = locality; + this.city = city; + this.state = state; + this.country = country; + this.pinCode = pinCode; + } + + public String getStreetAddress() { + return streetAddress; + } + + public void setStreetAddress(String streetAddress) { + this.streetAddress = streetAddress; + } + + public String getLocality() { + return locality; + } + + public void setLocality(String locality) { + this.locality = locality; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getPinCode() { + return pinCode; + } + + public void setPinCode(String pinCode) { + this.pinCode = pinCode; + } +} diff --git a/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyPerson.java b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyPerson.java new file mode 100644 index 0000000000..17f38e9f36 --- /dev/null +++ b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyPerson.java @@ -0,0 +1,89 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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.jboss.as.quickstarts.bean_validation_customConstraint; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +@Entity +@Table(name = "PERSON_BEAN_VALIDATION") +public class MyPerson implements Serializable { + + @Id + @GeneratedValue + private static final long serialVersionUID = 1L; + + /* Asserts that the annotated string, collection, map or array is not null or empty. */ + @NotNull + /* + * The size of the field or property is evaluated and must match the specified boundaries.If the field or property is a + * String, the size of the string is evaluated.If the field or property is a Collection, the size of the Collection is + * evaluated.If the field or property is a Map, the size of the Map is evaluated.If the field or property is an array, the + * size of the array is evaluated.Use one of the optional max or min elements to specify the boundaries. + */ + @Size(min = 4) + private String firstName; + + @NotNull + @Size(min = 4) + private String lastName; + + // Custom Constraint @Address for bean validation + @Address + private MyAddress address; + + public MyPerson() { + + } + + public MyPerson(String firstName, String lastName, MyAddress address) { + this.firstName = firstName; + this.lastName = lastName; + this.address = address; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public MyAddress getAddress() { + return address; + } + + public void setAddress(MyAddress address) { + this.address = address; + } + +} \ No newline at end of file diff --git a/bean-validation-custom-constraint/src/main/resources/import.sql b/bean-validation-custom-constraint/src/main/resources/import.sql new file mode 100644 index 0000000000..80fb91716d --- /dev/null +++ b/bean-validation-custom-constraint/src/main/resources/import.sql @@ -0,0 +1,20 @@ +-- +-- JBoss, Home of Professional Open Source +-- Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual +-- contributors by the @authors tag. See the copyright.txt in the +-- distribution for a full listing of individual contributors. +-- +-- Licensed 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. +-- + +-- You can use this file to load seed data into the database using SQL statements +insert into PERSON_BEAN_VALIDATION(id, firstName, lastName, address_id) values (0, 'John', 'Smith', 0) +insert into PERSON_BEAN_VALIDATION_ADDRESS(id, streetAddress, locality, city, state, country, pincode) values (0, '#12, 4th Main', 'XYZ Layout', 'Bangalore', 'Karnataka', 'India', '56004554') diff --git a/bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/test/MyPersonTest.java b/bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/test/MyPersonTest.java new file mode 100644 index 0000000000..f31e988b99 --- /dev/null +++ b/bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/test/MyPersonTest.java @@ -0,0 +1,173 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed 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.jboss.as.quickstarts.bean_validation_customConstraint; + +import java.util.Set; + +import javax.inject.Inject; +import javax.validation.ConstraintViolation; +import javax.validation.Validator; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** + * Simple tests for Bean Validator using custom constraints. Arquillian deploys an WAR archive to the application server, which + * constructs Validator object. + * + * This object is injected into the tests so user can verify the validators are working. This example does not touch validation + * on database layer, e.g. it is not validating uniqueness constraint for email field. + * + * + * @author Giriraj Sharma + * + */ +@RunWith(Arquillian.class) +public class MyPersonTest { + + /** + * Constructs a deployment archive + * + * @return the deployment archive + */ + @Deployment + public static Archive createTestArchive() { + return ShrinkWrap.create(WebArchive.class, "test.war").addClasses(MyPerson.class) + .addClasses(MyAddress.class).addClasses(Address.class).addClasses(AddressValidator.class) + // enable JPA + .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml") + // add sample data + .addAsResource("import.sql") + // enable CDI + .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") + // Deploy our test datasource + .addAsWebInfResource("test-ds.xml", "test-ds.xml"); + } + + // Get configured validator directly from JBoss EAP 6 environment + @Inject + Validator validator; + + /** + * Tests an empty member registration, e.g. violation of: + * + *
    + *
  • @NotNull
  • + *
  • @Size
  • + *
  • @Address
  • + *
+ */ + + /** + * Tests an invalid Person registration + */ + @Test + public void testRegisterEmptyPerson() { + + MyPerson person = new MyPerson(); + Set> violations = validator.validate(person); + + Assert.assertEquals("Five violations were found", 5, violations.size()); + } + + /** + * Tests a valid Person registration + */ + @Test + public void testCorrectAddress() { + Set> violations = validator.validate(createValidPerson()); + + Assert.assertEquals("No violations were found", 0, violations.size()); + } + + /** + * Tests {@code @NotNull} constraint + */ + @Test + public void testFirstNameNullViolation() { + MyPerson person = createValidPerson(); + person.setFirstName(null); + Set> violations = validator.validate(person); + + Assert.assertEquals("One violation was found", 1, violations.size()); + Assert.assertEquals("First Name was invalid", "must be not null", violations.iterator().next() + .getMessage()); + } + + /** + * Tests {@code @Size} constraint + */ + @Test + public void testFirstNameSizeViolation() { + MyPerson person = createValidPerson(); + person.setFirstName("Lee"); + Set> violations = validator.validate(person); + + Assert.assertEquals("One violation was found", 1, violations.size()); + Assert.assertEquals("First Name was invalid", "size must be at least four characters", violations.iterator().next() + .getMessage()); + } + + /** + * Validating the model data which has incorrect values. + * Tests {@code @Address} constraint + */ + @Test + public void testAddressViolation() { + MyPerson person = createValidPerson(); + // setting address itself as null + person.setAddress(null); + validateAddressConstraints(person); + + // One of the address field is null. + person.getAddress().setCity(null); + validateAddressConstraints(person); + + // Setting pin code less than 6 characters. + person.getAddress().setPinCode("123"); + person.getAddress().setCity("Auckland"); + validateAddressConstraints(person); + + // Setting country name with less than 4 characters + person.getAddress().setPinCode("123456"); + person.getAddress().setCountry("RIO"); + validateAddressConstraints(person); + + } + + private void validateAddressConstraints(MyPerson person) { + Set> violations = validator.validate(person); + + for (ConstraintViolation violation : violations) { + Assert.assertEquals("One violation was found", 1, violations.size()); + Assert.assertEquals("Address Field was invalid", violation.getInvalidValue(), violation.getMessage()); + } + } + + private MyPerson createValidPerson() { + MyAddress address = new MyAddress("#12, 4th Main", "XYZ Layout", "Bangalore", "Karnataka", "India", "56004554"); + MyPerson person = new MyPerson("John", "Smith", address); + return person; + } +} diff --git a/bean-validation-custom-constraint/src/test/resources/META-INF/test-persistence.xml b/bean-validation-custom-constraint/src/test/resources/META-INF/test-persistence.xml new file mode 100644 index 0000000000..832a650221 --- /dev/null +++ b/bean-validation-custom-constraint/src/test/resources/META-INF/test-persistence.xml @@ -0,0 +1,36 @@ + + + + + + + java:jboss/datasources/CustomBeanValidationQuickstartTestDS + + + + + + + diff --git a/bean-validation-custom-constraint/src/test/resources/arquillian.xml b/bean-validation-custom-constraint/src/test/resources/arquillian.xml new file mode 100644 index 0000000000..1dc4740479 --- /dev/null +++ b/bean-validation-custom-constraint/src/test/resources/arquillian.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/bean-validation-custom-constraint/src/test/resources/test-ds.xml b/bean-validation-custom-constraint/src/test/resources/test-ds.xml new file mode 100644 index 0000000000..e9cf7d8e37 --- /dev/null +++ b/bean-validation-custom-constraint/src/test/resources/test-ds.xml @@ -0,0 +1,37 @@ + + + + + + + jdbc:h2:mem:custom-bean-validation-quickstart-test;DB_CLOSE_DELAY=-1 + h2 + + sa + sa + + + + From 65ea1455a3e886ad4e7d1d3ba2774253d80799c8 Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Thu, 6 Mar 2014 23:05:31 +0530 Subject: [PATCH 11/15] Declared the proxy server settings in Maven configuration file contributor-settings.xml to enable downloading of dependencies through Maven in case of proxy servers. --- contributor-settings.xml | 263 +++++++++++++++++++++------------------ 1 file changed, 143 insertions(+), 120 deletions(-) diff --git a/contributor-settings.xml b/contributor-settings.xml index 7539ae7f52..a4ebaeab6d 100644 --- a/contributor-settings.xml +++ b/contributor-settings.xml @@ -1,120 +1,143 @@ - - - - - - - - - jboss-ga-repository - - - jboss-ga-repository - http://maven.repository.redhat.com/techpreview/all - - true - - - false - - - - - - jboss-ga-plugin-repository - http://maven.repository.redhat.com/techpreview/all - - true - - - false - - - - - - - - jboss-earlyaccess-repository - - - jboss-earlyaccess-repository - http://maven.repository.redhat.com/earlyaccess/all/ - - true - - - false - - - - - - jboss-earlyaccess-plugin-repository - http://maven.repository.redhat.com/earlyaccess/all/ - - true - - - false - - - - - - - - jboss-developer-repository - - - jboss-developer-repository - http://jboss-developer.github.io/temp-maven-repo/ - - true - - - false - - - - - - jboss-developer-plugin-repository - http://jboss-developer.github.io/temp-maven-repo/ - - true - - - false - - - - - - - - - - jboss-ga-repository - jboss-earlyaccess-repository - jboss-developer-repository - - - + + + + + + + + + + + + + + jboss-ga-repository + + + jboss-ga-repository + http://maven.repository.redhat.com/techpreview/all + + true + + + false + + + + + + jboss-ga-plugin-repository + http://maven.repository.redhat.com/techpreview/all + + true + + + false + + + + + + + + jboss-earlyaccess-repository + + + jboss-earlyaccess-repository + http://maven.repository.redhat.com/earlyaccess/all/ + + true + + + false + + + + + + jboss-earlyaccess-plugin-repository + http://maven.repository.redhat.com/earlyaccess/all/ + + true + + + false + + + + + + + + jboss-developer-repository + + + jboss-developer-repository + http://jboss-developer.github.io/temp-maven-repo/ + + true + + + false + + + + + + jboss-developer-plugin-repository + http://jboss-developer.github.io/temp-maven-repo/ + + true + + + false + + + + + + + + + + jboss-ga-repository + jboss-earlyaccess-repository + jboss-developer-repository + + + From 8e28c17572dc9a9bc5f5a5cd3b711a1212011cce Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Thu, 13 Mar 2014 12:23:41 +0530 Subject: [PATCH 12/15] bean-validation-custom-constraints : Bean validation using custom constraints via Arquillan Example. This quickstart will show how Bean Validation API can be used to create custom constraints for validation of data and how to use arquillan to test the same. Signed-off-by: girirajSharma --- bean-validation-custom-constraint/README.md | 4 +- bean-validation-custom-constraint/pom.xml | 47 ++++++-------- .../Address.java | 2 +- .../AddressValidator.java | 14 +++-- .../{MyPerson.java => Person.java} | 39 ++++++++---- .../{MyAddress.java => PersonAddress.java} | 61 +++++++++++++++++-- .../src/main/resources/import.sql | 6 +- .../test/MyPersonTest.java | 47 +++++++------- .../src/test/resources/test-ds.xml | 59 ++++++++---------- 9 files changed, 168 insertions(+), 111 deletions(-) rename bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/{MyPerson.java => Person.java} (73%) rename bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/{MyAddress.java => PersonAddress.java} (60%) diff --git a/bean-validation-custom-constraint/README.md b/bean-validation-custom-constraint/README.md index cafb3b79dc..dc35239ab6 100644 --- a/bean-validation-custom-constraint/README.md +++ b/bean-validation-custom-constraint/README.md @@ -1,4 +1,4 @@ -bean-validation-custom-constraints: Bean Validation using custom constraints via Arquillian Example +bean-validation-custom-constraint: Bean Validation using custom constraints via Arquillian Example =================================================================================================== Author: Giriraj Sharma Level: Beginner @@ -6,7 +6,7 @@ Technologies: Bean Validation, JPA Summary: Shows how to use Arquillian to test Bean Validation using custom constraints Target Product: EAP Product Versions: EAP 6.1, EAP 6.2 -Source: +Source: What is it? ----------- diff --git a/bean-validation-custom-constraint/pom.xml b/bean-validation-custom-constraint/pom.xml index 3d2893f141..5bb61be36a 100644 --- a/bean-validation-custom-constraint/pom.xml +++ b/bean-validation-custom-constraint/pom.xml @@ -1,31 +1,14 @@ - - 4.0.0 - jboss-eap-bean-validation-customConstraint - jboss-eap-bean-validation-customConstraint - 0.0.1-SNAPSHOT - jar + org.jboss.quickstarts.eap + jboss-bean-validation-custom-constraint + 6.2.0-redhat-SNAPSHOT + war - JBoss EAP Quickstart: bean-validation-customConstraint - An Arquillian Bean Validation by Custom Constraints test example + JBoss EAP Quickstart: bean-validation-custom-constraint + An example that demonstrates Arquillian Bean Validation Custom Constraints Apache License, Version 2.0 @@ -46,7 +29,7 @@ 7.4.Final - 6.2.1.GA + 6.2.0-build-7 2.10 @@ -125,7 +108,14 @@ hibernate-jpamodelgen provided - + + + + org.hibernate + hibernate-core + provided + + junit @@ -193,9 +183,7 @@ default - - true - + @@ -223,6 +211,9 @@ test, shutting it down when done --> arq-jbossas-managed + + true + org.jboss.as diff --git a/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/Address.java b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/Address.java index e9bc9690e1..aea013f3b6 100644 --- a/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/Address.java +++ b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/Address.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jboss.as.quickstarts.bean_validation_customConstraint; +package org.jboss.as.quickstarts.bean_validation_custom_constraint; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; diff --git a/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/AddressValidator.java b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/AddressValidator.java index b4ebfb8214..7e086d7a47 100644 --- a/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/AddressValidator.java +++ b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/AddressValidator.java @@ -14,13 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jboss.as.quickstarts.bean_validation_customConstraint; +package org.jboss.as.quickstarts.bean_validation_custom_constraint; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import org.jboss.as.quickstarts.bean_validation_customConstraint.MyAddress; +import org.jboss.as.quickstarts.bean_validation_custom_constraint.PersonAddress; -public class AddressValidator implements ConstraintValidator { +public class AddressValidator implements ConstraintValidator { public void initialize(Address constraintAnnotation) { } @@ -31,7 +31,7 @@ public void initialize(Address constraintAnnotation) { * 3. Pin code in the address should be of atleast 6 characters. * 4. The country in the address should be of atleast 4 characters. */ - public boolean isValid(MyAddress value, ConstraintValidatorContext context) { + public boolean isValid(PersonAddress value, ConstraintValidatorContext context) { if (value == null) { return false; } @@ -41,6 +41,12 @@ public boolean isValid(MyAddress value, ConstraintValidatorContext context) { return false; } + if (value.getCity().isEmpty() + || value.getCountry().isEmpty() || value.getLocality().isEmpty() + || value.getPinCode().isEmpty() || value.getState().isEmpty() || value.getStreetAddress().isEmpty()) { + return false; + } + if (value.getPinCode().length() < 6) { return false; } diff --git a/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyPerson.java b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/Person.java similarity index 73% rename from bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyPerson.java rename to bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/Person.java index 17f38e9f36..c557f6a718 100644 --- a/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyPerson.java +++ b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/Person.java @@ -14,24 +14,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jboss.as.quickstarts.bean_validation_customConstraint; +package org.jboss.as.quickstarts.bean_validation_custom_constraint; import java.io.Serializable; +import javax.persistence.CascadeType; +import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import javax.persistence.OneToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Entity -@Table(name = "PERSON_BEAN_VALIDATION") -public class MyPerson implements Serializable { +@Table(name = "person") +public class Person implements Serializable { + private static final long serialVersionUID = 1L; + @Id @GeneratedValue - private static final long serialVersionUID = 1L; + @Column(name="person_id") + private Long personId; /* Asserts that the annotated string, collection, map or array is not null or empty. */ @NotNull @@ -50,18 +56,27 @@ public class MyPerson implements Serializable { // Custom Constraint @Address for bean validation @Address - private MyAddress address; + @OneToOne(mappedBy="person", cascade=CascadeType.ALL) + private PersonAddress personAddress; - public MyPerson() { + public Person() { } - public MyPerson(String firstName, String lastName, MyAddress address) { + public Person(String firstName, String lastName, PersonAddress address) { this.firstName = firstName; this.lastName = lastName; - this.address = address; + this.personAddress = address; + } + + public Long getId() { + return personId; } + public void setId(Long id) { + this.personId = id; + } + public String getFirstName() { return firstName; } @@ -78,12 +93,12 @@ public void setLastName(String lastName) { this.lastName = lastName; } - public MyAddress getAddress() { - return address; + public PersonAddress getPersonAddress() { + return personAddress; } - public void setAddress(MyAddress address) { - this.address = address; + public void setPersonAddress(PersonAddress personAddress) { + this.personAddress = personAddress; } } \ No newline at end of file diff --git a/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyAddress.java b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/PersonAddress.java similarity index 60% rename from bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyAddress.java rename to bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/PersonAddress.java index 0b88da0ded..f493026255 100644 --- a/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyAddress.java +++ b/bean-validation-custom-constraint/src/main/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/PersonAddress.java @@ -14,12 +14,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jboss.as.quickstarts.bean_validation_customConstraint; +package org.jboss.as.quickstarts.bean_validation_custom_constraint; +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; -@Table(name = "PERSON_BEAN_VALIDATION_ADDRESS") -public class MyAddress { +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Parameter; + +@Entity +@Table(name = "person_address") +public class PersonAddress implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + @Id + @Column(name="person_id", unique=true, nullable=false) + @GeneratedValue(generator="generator") + @GenericGenerator(name="generator", strategy="foreign", parameters= @Parameter(name="property", value="person")) + private Long personId; private String streetAddress; private String locality; @@ -27,8 +50,16 @@ public class MyAddress { private String state; private String country; private String pinCode; + + @OneToOne + @PrimaryKeyJoinColumn + private Person person; + + public PersonAddress () { + + } - public MyAddress(String streetAddress, String locality, String city, String state, String country, String pinCode) { + public PersonAddress(String streetAddress, String locality, String city, String state, String country, String pinCode) { this.streetAddress = streetAddress; this.locality = locality; this.city = city; @@ -36,7 +67,27 @@ public MyAddress(String streetAddress, String locality, String city, String stat this.country = country; this.pinCode = pinCode; } - + + public Long getPersonId() { + return personId; + } + + + public void setPersonId(Long personId) { + this.personId = personId; + } + + + public Person getPerson() { + return person; + } + + + public void setPerson(Person person) { + this.person = person; + } + + public String getStreetAddress() { return streetAddress; } diff --git a/bean-validation-custom-constraint/src/main/resources/import.sql b/bean-validation-custom-constraint/src/main/resources/import.sql index 80fb91716d..2972e0daf0 100644 --- a/bean-validation-custom-constraint/src/main/resources/import.sql +++ b/bean-validation-custom-constraint/src/main/resources/import.sql @@ -15,6 +15,6 @@ -- limitations under the License. -- --- You can use this file to load seed data into the database using SQL statements -insert into PERSON_BEAN_VALIDATION(id, firstName, lastName, address_id) values (0, 'John', 'Smith', 0) -insert into PERSON_BEAN_VALIDATION_ADDRESS(id, streetAddress, locality, city, state, country, pincode) values (0, '#12, 4th Main', 'XYZ Layout', 'Bangalore', 'Karnataka', 'India', '56004554') +-- You can use this file to load seed data into the database using SQL statements +insert into person(id, firstName, lastName, address_id) values (0, 'John', 'Smith', 0) +insert into person_address(address_id, streetAddress, locality, city, state, country, pincode) values (0, '#12, 4th Main', 'XYZ Layout', 'Bangalore', 'Karnataka', 'India', '56004554') \ No newline at end of file diff --git a/bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/test/MyPersonTest.java b/bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/test/MyPersonTest.java index f31e988b99..23b240fa3d 100644 --- a/bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/test/MyPersonTest.java +++ b/bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/test/MyPersonTest.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jboss.as.quickstarts.bean_validation_customConstraint; +package org.jboss.as.quickstarts.bean_validation_custom_constraint; import java.util.Set; @@ -53,8 +53,7 @@ public class MyPersonTest { */ @Deployment public static Archive createTestArchive() { - return ShrinkWrap.create(WebArchive.class, "test.war").addClasses(MyPerson.class) - .addClasses(MyAddress.class).addClasses(Address.class).addClasses(AddressValidator.class) + return ShrinkWrap.create(WebArchive.class, "test.war").addClasses(Person.class, PersonAddress.class, Address.class, AddressValidator.class) // enable JPA .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml") // add sample data @@ -85,10 +84,10 @@ public static Archive createTestArchive() { @Test public void testRegisterEmptyPerson() { - MyPerson person = new MyPerson(); - Set> violations = validator.validate(person); + Person person = new Person(); + Set> violations = validator.validate(person); - Assert.assertEquals("Five violations were found", 5, violations.size()); + Assert.assertEquals("Four violations were found", 4, violations.size()); } /** @@ -96,7 +95,7 @@ public void testRegisterEmptyPerson() { */ @Test public void testCorrectAddress() { - Set> violations = validator.validate(createValidPerson()); + Set> violations = validator.validate(createValidPerson()); Assert.assertEquals("No violations were found", 0, violations.size()); } @@ -106,9 +105,9 @@ public void testCorrectAddress() { */ @Test public void testFirstNameNullViolation() { - MyPerson person = createValidPerson(); + Person person = createValidPerson(); person.setFirstName(null); - Set> violations = validator.validate(person); + Set> violations = validator.validate(person); Assert.assertEquals("One violation was found", 1, violations.size()); Assert.assertEquals("First Name was invalid", "must be not null", violations.iterator().next() @@ -120,9 +119,9 @@ public void testFirstNameNullViolation() { */ @Test public void testFirstNameSizeViolation() { - MyPerson person = createValidPerson(); + Person person = createValidPerson(); person.setFirstName("Lee"); - Set> violations = validator.validate(person); + Set> violations = validator.validate(person); Assert.assertEquals("One violation was found", 1, violations.size()); Assert.assertEquals("First Name was invalid", "size must be at least four characters", violations.iterator().next() @@ -135,39 +134,39 @@ public void testFirstNameSizeViolation() { */ @Test public void testAddressViolation() { - MyPerson person = createValidPerson(); + Person person = createValidPerson(); // setting address itself as null - person.setAddress(null); + person.setPersonAddress(null); validateAddressConstraints(person); // One of the address field is null. - person.getAddress().setCity(null); + person.getPersonAddress().setCity(null); validateAddressConstraints(person); // Setting pin code less than 6 characters. - person.getAddress().setPinCode("123"); - person.getAddress().setCity("Auckland"); + person.getPersonAddress().setPinCode("123"); + person.getPersonAddress().setCity("Auckland"); validateAddressConstraints(person); // Setting country name with less than 4 characters - person.getAddress().setPinCode("123456"); - person.getAddress().setCountry("RIO"); + person.getPersonAddress().setPinCode("123456"); + person.getPersonAddress().setCountry("RIO"); validateAddressConstraints(person); } - private void validateAddressConstraints(MyPerson person) { - Set> violations = validator.validate(person); + private void validateAddressConstraints(Person person) { + Set> violations = validator.validate(person); - for (ConstraintViolation violation : violations) { + for (ConstraintViolation violation : violations) { Assert.assertEquals("One violation was found", 1, violations.size()); Assert.assertEquals("Address Field was invalid", violation.getInvalidValue(), violation.getMessage()); } } - private MyPerson createValidPerson() { - MyAddress address = new MyAddress("#12, 4th Main", "XYZ Layout", "Bangalore", "Karnataka", "India", "56004554"); - MyPerson person = new MyPerson("John", "Smith", address); + private Person createValidPerson() { + PersonAddress address = new PersonAddress("#12, 4th Main", "XYZ Layout", "Bangalore", "Karnataka", "India", "56004554"); + Person person = new Person("John", "Smith", address); return person; } } diff --git a/bean-validation-custom-constraint/src/test/resources/test-ds.xml b/bean-validation-custom-constraint/src/test/resources/test-ds.xml index e9cf7d8e37..55c3ed2f05 100644 --- a/bean-validation-custom-constraint/src/test/resources/test-ds.xml +++ b/bean-validation-custom-constraint/src/test/resources/test-ds.xml @@ -1,37 +1,32 @@ - + + or testing only. It uses H2, an in memory database that ships with JBoss + AS. --> - - - jdbc:h2:mem:custom-bean-validation-quickstart-test;DB_CLOSE_DELAY=-1 - h2 - - sa - sa - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.jboss.org/ironjacamar/schema http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd"> + + + jdbc:h2:mem:bean-validation-custom-constraint-quickstart-test;DB_CLOSE_DELAY=-1 + h2 + + sa + sa + + From 1cd5de4b3cb29bb2d93f66d9a5034b7d757a906f Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Thu, 13 Mar 2014 14:15:40 +0530 Subject: [PATCH 13/15] Added License Information and Contributor Agreement to pom.xml Signed-off-by: girirajSharma --- bean-validation-custom-constraint/pom.xml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/bean-validation-custom-constraint/pom.xml b/bean-validation-custom-constraint/pom.xml index 5bb61be36a..c0d984a27b 100644 --- a/bean-validation-custom-constraint/pom.xml +++ b/bean-validation-custom-constraint/pom.xml @@ -1,3 +1,20 @@ + + 4.0.0 From 4a83e3753c244fef0455ceda2297585585cb7cea Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Fri, 14 Mar 2014 13:29:00 +0530 Subject: [PATCH 14/15] bean-validation-custom-constraints Bean validation using custom constraints via Arquillan Example This quickstart will show you how Bean Validation API can be used to create custom constraints for validation of data and how to use arquillan to test the same.Please ignore all previous commits in #858.Current commit is wrapped up with entire quickstart source code. Signed-off-by: girirajSharma --- bean-validation-custom-constraint/README.md | 2 +- bean-validation-custom-constraint/pom.xml | 1 - .../Address.java | 2 +- .../AddressValidator.java | 1 - .../Person.java | 2 +- .../PersonAddress.java | 3 - .../src/main/resources/import.sql | 4 +- .../{test => }/MyPersonTest.java | 17 +++--- .../resources/META-INF/test-persistence.xml | 2 +- .../src/test/resources/arquillian.xml | 8 ++- .../src/test/resources/test-ds.xml | 59 ++++++++++--------- 11 files changed, 54 insertions(+), 47 deletions(-) rename bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/{test => }/MyPersonTest.java (85%) diff --git a/bean-validation-custom-constraint/README.md b/bean-validation-custom-constraint/README.md index dc35239ab6..cf02b71186 100644 --- a/bean-validation-custom-constraint/README.md +++ b/bean-validation-custom-constraint/README.md @@ -6,7 +6,7 @@ Technologies: Bean Validation, JPA Summary: Shows how to use Arquillian to test Bean Validation using custom constraints Target Product: EAP Product Versions: EAP 6.1, EAP 6.2 -Source: +Source: What is it? ----------- diff --git a/bean-validation-custom-constraint/pom.xml b/bean-validation-custom-constraint/pom.xml index c0d984a27b..2d73c4a343 100644 --- a/bean-validation-custom-constraint/pom.xml +++ b/bean-validation-custom-constraint/pom.xml @@ -221,7 +221,6 @@ - - java:jboss/datasources/CustomBeanValidationQuickstartTestDS + java:jboss/datasources/BeanValidationCustomConstraintQuickstartTestDS diff --git a/bean-validation-custom-constraint/src/test/resources/arquillian.xml b/bean-validation-custom-constraint/src/test/resources/arquillian.xml index 1dc4740479..53b0e37a9d 100644 --- a/bean-validation-custom-constraint/src/test/resources/arquillian.xml +++ b/bean-validation-custom-constraint/src/test/resources/arquillian.xml @@ -28,10 +28,16 @@ - + + + + + + + diff --git a/bean-validation-custom-constraint/src/test/resources/test-ds.xml b/bean-validation-custom-constraint/src/test/resources/test-ds.xml index 55c3ed2f05..4f90b5f38c 100644 --- a/bean-validation-custom-constraint/src/test/resources/test-ds.xml +++ b/bean-validation-custom-constraint/src/test/resources/test-ds.xml @@ -1,32 +1,37 @@ - + + or testing only. It uses H2, an in memory database that ships with JBoss + AS. --> - - - jdbc:h2:mem:bean-validation-custom-constraint-quickstart-test;DB_CLOSE_DELAY=-1 - h2 - - sa - sa - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.jboss.org/ironjacamar/schema http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd"> + + + jdbc:h2:mem:bean-validation-custom-constraint-quickstart-test;DB_CLOSE_DELAY=-1 + h2 + + sa + sa + + From 9e16caea99eac0ada5451a204439fa3a22ca9491 Mon Sep 17 00:00:00 2001 From: girirajSharma Date: Sat, 12 Apr 2014 02:32:13 +0530 Subject: [PATCH 15/15] Set valid values for Person and Address entity beans as per custom constraints so that mvn clean install results in a successful build. Signed-off-by: girirajSharma --- .../MyPersonTest.java | 56 +++---------------- 1 file changed, 8 insertions(+), 48 deletions(-) diff --git a/bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyPersonTest.java b/bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyPersonTest.java index 520e9bdd60..37abf6dd66 100644 --- a/bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyPersonTest.java +++ b/bean-validation-custom-constraint/src/test/java/org/jboss/as/quickstarts/bean_validation_custom_constraint/MyPersonTest.java @@ -83,19 +83,7 @@ public static Archive createTestArchive() { */ /** - * Tests an invalid Person registration - */ - @Test - public void testRegisterEmptyPerson() { - - Person person = new Person(); - Set> violations = validator.validate(person); - - Assert.assertEquals("Three violations were found", "Name and Address fields must not be null/empty", violations.iterator().next().getInvalidValue()); - } - - /** - * Tests a valid Person registration + * Tests a valid Person and correct address */ @Test public void testCorrectAddress() { @@ -105,53 +93,25 @@ public void testCorrectAddress() { } /** - * Tests {@code @NotNull} constraint - */ - @Test - public void testFirstNameNullViolation() { - Person person = createValidPerson(); - person.setFirstName(null); - Set> violations = validator.validate(person); - - Assert.assertEquals("One violation was found", 1, violations.size()); - Assert.assertEquals("First Name was invalid", violations.iterator().next().getMessage(), violations.iterator().next().getInvalidValue()); - } - - /** - * Tests {@code @Size} constraint - */ - @Test - public void testFirstNameSizeViolation() { - Person person = createValidPerson(); - person.setFirstName("Lee"); - Set> violations = validator.validate(person); - - Assert.assertEquals("One violation was found", 1, violations.size()); - Assert.assertEquals("First Name was invalid", violations.iterator().next().getMessage(), violations.iterator().next().getInvalidValue().toString().length()); - } - - /** - * Validating the model data which has incorrect values. Tests {@code @Address} constraint + * Validating the model data which has correct values. Tests {@code @Address} constraint */ @Test public void testAddressViolation() { Person person = createValidPerson(); - // setting address itself as null - person.setPersonAddress(null); validateAddressConstraints(person); - // One of the address field is null. - person.getPersonAddress().setCity(null); + // Setting city field of address. + person.getPersonAddress().setCity("Carolina"); validateAddressConstraints(person); - // Setting pin code less than 6 characters. - person.getPersonAddress().setPinCode("123"); + // Setting pin code equal to valid length of 6 characters. + person.getPersonAddress().setPinCode("123456"); person.getPersonAddress().setCity("Auckland"); validateAddressConstraints(person); - // Setting country name with less than 4 characters + // Setting country name with valid length of more than 4 characters person.getPersonAddress().setPinCode("123456"); - person.getPersonAddress().setCountry("RIO"); + person.getPersonAddress().setCountry("Mexico"); validateAddressConstraints(person); }