Merge branch 'develop'

This commit is contained in:
Fabio Scotto di Santolo
2019-04-05 23:31:04 +02:00
101 changed files with 3134 additions and 0 deletions

92
.gitignore vendored Normal file
View File

@@ -0,0 +1,92 @@
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
*.dat
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
/ejbdemo/testdb/

View File

@@ -0,0 +1,9 @@
<component name="ArtifactManager">
<artifact type="exploded-ejb" name="jsfdemo:ejb exploded">
<output-path>$PROJECT_DIR$/out/artifacts/jsfdemo_ejb_exploded</output-path>
<root id="root">
<element id="javaee-facet-resources" facet="jsfdemo/ejb/EJB" />
<element id="module-output" name="jsfdemo" />
</root>
</artifact>
</component>

23
.idea/artifacts/jsfdemo_war_exploded.xml generated Normal file
View File

@@ -0,0 +1,23 @@
<component name="ArtifactManager">
<artifact type="exploded-war" name="jsfdemo:war exploded">
<output-path>$PROJECT_DIR$/jsfdemo/target/jsfdemo-1.0-SNAPSHOT</output-path>
<properties id="maven-jee-properties">
<options>
<exploded>true</exploded>
<module>jsfdemo</module>
<packaging>war</packaging>
</options>
</properties>
<root id="root">
<element id="directory" name="WEB-INF">
<element id="directory" name="classes">
<element id="module-output" name="jsfdemo" />
</element>
</element>
<element id="directory" name="META-INF">
<element id="file-copy" path="$PROJECT_DIR$/jsfdemo/target/jsfdemo-1.0-SNAPSHOT/META-INF/MANIFEST.MF" />
</element>
<element id="javaee-facet-resources" facet="jsfdemo/web/Web" />
</root>
</artifact>
</component>

5
.idea/codeStyles/codeStyleConfig.xml generated Normal file
View File

@@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="GoogleStyle" />
</state>
</component>

33
.idea/compiler.xml generated Normal file
View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="cdidemo" />
<module name="jpademo" />
<module name="jsfdemo" />
<module name="beanvalidationdemo" />
<module name="jmsdemo" />
<module name="jaxwsdemo-client" />
<module name="xmlandjsondemo" />
<module name="jaxwsdemoservice" />
<module name="jaxwsdemo-service" />
<module name="ejbdemo" />
<module name="jaxrsdemo" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>
<module name="jaxwsdemo-client" target="1.7" />
<module name="maven-archiver (1)" target="1.5" />
<module name="maven-archiver (2)" target="1.5" />
<module name="maven-archiver (3)" target="1.5" />
</bytecodeTargetLevel>
</component>
<component name="RmicSettings">
<option name="IS_EANABLED" value="true" />
</component>
</project>

15
.idea/encodings.xml generated Normal file
View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/beanvalidationdemo" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/cdidemo" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/ejbdemo" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jaxrsdemo" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jaxwsdemo-client" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jaxwsdemo-service" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jmsdemo" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jpademo" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jsfdemo" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/xmlandjsondemo" charset="UTF-8" />
</component>
</project>

37
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$/jaxrsdemo" />
<file type="web" url="file://$PROJECT_DIR$/jaxwsdemo-service" />
<file type="web" url="file://$PROJECT_DIR$/jsfdemo" />
</component>
<component name="GOROOT" path="/usr/lib/go" />
<component name="Kotlin2JsCompilerArguments">
<option name="sourceMapEmbedSources" />
</component>
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectInspectionProfilesVisibleTreeState">
<entry key="Project Default">
<profile-state>
<expanded-state>
<State />
</expanded-state>
<selected-state>
<State>
<id>Angular</id>
</State>
</selected-state>
</profile-state>
</entry>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4" />

View File

@@ -0,0 +1,71 @@
<?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>
<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>
</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,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>

2
cdidemo/cdidemo.iml Normal file
View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4" />

75
cdidemo/pom.xml Normal file
View File

@@ -0,0 +1,75 @@
<?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>cdidemo</artifactId>
<name>cdidemo</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.CdiMain</exec.mainClass>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</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.CdiMain</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,18 @@
package it.plague.jeedemo;
import it.plague.jeedemo.beans.Book;
import it.plague.jeedemo.services.BookService;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
public class CdiMain {
public static void main(String[] args) {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
BookService bookService = container.instance().select(BookService.class).get();
Book book = bookService.createBook("H2G2", 12.5f, "Geeky scifi Book");
System.out.println(book);
weld.shutdown();
}
}

View File

@@ -0,0 +1,14 @@
package it.plague.jeedemo.annotations;
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 EightDigits {
}

View File

@@ -0,0 +1,14 @@
package it.plague.jeedemo.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;
@InterceptorBinding
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Loggable {
}

View File

@@ -0,0 +1,14 @@
package it.plague.jeedemo.annotations;
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 ThirteenDigits {
}

View File

@@ -0,0 +1,58 @@
package it.plague.jeedemo.beans;
public class Book {
private String title;
private Float price;
private String description;
private String number;
public Book(String title, Float price, String description) {
this.title = title;
this.price = price;
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", price=" + price +
", description='" + description + '\'' +
", number='" + number + '\'' +
'}';
}
}

View File

