Aggiunto l'esempio del capitolo sulla Bean Validation

This commit is contained in:
Fabio Scotto di Santolo
2019-03-29 12:19:19 +01:00
parent 0fd4ce96b3
commit 0784cbfb09
16 changed files with 414 additions and 0 deletions

View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.hibernate.validator:hibernate-validator:6.0.16.Final" level="project" />
<orderEntry type="library" name="Maven: javax.validation:validation-api:2.0.1.Final" level="project" />
<orderEntry type="library" name="Maven: org.jboss.logging:jboss-logging:3.3.2.Final" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml:classmate:1.3.4" level="project" />
<orderEntry type="library" name="Maven: org.glassfish:javax.el:3.0.1-b09" level="project" />
<orderEntry type="library" name="Maven: org.jboss.weld.se:weld-se-core:2.0.0.Final" level="project" />
<orderEntry type="library" name="Maven: org.jboss.weld:weld-spi:2.0.Final" level="project" />
<orderEntry type="library" name="Maven: javax.inject:javax.inject:1" level="project" />
<orderEntry type="library" name="Maven: org.jboss.weld:weld-api:2.0.Final" level="project" />
<orderEntry type="library" name="Maven: org.jboss.weld:weld-core:2.0.0.Final" level="project" />
<orderEntry type="library" name="Maven: org.jboss.classfilewriter:jboss-classfilewriter:1.0.4.Final" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava:13.0.1" level="project" />
<orderEntry type="library" name="Maven: org.jboss.spec.javax.interceptor:jboss-interceptors-api_1.2_spec:1.0.0.Alpha3" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-ext:1.7.2" level="project" />
<orderEntry type="library" name="Maven: ch.qos.cal10n:cal10n-api:0.7.7" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.2" level="project" />
<orderEntry type="library" name="Maven: javax.enterprise:cdi-api:1.1" level="project" />
<orderEntry type="library" name="Maven: javax.annotation:jsr250-api:1.0" level="project" />
<orderEntry type="library" name="Maven: javax.el:javax.el-api:3.0-b08" level="project" />
<orderEntry type="library" name="Maven: org.jboss.spec.javax.annotation:jboss-annotations-api_1.2_spec:1.0.0.Alpha1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.projectlombok:lombok:1.18.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
</component>
</module>

View File

@@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>beanvalidationdemo</artifactId>
<name>beanvalidationdemo</name>
<parent>
<artifactId>jeedemo</artifactId>
<groupId>it.plague.jeedemo</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<exec.mainClass>it.plague.jeedemo.BeanValidationMain</exec.mainClass>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12.4</version>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>it.plague.jeedemo.BeanValidationMain</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,32 @@
package it.plague.jeedemo;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Address {
@NotNull
private String street1;
private String street2;
@NotNull
private String city;
private String state;
@NotNull
@ZipCode
private String zipCode;
private String coutry;
public Address(@NotNull String street1, @NotNull String city, String state,
@NotNull String zipCode, String coutry) {
this.street1 = street1;
this.city = city;
this.state = state;
this.zipCode = zipCode;
this.coutry = coutry;
}
}

View File

@@ -0,0 +1,13 @@
package it.plague.jeedemo;
/**
* Hello world!
*
*/
public class BeanValidationMain
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}

View File

@@ -0,0 +1,31 @@
package it.plague.jeedemo;
import java.util.Date;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Customer {
@NotNull
@Size(min = 2)
private String firstName;
private String lastName;
@Email
private String email;
private String phoneNumber;
@Past
private Date dateOfBirth;
private Address deliveryAddress;
public Customer(
@NotNull @Size(min = 2) String firstName, String lastName, String email) {
this(firstName, lastName, email, null, null, null);
}
}

View File

@@ -0,0 +1,37 @@
package it.plague.jeedemo;
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;
import javax.validation.ReportAsSingleViolation;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
@Size(min = 7)
@Pattern(regexp = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\."
+ "[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*"
+ "@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
@ReportAsSingleViolation
@Constraint(validatedBy = {})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Email {
String message() default "{it.plague.jeedemo.Email.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@interface List {
Email[] value();
}
}

View File

@@ -0,0 +1,14 @@
package it.plague.jeedemo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
public @interface USA {
}

View File

@@ -0,0 +1,29 @@
package it.plague.jeedemo;
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;
@Constraint(validatedBy = ZipCodeValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ZipCode {
String message() default "{it.plague.jeedemo.beanvalidation.ZipCode.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@interface List {
ZipCode[] value();
}
}

View File

@@ -0,0 +1,9 @@
package it.plague.jeedemo;
public class ZipCodeChecker {
public boolean isZipCodeValid(String value) {
// TODO it's not important for this example, here could you do anything do you want
return true;
}
}

View File

@@ -0,0 +1,38 @@
package it.plague.jeedemo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {
/**
* FIXME
* this attribute not work, because <code>@Produce</code>
* not defined
*/
@Inject
@USA
private ZipCodeChecker checker;
private Pattern zipPattern = Pattern.compile("\\d{5}(-\\d{5})?");
@Override
public void initialize(ZipCode zipCode) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
Matcher m = zipPattern.matcher(value);
if (!m.matches()) {
return false;
}
return checker.isZipCodeValid(value);
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/
XMLSchema-instance" xsi:schemeLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/beans_1_0.xsd" version="1.1" bean-discovery-mode="all">
<!-- This is empty on purpose. -->
</beans>

View File

@@ -0,0 +1 @@
it.plague.jeedemo.Email.message=invalid email address

View File

@@ -0,0 +1,23 @@
package it.plague.jeedemo;
import static org.junit.Assert.*;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.Test;
public class AddressIT {
@Test
public void shouldRaiseConstraintViolationCauseInvalidZipCode() {
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Validator validator = vf.getValidator();
Address address = new Address("233 Spring Street", "New York", "NY", "DUMMY", "USA");
Set<ConstraintViolation<Address>> violations = validator.validate(address);
assertEquals(1, violations.size());
vf.close();
}
}

View File

@@ -0,0 +1,48 @@
package it.plague.jeedemo;
import static org.junit.Assert.assertEquals;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class CustomerIT {
private static ValidatorFactory vf;
private static Validator validator;
@BeforeClass
public static void init() {
vf = Validation.buildDefaultValidatorFactory();
validator = vf.getValidator();
}
@AfterClass
public static void close() {
vf.close();
}
@Test
public void shouldRaiseNoConstraintViolation() {
Customer customer = new Customer("John", "Smith", "jsmith@gmail.com");
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(0, violations.size());
}
@Test
public void shouldRaiseConstraintViolationCauseInvalidEmail() {
Customer customer = new Customer("John", "Smith", "DummyEmail");
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(1, violations.size());
assertEquals("invalid email address", violations.iterator().next().getMessage());
assertEquals("DummyEmail", violations.iterator().next().getInvalidValue());
assertEquals("{it.plague.jeedemo.Email.message}",
violations.iterator().next().getMessageTemplate());
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/
XMLSchema-instance" xsi:schemeLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/beans_1_0.xsd" version="1.1" bean-discovery-mode="all">
<!-- This is empty on purpose. -->
</beans>

View File

@@ -10,6 +10,7 @@
<modules>
<module>cdidemo</module>
<module>beanvalidationdemo</module>
</modules>
<dependencyManagement>