@@ -0,0 +1,22 @@
package it.plague.jeedemo.beans;
import it.plague.jeedemo.annotations.Loggable;
import it.plague.jeedemo.annotations.ThirteenDigits;
import java.util.Random;
import java.util.logging.Logger;
import javax.inject.Inject;
@ThirteenDigits
public class IsbnGenerator implements NumberGenerator {
@Inject
private Logger logger;
@Override
@Loggable
public String generateNumber() {
String isbn = " 13-84356- " + Math.abs(new Random().nextInt());
logger.info("Generated ISBN: " + isbn);
return isbn;
}
}

View File

@@ -0,0 +1,22 @@
package it.plague.jeedemo.beans;
import it.plague.jeedemo.annotations.EightDigits;
import it.plague.jeedemo.annotations.Loggable;
import java.util.Random;
import java.util.logging.Logger;
import javax.inject.Inject;
@EightDigits
public class IssnGenerator implements NumberGenerator {
@Inject
private Logger logger;
@Override
@Loggable
public String generateNumber() {
String issn = " 8- " + Math.abs(new Random().nextInt());
logger.info("Generated ISSN: " + issn);
return issn;
}
}

View File

@@ -0,0 +1,6 @@
package it.plague.jeedemo.beans;
public interface NumberGenerator {
String generateNumber();
}

View File

@@ -0,0 +1,26 @@
package it.plague.jeedemo.interceptors;
import it.plague.jeedemo.annotations.Loggable;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
@Interceptor
@Loggable
public class LoggingInterceptor {
@Inject
private Logger logger;
@AroundInvoke
public Object logMethod(InvocationContext ic) throws Exception {
logger.entering(ic.getTarget().getClass().getName(), ic.getMethod().getName());
try {
return ic.proceed();
} finally {
logger.exiting(ic.getTarget().getClass().getName(), ic.getMethod().getName());
}
}
}

View File

@@ -0,0 +1,13 @@
package it.plague.jeedemo.producers;
import java.util.logging.Logger;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
public class LoggerProducer {
@Produces
public Logger produceLogger(InjectionPoint injectionPoint) {
return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
}
}

View File

@@ -0,0 +1,21 @@
package it.plague.jeedemo.services;
import it.plague.jeedemo.annotations.Loggable;
import it.plague.jeedemo.annotations.ThirteenDigits;
import it.plague.jeedemo.beans.Book;
import it.plague.jeedemo.beans.NumberGenerator;
import javax.inject.Inject;
@Loggable
public class BookService {
@Inject
@ThirteenDigits
private NumberGenerator numberGenerator;
public Book createBook(String title, Float price, String description) {
Book book = new Book(title, price, description);
book.setNumber(numberGenerator.generateNumber());
return book;
}
}

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,22 @@
package it.plague.jeedemo;
import static org.junit.Assert.assertTrue;
import it.plague.jeedemo.beans.Book;
import it.plague.jeedemo.services.BookService;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.Test;
public class BookServiceIT {
@Test
public void shouldCheckNumberIsMOCK() {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
BookService bookService = container.instance().select(BookService.class).get();
Book book = bookService.createBook("H2G2", 12.5f, "Geeky scifi Book");
assertTrue(book.getNumber().startsWith("MOCK"));
weld.shutdown();
}
}

View File

@@ -0,0 +1,25 @@
package it.plague.jeedemo;
import it.plague.jeedemo.annotations.Loggable;
import it.plague.jeedemo.annotations.ThirteenDigits;
import it.plague.jeedemo.beans.NumberGenerator;
import java.util.Random;
import java.util.logging.Logger;
import javax.enterprise.inject.Alternative;
import javax.inject.Inject;
@Alternative
@ThirteenDigits
public class MockGenerator implements NumberGenerator {
@Inject
private Logger logger;
@Override
@Loggable
public String generateNumber() {
String mock = "MOCK- " + Math.abs(new Random().nextInt());
logger.info("Generated Mock: " + mock);
return mock;
}
}

View File

@@ -0,0 +1,11 @@
<?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">
<alternatives>
<class>it.plague.jeedemo.MockGenerator</class>
</alternatives>
<interceptors>
<class>it.plague.jeedemo.interceptors.LoggingInterceptor</class>
</interceptors>
</beans>

15
ejbdemo/ejbdemo.iml Normal file
View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="jpa" name="JPA">
<configuration>
<setting name="validation-enabled" value="true" />
<datasource-mapping>
<factory-entry name="ejbdemoPU" />
</datasource-mapping>
<naming-strategy-map />
<deploymentDescriptor name="persistence.xml" url="file://$MODULE_DIR$/src/main/resources/META-INF/persistence.xml" />
</configuration>
</facet>
</component>
</module>

85
ejbdemo/pom.xml Normal file
View File

@@ -0,0 +1,85 @@
<?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>ejbdemo</artifactId>
<name>ejbdemo</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>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.5.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</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>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,37 @@
package it.plague.jeedemo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@NamedQuery(name = "Book.findAll", query = "select b from Book b")
public class Book implements Serializable {
@Id
@GeneratedValue
private Long id;
@NotNull
@Column(nullable = false)
private String title;
private Float price;
@Size(max = 2000)
@Column(length = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
}

View File

@@ -0,0 +1,39 @@
package it.plague.jeedemo;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;
@Stateless
@LocalBean
public class BookEJB implements BookEJBRemote {
@Inject
private EntityManager em;
@Override
public List<Book> findBooks() {
TypedQuery<Book> query = em.createNamedQuery("Book.findAll", Book.class);
return query.getResultList();
}
@Override
public @NotNull Book createBook(@NotNull Book book) {
em.persist(book);
return book;
}
@Override
public @NotNull Book updateBook(@NotNull Book book) {
return em.merge(book);
}
@Override
public void deleteBook(@NotNull Book book) {
em.remove(em.merge(book));
}
}

View File

@@ -0,0 +1,16 @@
package it.plague.jeedemo;
import java.util.List;
import javax.ejb.Remote;
@Remote
public interface BookEJBRemote {
List<Book> findBooks();
Book createBook(Book book);
void deleteBook(Book book);
Book updateBook(Book book);
}

View File

@@ -0,0 +1,56 @@
package it.plague.jeedemo;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.sql.DataSourceDefinition;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
@Startup
@Singleton
@DataSourceDefinition(
className = "org.apache.derby.jdbc.EmbeddedDataSource",
name = "java:global/jdbc/ejbdemoDS",
user = "APP",
password = "APP",
databaseName = "testdb",
properties = {"connectionAttributes=;create=true"})
public class DatabasePopulator {
@Inject
private BookEJB bookEJB;
private Book h2g2;
private Book lord;
@PostConstruct
private void populateDB() {
h2g2 = Book.builder()
.title("Beginning Java EE 7")
.price(35f)
.description("Great book")
.isbn("1-8763-9125-7")
.nbOfPage(605)
.illustrations(true)
.build();
lord = Book.builder()
.title("The Lord of the Rings")
.price(50.4f)
.description("SciFi")
.isbn("1-84023-742-2")
.nbOfPage(1216)
.illustrations(true)
.build();
bookEJB.createBook(h2g2);
bookEJB.createBook(lord);
}
@PreDestroy
private void clearDB() {
bookEJB.deleteBook(h2g2);
bookEJB.deleteBook(lord);
}
}

View File

@@ -0,0 +1,12 @@
package it.plague.jeedemo;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class DatabaseProducer {
@Produces
@PersistenceContext(unitName = "ejbdemoPU")
private EntityManager em;
}

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="ejbdemoPU" transaction-type="JTA">
<jta-data-source>java:global/jdbc/ejbdemoDS</jta-data-source>
<properties>
<property name="eclipselink.target-database" value="DERBY"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
<property name="eclipselink.logging.level" value="ALL"/>
</properties>
</persistence-unit>
</persistence>

View File

@@ -0,0 +1,56 @@
package it.plague.jeedemo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.ejb.embeddable.EJBContainer;
import javax.naming.Context;
import org.junit.Test;
public class BookEJBIT {
@Test
public void shouldCreateABook() throws Exception {
Map<String, Object> properties = new HashMap<>();
properties.put(EJBContainer.MODULES, new File("target/classes"));
try (EJBContainer ec = EJBContainer.createEJBContainer(properties)) {
Context ctx = ec.getContext();
// Check JNDI dependencies (Datasource and EJBs)
assertNotNull(ctx.lookup("java:global/jdbc/ejbdemoDS"));
assertNotNull(ctx.lookup("java:global/classes/BookEJB!it.plague.jeedemo.BookEJBRemote"));
assertNotNull(ctx.lookup("java:global/classes/BookEJB!it.plague.jeedemo.BookEJB"));
// Looks up the EJB
BookEJB bookEJB = (BookEJB) ctx
.lookup("java:global/classes/BookEJB!it.plague.jeedemo.BookEJB");
// Find all the books and makes sure there are two (inserted by the DBPopulator)
assertEquals(2, bookEJB.findBooks().size());
// Creates an instance of book;
Book book = Book.builder()
.title("H2G2")
.price(12.5f)
.description("Scifi book")
.isbn("1-24561-799-0")
.nbOfPage(354)
.illustrations(false)
.build();
book = bookEJB.createBook(book);
assertNotNull("ID should not be null", book.getId());
// Find all the books and makes sure is an extra one
assertEquals(3, bookEJB.findBooks().size());
// Removes the created book
bookEJB.deleteBook(book);
// Finds all the books and makes sure there is one less
assertEquals(2, bookEJB.findBooks().size());
}
}
}

15
jaxrsdemo/jaxrsdemo.iml Normal file
View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="FacetManager">
<facet type="jpa" name="JPA">
<configuration>
<setting name="validation-enabled" value="true" />
<datasource-mapping>
<factory-entry name="jaxrsoPU" />
</datasource-mapping>
<naming-strategy-map />
<deploymentDescriptor name="persistence.xml" url="file://$MODULE_DIR$/src/main/resources/META-INF/persistence.xml" />
</configuration>
</facet>
</component>
</module>

85
jaxrsdemo/pom.xml Normal file
View File

@@ -0,0 +1,85 @@
<?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>jaxrsdemo</artifactId>
<packaging>war</packaging>
<name>jaxrsdemo</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>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.5.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</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>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,23 @@
package it.plague.jeedemo;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("rs")
public class ApplicationConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new HashSet<>();
addRestResources(resources);
return resources;
}
private void addRestResources(Set<Class<?>> resources) {
resources.add(it.plague.jeedemo.BookRestService.class);
resources.add(org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.class);
}
}

View File

@@ -0,0 +1,43 @@
package it.plague.jeedemo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@XmlRootElement
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@NamedQuery(name = Book.FIND_ALL, query = "select b from Book b")
public class Book {
public static final String FIND_ALL = "FIND_ALL";
@Id
@GeneratedValue
private String id;
@Column(nullable = false)
private String title;
private Float price;
@Column(length = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
}

View File

@@ -0,0 +1,75 @@
package it.plague.jeedemo;
import java.net.URI;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
@Path("/book")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Stateless
public class BookRestService {
@PersistenceContext(name = "jaxrsPU")
private EntityManager em;
@Context
private UriInfo uriInfo;
@GET
public Response getBooks() {
TypedQuery<Book> query = em.createNamedQuery(Book.FIND_ALL, Book.class);
Books books = new Books(query.getResultList());
return Response.ok(books).build();
}
@GET
@Path("{id}")
public Response getBook(@PathParam("id") String id) {
Book book = em.find(Book.class, id);
if (book == null) {
throw new NotFoundException();
}
return Response.ok(book)
.build();
}
@POST
public Response createBook(Book book) {
if (book == null) {
throw new BadRequestException();
}
em.persist(book);
URI location = uriInfo.getAbsolutePathBuilder()
.path(book.getId())
.build();
return Response.created(location).build();
}
@DELETE
@Path("{id}")
public Response deleteBook(@PathParam("id") String id) {
Book book = em.find(Book.class, id);
if (book == null) {
throw new NotFoundException();
}
em.remove(book);
return Response.noContent().build();
}
}

View File

@@ -0,0 +1,29 @@
package it.plague.jeedemo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@XmlRootElement
@XmlSeeAlso(Book.class)
public class Books extends ArrayList<Book> {
public Books(Collection<? extends Book> c) {
super(c);
}
@XmlElement(name = "book")
public List<Book> getBooks() {
return this;
}
public void setBooks(List<Book> books) {
this.addAll(books);
}
}

View File

@@ -0,0 +1,59 @@
package it.plague.jeedemo;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.sql.DataSourceDefinition;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Startup
@Singleton
@DataSourceDefinition(
className = "org.apache.derby.jdbc.EmbeddedDataSource",
name = "java:global/jdbc/jaxrsoPU",
user = "APP",
password = "APP",
databaseName = "testdb",
properties = {"connectionAttributes=;create=true"})
public class DatabasePopulator {
@PersistenceContext(name = "jaxrsPU")
private EntityManager em;
private Book h2g2;
private Book lord;
@PostConstruct
private void populateDB() {
h2g2 = Book.builder()
.title("Beginning Java EE 7")
.price(35f)
.description("Great book")
.isbn("1-8763-9125-7")
.nbOfPage(605)
.illustrations(true)
.build();
lord = Book.builder()
.title("The Lord of the Rings")
.price(50.4f)
.description("SciFi")
.isbn("1-84023-742-2")
.nbOfPage(1216)
.illustrations(true)
.build();
em.persist(h2g2);
em.persist(lord);
}
@PreDestroy
private void clearDB() {
em.remove(h2g2);
em.remove(lord);
}
}

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="jaxrsoPU" transaction-type="JTA">
<jta-data-source>java:global/jdbc/jaxrsoPU</jta-data-source>
<properties>
<property name="eclipselink.target-database" value="DERBY"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
<property name="eclipselink.logging.level" value="ALL"/>
</properties>
</persistence-unit>
</persistence>

View File

@@ -0,0 +1,84 @@
package it.plague.jeedemo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.net.URI;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import org.junit.Test;
public class BookRestServiceIT {
private static URI uri = UriBuilder.fromUri("http://localhost/jaxrsdemo-1.0-SNAPSHOT/rs/book")
.port(8080).build();
private static Client client = ClientBuilder.newClient();
@Test
public void shouldNotCreateANullBook() {
// POSTs a null book
Response response = client.target(uri)
.request()
.post(Entity.entity(null, MediaType.APPLICATION_XML));
assertThat(response.getStatus(), is(Status.BAD_REQUEST.getStatusCode()));
}
@Test
public void shouldNOtFindTheBookID() {
// GETs a book with an unknown ID
Response response = client.target(uri)
.path("unknownID")
.request()
.get();
assertThat(response.getStatus(), is(Status.NOT_FOUND.getStatusCode()));
}
@Test
public void shouldCreateAndDeleteABook() {
Book book = Book.builder()
.title("H2G2")
.price(12.5f)
.description("Science book")
.isbn("1-84023-742-2")
.nbOfPage(354)
.illustrations(false)
.build();
// POSTs a book
Response response = client.target(uri)
.request()
.post(Entity.entity(book, MediaType.APPLICATION_XML));
assertThat(response.getStatus(), is(Status.CREATED.getStatusCode()));
URI bookUri = response.getLocation();
// With the location, GETs the book
response = client.target(bookUri)
.request()
.get();
book = response.readEntity(Book.class);
assertThat(response.getStatus(), is(Status.OK.getStatusCode()));
assertEquals("H2G2", book.getTitle());
// Gets the book id and DELETEs it
String bookId = bookUri.toString().split("/")[6];
response = client.target(uri)
.path(bookId)
.request()
.delete();
assertThat(response.getStatus(), is(Status.NO_CONTENT.getStatusCode()));
// GETs the book and checks it has been deleted
response = client.target(bookUri)
.request()
.get();
assertThat(response.getStatus(), is(Status.NOT_FOUND.getStatusCode()));
}
}

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<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$/target/generated-sources/wsimport" isTestSource="false" generated="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.glassfish.main.extras:glassfish-embedded-all:4.1.2" level="project" />
<orderEntry type="module-library">
<library name="Maven: com.sun:tools-jar:1">
<CLASSES>
<root url="jar://C:/Program Files/Java/jdk1.8.0_201/lib/tools.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<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>

96
jaxwsdemo-client/pom.xml Normal file
View File

@@ -0,0 +1,96 @@
<?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>jaxwsdemo-client</artifactId>
<name>jaxwsdemo-client</name>
<packaging>jar</packaging>
<parent>
<artifactId>jeedemo</artifactId>
<groupId>it.plague.jeedemo</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${project.build.directory}/generated-sources/wsimport/</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<mainClass>it.plague.jeedemo.WebServiceConsumer</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.jvnet.jax-ws-commons</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<wsdlUrls>
<wsdlUrl>
http://localhost:8080/jaxwsdemo-service-1.0-SNAPSHOT/CardValidatorService?wsdl
</wsdlUrl>
</wsdlUrls>
<keep>true</keep>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,20 @@
package it.plague.jeedemo;
import javax.xml.ws.WebServiceRef;
public class WebServiceConsumer {
@WebServiceRef
private static CardValidatorService cardValidatorService;
public static void main(String[] args) {
CreditCard creditCard = new CreditCard();
creditCard.setNumber("12341234");
creditCard.setExpiryDate("10/12");
creditCard.setType("VISA");
creditCard.setControlNumber(1234);
Validator cardValidator = cardValidatorService.getCardValidatorPort();
System.out.println(cardValidator.validate(creditCard));
}
}

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />

72
jaxwsdemo-service/pom.xml Normal file
View File

@@ -0,0 +1,72 @@
<?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>jaxwsdemo-service</artifactId>
<name>jaxwsdemo-service</name>
<packaging>war</packaging>
<parent>
<artifactId>jeedemo</artifactId>
<groupId>it.plague.jeedemo</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</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>3.8.0</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</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>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,13 @@
package it.plague.jeedemo;
import javax.jws.WebService;
@WebService(endpointInterface = "it.plague.jeedemo.Validator")
public class CardValidator implements Validator {
@Override
public boolean validate(CreditCard creditCard) {
Character lastDigit = creditCard.getNumber().charAt(creditCard.getNumber().length() - 1);
return Integer.parseInt(lastDigit.toString()) % 2 == 0;
}
}

View File

@@ -0,0 +1,30 @@
package it.plague.jeedemo;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class CreditCard {
@XmlAttribute(required = true)
private String number;
@XmlAttribute(name = "expiry_date", required = true)
private String expiryDate;
@XmlAttribute(name = "control_number", required = true)
private Integer controlNumber;
@XmlAttribute(required = true)
private String type;
}

View File

@@ -0,0 +1,9 @@
package it.plague.jeedemo;
import javax.jws.WebService;
@WebService
public interface Validator {
boolean validate(CreditCard creditCard);
}

View File

@@ -0,0 +1,62 @@
package it.plague.jeedemo;
import static org.junit.Assert.*;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Endpoint;
import javax.xml.ws.Service;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class CardValidatorIT {
private static Endpoint endpoint;
private static Validator cardValidator;
@BeforeClass
public static void setUp() throws MalformedURLException {
final String url = "http://localhost:8081/cardValidator";
// Publishes the SOAP Web Service
endpoint = Endpoint.publish(url, new CardValidator());
// Needed properties to access the web service
URL wsdlDocumentLocation = new URL(url + "?wsdl");
String namespaceURI = "http://jeedemo.plague.it/";
String servicePart = "CardValidatorService";
String portName = "CardValidatorPort";
QName serviceQn = new QName(namespaceURI, servicePart);
QName portQn = new QName(namespaceURI, portName);
// Creates a service instance
Service service = Service.create(wsdlDocumentLocation, serviceQn);
cardValidator = service.getPort(portQn, Validator.class);
}
@AfterClass
public static void tearDown() {
if (endpoint != null) {
endpoint.stop();
}
}
@Test
public void shouldBePublished() {
assertTrue(endpoint.isPublished());
assertEquals("http://schemas.xmlsoap.org/wsdl/soap/http", endpoint.getBinding().getBindingID());
}
@Test
public void shouldCheckCreditCardValidity() {
CreditCard creditCard = new CreditCard("12341234", "10/10", 1234, "VISA");
assertTrue("Credit card should be valid", cardValidator.validate(creditCard));
creditCard.setNumber("12341233");
assertFalse("Credit card should not be valid", cardValidator.validate(creditCard));
}
}

View File

@@ -0,0 +1,21 @@
package it.plague.jeedemo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CardValidatorTest {
@Test
public void shouldCheckCreditCardValidity() {
CardValidator cardValidator = new CardValidator();
CreditCard creditCard = new CreditCard("12341234", "10/10", 1234, "VISA");
assertTrue("Credit card should be valid", cardValidator.validate(creditCard));
creditCard.setNumber("12341233");
assertFalse("Credit card should not be valid", cardValidator.validate(creditCard));
}
}

2
jeedemo.iml Normal file
View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4" />

66
jmsdemo/pom.xml Normal file
View File

@@ -0,0 +1,66 @@
<?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>jmsdemo</artifactId>
<name>jmsdemo</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>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</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>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,25 @@
package it.plague.jeedemo;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
@MessageDriven(mappedName = "jms/javaee7/Topic",
activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMod", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "messageSelector", propertyValue = "orderAmount > 1000")
})
public class ExpensiveOrderMDB implements MessageListener {
@Override
public void onMessage(Message message) {
try {
OrderDTO order = message.getBody(OrderDTO.class);
System.out.println("Expensive order received: " + order);
} catch (JMSException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,29 @@
package it.plague.jeedemo;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class OrderConsumer {
public static void main(String[] args) throws NamingException {
// Get the JNDI context
Context jndiContext = new InitialContext();
// Looks up the administered objects
ConnectionFactory connectionFactory =
(ConnectionFactory) jndiContext.lookup("jms/javaee7/ConnectionFactory");
Destination destination =
(Destination) jndiContext.lookup("jms/javaee7/Topic");
try (JMSContext context = connectionFactory.createContext()) {
while (true) {
OrderDTO order = context.createConsumer(destination).receiveBody(OrderDTO.class);
System.out.println("Order received: " + order);
}
}
}
}

View File

@@ -0,0 +1,18 @@
package it.plague.jeedemo;
import java.io.Serializable;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class OrderDTO implements Serializable {
private Long orderId;
private Date creationDate;
private String customerName;
private Float totalAmount;
}

View File

@@ -0,0 +1,32 @@
package it.plague.jeedemo;
import java.util.Date;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class OrderProducer {
public static void main(String[] args) throws NamingException {
// Creates an orderDto with a total amount parameter
Float totalAmount = Float.valueOf(args[0]);
OrderDTO order = new OrderDTO(12342L, new Date(), "Betty Moreu", totalAmount);
// Get the JNDI context
Context jndiContext = new InitialContext();
// Looks up the administered objects
ConnectionFactory connectionFactory =
(ConnectionFactory) jndiContext.lookup("jms/javaee7/ConnectionFactory");
Destination destination =
(Destination) jndiContext.lookup("jms/javaee7/Topic");
try (JMSContext context = connectionFactory.createContext()) {
// Sends an object message to the topic
context.createProducer().setProperty("orderAmount", totalAmount).send(destination, order);
}
}
}

16
jpademo/jpademo.iml Normal file
View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="jpa" name="JPA">
<configuration>
<setting name="validation-enabled" value="true" />
<datasource-mapping>
<factory-entry name="jpademoTestUnit" />
<factory-entry name="jpademoUnit" />
</datasource-mapping>
<naming-strategy-map />
<deploymentDescriptor name="persistence.xml" url="file://$MODULE_DIR$/src/main/resources/META-INF/persistence.xml" />
</configuration>
</facet>
</component>
</module>

82
jpademo/pom.xml Normal file
View File

@@ -0,0 +1,82 @@
<?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>jpademo</artifactId>
<name>jpademo</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>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</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>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,37 @@
package it.plague.jeedemo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
@NamedQueries({
@NamedQuery(name = "Book.findAll", query = "select b from Book b"),
@NamedQuery(name = "Book.findOneH2G2", query = "select b from Book b where b.title = 'H2G2'")
})
public @Data
class Book {
@Id
@GeneratedValue
private Long id;
@NotNull
private String title;
private Float price;
@Size(min = 10, max = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
}

View File

@@ -0,0 +1,3 @@
insert into book(id, title, description, illustrations, isbn, nbofpage, price) values (1000, 'Beginning Java EE 6', 'Best Java EE book ever', 1, '1234-5678', 450, 49)
insert into book(id, title, description, illustrations, isbn, nbofpage, price) values (1001, 'Beginning Java EE 7', 'No, this is the best', 1, '5678-9012', 550, 53)
insert into book(id, title, description, illustrations, isbn, nbofpage, price) values (1010, 'The Lord of the Rings', 'One ring to rule them all', 0, '1234-5678', 222, 23)

View File

@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="jpademoUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>it.plague.jeedemo.Book</class>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.create-source" value="metadata"/>
<property name="javax.persistence.schema-generation.drop-source" value="metadata"/>
<property name="javax.persistence.schema-generation.create-database-schemas" value="true"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/jpademo;create=true"/>
<property name="javax.persistence.jdbc.user" value="APP"/>
<property name="javax.persistence.jdbc.password" value="APP"/>
<property name="javax.persistence.sql-load-script-source" value="META-INF/insert.sql"/>
<property name="eclipselink.logging.level" value="ALL"/>
</properties>
</persistence-unit>
<!-- TEST PERSISTENCE UNIT -->
<persistence-unit name="jpademoTestUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>it.plague.jeedemo.Book</class>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.create-source" value="metadata"/>
<property name="javax.persistence.schema-generation.drop-source" value="metadata"/>
<property name="javax.persistence.schema-generation.create-database-schemas" value="true"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:derby:memory:jpademo;create=true"/>
<property name="javax.persistence.sql-load-script-source" value="META-INF/insert.sql"/>
<property name="eclipselink.logging.level" value="ALL"/>
</properties>
</persistence-unit>
</persistence>

View File

@@ -0,0 +1,70 @@
package it.plague.jeedemo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.validation.ConstraintViolationException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class BookIT {
private EntityManager em;
@Before
public void initEntityManager() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpademoTestUnit");
em = emf.createEntityManager();
}
@After
public void closeEntityManager() {
if (em != null) {
em.close();
}
}
@Test
public void shouldCreateJavaEE7Book() {
Book book = em.find(Book.class, 1001L);
assertEquals("Beginning Java EE 7", book.getTitle());
}
@Test
public void shouldCreateH2G2Book() {
Book book = Book.builder()
.title("H2G2")
.description("The Hitchhiker's Guide to the Galaxy")
.price(12.5f)
.isbn("1-84023-742-2")
.nbOfPage(354)
.illustrations(false)
.build();
em.getTransaction().begin();
em.persist(book);
em.getTransaction().commit();
assertNotNull("ID should not be null", book.getId());
book = em.createNamedQuery("Book.findOneH2G2", Book.class).getSingleResult();
assertEquals("The Hitchhiker's Guide to the Galaxy", book.getDescription());
}
@Test(expected = ConstraintViolationException.class)
public void shouldRaiseConstraintViolationCauseNullTitle() {
Book book = Book.builder()
.title(null)
.description("Null title, should fail")
.price(12.5f)
.isbn("1-84023-742-2")
.nbOfPage(354)
.illustrations(false)
.build();
em.persist(book);
}
}

35
jsfdemo/jsfdemo.iml Normal file
View File

@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="FacetManager">
<facet type="jpa" name="JPA">
<configuration>
<setting name="validation-enabled" value="true" />
<datasource-mapping />
<naming-strategy-map />
<deploymentDescriptor name="persistence.xml" url="file://$MODULE_DIR$/src/main/resources/META-INF/persistence.xml" />
</configuration>
</facet>
<facet type="ejb" name="EJB">
<configuration>
<ejbRoots>
<root url="file://$MODULE_DIR$/src/main/java" />
</ejbRoots>
</configuration>
</facet>
<facet type="web" name="Web">
<configuration>
<descriptors>
<deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/src/main/webapp/WEB-INF/web.xml" />
</descriptors>
<webroots>
<root url="file://$MODULE_DIR$/src/main/webapp" relative="/" />
</webroots>
<sourceRoots>
<root url="file://$MODULE_DIR$/src/main/java" />
<root url="file://$MODULE_DIR$/src/main/resources" />
<root url="file://$MODULE_DIR$/target/generated-sources/annotations" />
</sourceRoots>
</configuration>
</facet>
</component>
</module>

61
jsfdemo/pom.xml Normal file
View File

@@ -0,0 +1,61 @@
<?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>jsfdemo</artifactId>
<packaging>war</packaging>
<name>jsfdemo</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>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,47 @@
package it.plague.jeedemo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@XmlRootElement
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@NamedQuery(name = Book.FIND_ALL, query = "select b from Book b")
public class Book {
public static final String FIND_ALL = "FIND_ALL";
@Id
@GeneratedValue
private Long id;
@NotNull
@Size(min = 4, max = 50)
@Column(nullable = false)
private String title;
private Float price;
@Column(length = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
}

View File

@@ -0,0 +1,35 @@
package it.plague.jeedemo;
import java.util.List;
import javax.annotation.sql.DataSourceDefinition;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
@Named
@Stateless
@DataSourceDefinition(
name = "java:global/jdbc/lab11DS",
className = "org.apache.derby.jdbc.EmbeddedDriver",
url = "jdbc:derby:memory:lab11DB;create=true;user=app;password=app"
)
public class BookEJB {
@Inject
private EntityManager em;
public Book createBook(Book book) {
em.persist(book);
return book;
}
public List<Book> findAllBooks() {
return em.createNamedQuery(Book.FIND_ALL, Book.class).getResultList();
}
public Book findBookById(Long id) {
return em.find(Book.class, id);
}
}

View File

@@ -0,0 +1,36 @@
package it.plague.jeedemo;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Named
@RequestScoped
@NoArgsConstructor
public class BookView {
@Inject
private BookEJB bookEJB;
@Getter
@Setter
private Book book = new Book();
public void doFindBookById() {
book = bookEJB.findBookById(book.getId());
}
public String doCreateBook() {
bookEJB.createBook(book);
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO, "Book created",
"The book " + book.getTitle() + " has been created with id = " + book.getId()));
return "newBook.xhtml";
}
}

View File

@@ -0,0 +1,12 @@
package it.plague.jeedemo;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class DatabaseProducer {
@Produces
@PersistenceContext(unitName = "jsfdemoPU")
private EntityManager em;
}

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="jsfdemoPU" transaction-type="JTA">
<jta-data-source>java:global/jdbc/lab11DS</jta-data-source>
<properties>
<property name="eclipselink.target-database" value="DERBY"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
<property name="eclipselink.logging.level" value="ALL"/>
</properties>
</persistence-unit>
</persistence>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>

View File

@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
</faces-config>

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title><ui:insert name="title">Defautl title</ui:insert></title>
</h:head>
<h:body>
<h:link value="Create a book" outcome="newBook.xhtml"/>
<h1><ui:insert name="title">Default title</ui:insert></h1>
<hr/>
<h:messages id="errors" infoStyle="color: blue" warnStyle="color: orange"
errorStyle="color: red"/>
<ui:insert name="content">Default content</ui:insert>
<hr/>
<h:outputText value="APress - Beginning Java EE 7" style="font-style: italic"/>
</h:body>
</html>

View File

@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<ui:composition template="layout.xhtml">
<ui:define name="title">Create new book</ui:define>
<ui:define name="content">
<h:form id="bookForm">
<h:panelGrid columns="2">
<h:outputLabel value="Title: "/>
<h:inputText value="#{bookView.book.title}"/>
<h:outputLabel value="Price: "/>
<h:inputText value="#{bookView.book.price}"/>
<h:outputLabel value="Description: "/>
<h:inputTextarea value="#{bookView.book.description}" cols="16" rows="3"/>
<h:outputLabel value="Number of pages: "/>
<h:inputText value="#{bookView.book.nbOfPage}"/>
<h:outputLabel value="Illustrations: "/>
<h:selectBooleanCheckbox value="#{bookView.book.illustrations}"/>
</h:panelGrid>
<h:commandButton value="Create a book" action="#{bookView.doCreateBook}">
<f:ajax execute="@form" render=":booklist :errors"/>
</h:commandButton>
</h:form>
<hr/>
<h1>List of books</h1>
<h:dataTable id="booklist" value="#{bookEJB.findAllBooks()}" var="bk" border="1">
<h:column>
<f:facet name="header">
<h:outputText value="Title"/>
</f:facet>
<h:link outcome="viewBook.xhtml?id=#{bk.id}" value="#{bk.title}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Price"/>
</f:facet>
<h:outputText value="#{bk.price}"/>
</h:column>
</h:dataTable>
</ui:define>
</ui:composition>
</html>

View File

@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<ui:composition template="layout.xhtml">
<f:metadata>
<f:viewParam name="id" value="#{bookView.book.id}"/>
<f:viewAction action="#{bookView.doFindBookById}"/>
</f:metadata>
<ui:define name="title">View a book</ui:define>
<ui:define name="content">
<h:panelGrid columns="2">
<h:outputLabel value="Title: "/>
<h:outputText value="#{bookView.book.title}"/>
<h:outputLabel value="Price: "/>
<h:outputText value="#{bookView.book.price}"/>
<h:outputLabel value="Description: "/>
<h:outputText value="#{bookView.book.description}"/>
<h:outputLabel value="Number of pages: "/>
<h:outputText value="#{bookView.book.nbOfPage}"/>
<h:outputLabel value="Illustrations: "/>
<h:selectBooleanCheckbox value="#{bookView.book.illustrations}"/>
</h:panelGrid>
</ui:define>
</ui:composition>
</html>

View File

@@ -0,0 +1,20 @@
package it.plague.jeedemo;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Unit test for simple App.
*/
public class AppTest
{
/**
* Rigorous Test :-)
*/
@Test
public void shouldAnswerWithTrue()
{
assertTrue( true );
}
}

76
pom.xml Normal file
View File

@@ -0,0 +1,76 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>it.plague.jeedemo</groupId>
<artifactId>jeedemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>jeedemo</name>
<modules>
<module>cdidemo</module>
<module>beanvalidationdemo</module>
<module>jpademo</module>
<module>ejbdemo</module>
<module>xmlandjsondemo</module>
<module>jmsdemo</module>
<module>jaxwsdemo-service</module>
<module>jaxrsdemo</module>
<module>jsfdemo</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b09</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>2.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.9.1.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>4.1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.9.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>

71
xmlandjsondemo/pom.xml Normal file
View File

@@ -0,0 +1,71 @@
<?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>xmlandjsondemo</artifactId>
<name>xmlandjsondemo</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>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</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>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,26 @@
package it.plague.jeedemo;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class CreditCard {
@XmlAttribute
private String number;
@XmlElement(name = "expiry_date")
private String expiryDate;
@XmlElement(name = "control_number")
private Integer controlNumber;
private String type;
}

View File

@@ -0,0 +1,37 @@
package it.plague.jeedemo;
import static org.junit.Assert.*;
import java.io.StringWriter;
import javax.json.Json;
import javax.json.stream.JsonGenerator;
import org.junit.Test;
public class CreditCardJSonTest {
public static final String creditCardJSon =
"{\"creditCard\":" +
"{\"number\":\"12345678\"," +
"\"expiryDate\":\"10/14\"," +
"\"controlNumber\":566," +
"\"type\":\"Visa\"}" +
"}";
@Test
public void shouldGenerateACreditCard() {
CreditCard creditCard = new CreditCard("12345678", "10/14", 566, "Visa");
StringWriter writer = new StringWriter();
JsonGenerator generator = Json.createGenerator(writer);
generator.writeStartObject()
.writeStartObject("creditCard")
.write("number", creditCard.getNumber())
.write("expiryDate", creditCard.getExpiryDate())
.write("controlNumber", creditCard.getControlNumber())
.write("type", creditCard.getType())
.writeEnd()
.writeEnd()
.close();
assertEquals(creditCardJSon, writer.toString().trim());
}
}

View File

@@ -0,0 +1,46 @@
package it.plague.jeedemo;
import static org.junit.Assert.assertEquals;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.junit.Test;
public class CreditCardXmlTest {
public static final String creditCardXml =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
"<creditCard number=\"12345678\">" +
"<expiry_date>10/14</expiry_date>" +
"<control_number>566</control_number>" +
"<type>Visa</type>" +
"</creditCard>";
@Test
public void shouldMarshallACreditCard() throws JAXBException {
CreditCard creditCard = new CreditCard("12345678", "10/14", 566, "Visa");
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(CreditCard.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(creditCard, writer);
System.out.println(writer);
assertEquals(creditCardXml, writer.toString().trim());
}
@Test
public void shouldUnmarshallACreditCard() throws JAXBException {
StringReader reader = new StringReader(creditCardXml);
JAXBContext context = JAXBContext.newInstance(CreditCard.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
CreditCard creditCard = (CreditCard) unmarshaller.unmarshal(reader);
assertEquals("12345678", creditCard.getNumber());
assertEquals("10/14", creditCard.getExpiryDate());
assertEquals((Object) 566, creditCard.getControlNumber());
assertEquals("Visa", creditCard.getType());
}
}

Some files were not shown because too many files have changed in this diff Show More