Merge remote-tracking branch 'upstream/master'

This commit is contained in:
tschiman 2017-01-12 22:14:15 -07:00
commit 299fed28f5
82 changed files with 2404 additions and 640 deletions

View File

@ -1,7 +1,6 @@
<?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">
<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">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>

View File

@ -1,154 +1,155 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>apache-fop</artifactId>
<version>0.1-SNAPSHOT</version>
<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>
<groupId>com.baeldung</groupId>
<artifactId>apache-fop</artifactId>
<version>0.1-SNAPSHOT</version>
<name>apache-fop</name>
<name>apache-fop</name>
<dependencies>
<dependencies>
<!-- logging -->
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<!-- test scoped -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<!-- new dependencies -->
<!-- new dependencies -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>fop</artifactId>
<version>${fop.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.avalon.framework</groupId>
<artifactId>avalon-framework-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.avalon.framework</groupId>
<artifactId>avalon-framework-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>fop</artifactId>
<version>${fop.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.avalon.framework</groupId>
<artifactId>avalon-framework-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.avalon.framework</groupId>
<artifactId>avalon-framework-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>avalon-framework</groupId>
<artifactId>avalon-framework-api</artifactId>
<version>${avalon-framework.version}</version>
</dependency>
<dependency>
<groupId>avalon-framework</groupId>
<artifactId>avalon-framework-impl</artifactId>
<version>${avalon-framework.version}</version>
</dependency>
<dependency>
<groupId>avalon-framework</groupId>
<artifactId>avalon-framework-api</artifactId>
<version>${avalon-framework.version}</version>
</dependency>
<dependency>
<groupId>avalon-framework</groupId>
<artifactId>avalon-framework-impl</artifactId>
<version>${avalon-framework.version}</version>
</dependency>
<dependency>
<groupId>org.dbdoclet</groupId>
<artifactId>dbdoclet</artifactId>
<version>${dbdoclet.version}</version>
</dependency>
<dependency>
<groupId>org.dbdoclet</groupId>
<artifactId>dbdoclet</artifactId>
<version>${dbdoclet.version}</version>
</dependency>
<dependency>
<groupId>org.dbdoclet</groupId>
<artifactId>herold</artifactId>
<version>6.1.0</version>
<scope>system</scope>
<systemPath>${basedir}/src/test/resources/jars/herold.jar</systemPath>
</dependency>
<dependency>
<groupId>org.dbdoclet</groupId>
<artifactId>herold</artifactId>
<version>6.1.0</version>
<scope>system</scope>
<systemPath>${basedir}/src/test/resources/jars/herold.jar</systemPath>
</dependency>
<dependency>
<groupId>net.sf.jtidy</groupId>
<artifactId>jtidy</artifactId>
<version>${jtidy.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jtidy</groupId>
<artifactId>jtidy</artifactId>
<version>${jtidy.version}</version>
</dependency>
</dependencies>
</dependencies>
<build>
<finalName>apache-fop</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<build>
<finalName>apache-fop</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</excludes>
</configuration>
</plugin>
</plugins>
</plugins>
</build>
</build>
<profiles>
<profile>
@ -186,24 +187,24 @@
</profile>
</profiles>
<properties>
<fop.version>1.1</fop.version>
<avalon-framework.version>4.3</avalon-framework.version>
<dbdoclet.version>8.0.2</dbdoclet.version>
<jtidy.version>r938</jtidy.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<properties>
<fop.version>1.1</fop.version>
<avalon-framework.version>4.3</avalon-framework.version>
<dbdoclet.version>8.0.2</dbdoclet.version>
<jtidy.version>r938</jtidy.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</properties>
</project>

View File

@ -46,34 +46,34 @@
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.4.RELEASE</version>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.4.RELEASE</version>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.4.RELEASE</version>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.4</version>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.4.RELEASE</version>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
@ -111,18 +111,8 @@
<Xlint>ignore</Xlint>
<encoding>${project.build.sourceEncoding}</encoding>
<!-- Post-compile weaving -->
<!--
<weaveDependencies>
<weaveDependency>
<groupId>org.agroup</groupId>
<artifactId>to-weave</artifactId>
</weaveDependency>
<weaveDependency>
<groupId>org.anothergroup</groupId>
<artifactId>gen</artifactId>
</weaveDependency>
</weaveDependencies>
-->
<!-- <weaveDependencies> <weaveDependency> <groupId>org.agroup</groupId> <artifactId>to-weave</artifactId> </weaveDependency>
<weaveDependency> <groupId>org.anothergroup</groupId> <artifactId>gen</artifactId> </weaveDependency> </weaveDependencies> -->
</configuration>
<executions>
<execution>
@ -132,20 +122,11 @@
</goals>
</execution>
</executions>
</plugin>
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.10</version>
<configuration>
<argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
<useSystemClassLoader>true</useSystemClassLoader>
<forkMode>always</forkMode>
</configuration>
</plugin>
-->
<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.10</version>
<configuration> <argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
<useSystemClassLoader>true</useSystemClassLoader> <forkMode>always</forkMode> </configuration> </plugin> -->
</plugins>
</build>

View File

@ -1,91 +1,88 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>core-java9</artifactId>
<version>0.2-SNAPSHOT</version>
<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>
<groupId>com.baeldung</groupId>
<artifactId>core-java9</artifactId>
<version>0.2-SNAPSHOT</version>
<name>core-java9</name>
<name>core-java9</name>
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<build>
<finalName>core-java-9</finalName>
</dependencies>
<plugins>
<build>
<finalName>core-java-9</finalName>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.9</source>
<target>1.9</target>
<verbose>true</verbose>
</configuration>
</plugin>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.9</source>
<target>1.9</target>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</build>
</plugins>
<properties>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
</build>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<properties>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
</properties>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
</properties>
</project>

View File

@ -1,91 +1,91 @@
<?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>
<groupId>com.baeldung</groupId>
<artifactId>couchbase-sdk</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>couchbase-sdk</name>
<description>Couchbase SDK Tutorials</description>
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>
<groupId>com.baeldung</groupId>
<artifactId>couchbase-sdk</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>couchbase-sdk</name>
<description>Couchbase SDK Tutorials</description>
<dependencies>
<!-- Couchbase SDK -->
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId>
<version>${couchbase.client.version}</version>
</dependency>
<dependencies>
<!-- Couchbase SDK -->
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId>
<version>${couchbase.client.version}</version>
</dependency>
<!-- Spring Context for Dependency Injection -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring Context for Dependency Injection -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- Test-Scoped Dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Test-Scoped Dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
@ -96,20 +96,20 @@
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</plugins>
</build>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<couchbase.client.version>2.3.6</couchbase.client.version>
<spring-framework.version>4.3.4.RELEASE</spring-framework.version>
<logback.version>1.1.7</logback.version>
<org.slf4j.version>1.7.21</org.slf4j.version>
<junit.version>4.12</junit.version>
<commons-lang3.version>3.5</commons-lang3.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<couchbase.client.version>2.3.6</couchbase.client.version>
<spring-framework.version>4.3.4.RELEASE</spring-framework.version>
<logback.version>1.1.7</logback.version>
<org.slf4j.version>1.7.21</org.slf4j.version>
<junit.version>4.12</junit.version>
<commons-lang3.version>3.5</commons-lang3.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</properties>
</project>

View File

@ -1,6 +1,6 @@
<?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/maven-v4_0_0.xsd">
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>com.baeldung</groupId>
<artifactId>deltaspike</artifactId>
@ -19,11 +19,10 @@
</licenses>
<properties>
<!-- Explicitly declaring the source encoding eliminates the following
message: -->
<!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered
resources, i.e. build is platform dependent! -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Explicitly declaring the source encoding eliminates the following message: -->
<!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! -->
<project.build.sourceEncoding>
UTF-8</project.build.sourceEncoding>
<slf4j.version>1.7.21</slf4j.version>
<querydsl.version>3.7.4</querydsl.version>
@ -32,8 +31,7 @@
<!-- JBoss dependency versions -->
<wildfly.maven.plugin.version>1.0.2.Final</wildfly.maven.plugin.version>
<!-- Define the version of the JBoss BOMs we want to import to specify
tested stacks. -->
<!-- Define the version of the JBoss BOMs we want to import to specify tested stacks. -->
<jboss.bom.version>8.2.2.Final</jboss.bom.version>
<!-- other plugin versions -->
@ -50,14 +48,11 @@
<dependencyManagement>
<dependencies>
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill
of Materials (BOM). A BOM specifies the versions of a "stack" (or a collection)
of artifacts. We use this here so that we always get the correct versions
of artifacts. Here we use the jboss-javaee-7.0-with-tools stack (you can
read this as the JBoss stack of the Java EE 7 APIs, with some extras tools
for your project, such as Arquillian for testing) and the jboss-javaee-7.0-with-hibernate
stack you can read this as the JBoss stack of the Java EE 7 APIs, with extras
from the Hibernate family of projects) -->
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill of Materials (BOM). A BOM specifies the versions of a "stack"
(or a collection) of artifacts. We use this here so that we always get the correct versions of artifacts. Here we use the jboss-javaee-7.0-with-tools
stack (you can read this as the JBoss stack of the Java EE 7 APIs, with some extras tools for your project, such as Arquillian for testing) and
the jboss-javaee-7.0-with-hibernate stack you can read this as the JBoss stack of the Java EE 7 APIs, with extras from the Hibernate family of
projects) -->
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
@ -77,43 +72,37 @@
<dependencies>
<!-- First declare the APIs we depend on and need for compilation. All
of them are provided by JBoss WildFly -->
<!-- First declare the APIs we depend on and need for compilation. All of them are provided by JBoss WildFly -->
<!-- Import the CDI API, we use provided scope as the API is included in
JBoss WildFly -->
<!-- Import the CDI API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the Common Annotations API (JSR-250), we use provided scope
as the API is included in JBoss WildFly -->
<!-- Import the Common Annotations API (JSR-250), we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.jboss.spec.javax.annotation</groupId>
<artifactId>jboss-annotations-api_1.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the JAX-RS API, we use provided scope as the API is included
in JBoss WildFly -->
<!-- Import the JAX-RS API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the JPA API, we use provided scope as the API is included in
JBoss WildFly -->
<!-- Import the JPA API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the EJB API, we use provided scope as the API is included in
JBoss WildFly -->
<!-- Import the EJB API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
@ -135,8 +124,7 @@
</exclusions>
</dependency>
<!-- Import the JSF API, we use provided scope as the API is included in
JBoss WildFly -->
<!-- Import the JSF API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.jboss.spec.javax.faces</groupId>
<artifactId>jboss-jsf-api_2.2_spec</artifactId>
@ -145,16 +133,14 @@
<!-- Now we declare any tools needed -->
<!-- Annotation processor to generate the JPA 2.0 metamodel classes for
typesafe criteria queries -->
<!-- Annotation processor to generate the JPA 2.0 metamodel classes for typesafe criteria queries -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<scope>provided</scope>
</dependency>
<!-- Annotation processor that raising compilation errors whenever constraint
annotations are incorrectly used. -->
<!-- Annotation processor that raising compilation errors whenever constraint annotations are incorrectly used. -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
@ -169,8 +155,7 @@
</dependency>
<!-- Optional, but highly recommended -->
<!-- Arquillian allows you to test enterprise code such as EJBs and Transactional(JTA)
JPA from JUnit/TestNG -->
<!-- Arquillian allows you to test enterprise code such as EJBs and Transactional(JTA) JPA from JUnit/TestNG -->
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
@ -225,8 +210,7 @@
</dependencies>
<build>
<!-- Maven will append the version to the finalName (which is the name
given to the generated war, and hence the context root) -->
<!-- Maven will append the version to the finalName (which is the name given to the generated war, and hence the context root) -->
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
@ -265,10 +249,8 @@
<profiles>
<profile>
<!-- The default profile skips all tests, though you can tune it to run
just unit tests based on a custom pattern -->
<!-- Seperate profiles are provided for running all tests, including Arquillian
tests that execute in the specified container -->
<!-- The default profile skips all tests, though you can tune it to run just unit tests based on a custom pattern -->
<!-- Seperate profiles are provided for running all tests, including Arquillian tests that execute in the specified container -->
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
@ -288,10 +270,8 @@
<profile>
<!-- An optional Arquillian testing profile that executes tests
in your WildFly instance -->
<!-- This profile will start a new WildFly instance, and execute the
test, shutting it down when done -->
<!-- An optional Arquillian testing profile that executes tests in your WildFly instance -->
<!-- This profile will start a new WildFly instance, and execute the test, shutting it down when done -->
<!-- Run with: mvn clean test -Parq-wildfly-managed -->
<id>arq-wildfly-managed</id>
<dependencies>

View File

@ -1,6 +1,6 @@
<?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">
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>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
@ -75,8 +75,8 @@
</pluginManagement>
</build>
<modules>
<module>ejb-remote</module>
<module>ejb-client</module>
</modules>
<modules>
<module>ejb-remote</module>
<module>ejb-client</module>
</modules>
</project>

View File

@ -1,7 +1,6 @@
<?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">
<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>
<groupId>com.baeldung.enterprise.patterns</groupId>

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
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>
<groupId>com.baeldung.feign</groupId>

View File

@ -0,0 +1,25 @@
apply plugin: 'java'
apply plugin: 'maven'
repositories{
mavenCentral()
}
dependencies{
compile 'org.springframework:spring-context:4.3.5.RELEASE'
}
task hello {
println "this Baeldung's tutorial is ${awesomeness}"
}
uploadArchives {
repositories {
mavenDeployer {
repository(url: 'http://yourmavenrepo/repository') {
authentication(userName: 'user', password: 'password');
}
}
}
}

View File

@ -0,0 +1,3 @@
awesomeness=awesome
group=com.baeldung.tutorial
version=1.0.1

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Sat Dec 31 15:46:08 BRT 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-bin.zip

160
gradle-tutorial/gradlew vendored Normal file
View File

@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
gradle-tutorial/gradlew.bat vendored Normal file
View File

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,5 @@
public class Main{
public static void main(String[] args){
System.out.println("Baeldung Rocks");
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.guava;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.junit.Test;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class MultimapTest {
@Test
public void givenMap_whenAddTwoValuesForSameKey_shouldOverridePreviousKey() {
//given
String key = "a-key";
Map<String, String> map = new LinkedHashMap<>();
//when
map.put(key, "firstValue");
map.put(key, "secondValue");
//then
assertEquals(1, map.size());
}
@Test
public void givenMultiMap_whenAddTwoValuesForSameKey_shouldHaveTwoEntriesInMap() {
//given
String key = "a-key";
Multimap<String, String> map = ArrayListMultimap.create();
//when
map.put(key, "firstValue");
map.put(key, "secondValue");
//then
assertEquals(2, map.size());
}
@Test
public void givenMapOfListValues_whenAddTwoValuesForSameKey_shouldHaveTwoElementsInList() {
//given
String key = "a-key";
Map<String, List<String>> map = new LinkedHashMap<>();
//when
List<String> values = map.get(key);
if(values == null){
values = new LinkedList<>();
values.add("firstValue");
values.add("secondValue");
}
map.put(key, values);
//then
assertEquals(1, map.size());
}
}

View File

@ -28,13 +28,14 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@Ignore("Server is not available")
public class HttpClientMultipartLiveTest {
private static final String SERVER = "http://echo.200please.com";
// No longer available
// private static final String SERVER = "http://echo.200please.com";
private static final String SERVER = "http://posttestserver.com/post.php";
private static final String TEXTFILENAME = "temp.txt";
private static final String IMAGEFILENAME = "image.jpg";
private static final String ZIPFILENAME = "zipFile.zip";
@ -46,7 +47,8 @@ public class HttpClientMultipartLiveTest {
@Before
public final void before() {
client = HttpClientBuilder.create().build();
client = HttpClientBuilder.create()
.build();
post = new HttpPost(SERVER);
}
@ -80,7 +82,9 @@ public class HttpClientMultipartLiveTest {
@Test
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + TEXTFILENAME);
final URL url = Thread.currentThread()
.getContextClassLoader()
.getResource("uploads/" + TEXTFILENAME);
final File file = new File(url.getPath());
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
@ -97,11 +101,12 @@ public class HttpClientMultipartLiveTest {
post.setEntity(entity);
response = client.execute(post);
final int statusCode = response.getStatusLine().getStatusCode();
final int statusCode = response.getStatusLine()
.getStatusCode();
final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader);
@ -109,7 +114,9 @@ public class HttpClientMultipartLiveTest {
@Test
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException {
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + TEXTFILENAME);
final URL url = Thread.currentThread()
.getContextClassLoader()
.getResource("uploads/" + TEXTFILENAME);
final File file = new File(url.getPath());
final String message = "This is a multipart post";
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
@ -119,11 +126,12 @@ public class HttpClientMultipartLiveTest {
final HttpEntity entity = builder.build();
post.setEntity(entity);
response = client.execute(post);
final int statusCode = response.getStatusLine().getStatusCode();
final int statusCode = response.getStatusLine()
.getStatusCode();
final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader);
@ -131,8 +139,12 @@ public class HttpClientMultipartLiveTest {
@Test
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + ZIPFILENAME);
final URL url2 = Thread.currentThread().getContextClassLoader().getResource("uploads/" + IMAGEFILENAME);
final URL url = Thread.currentThread()
.getContextClassLoader()
.getResource("uploads/" + ZIPFILENAME);
final URL url2 = Thread.currentThread()
.getContextClassLoader()
.getResource("uploads/" + IMAGEFILENAME);
final InputStream inputStream = new FileInputStream(url.getPath());
final File file = new File(url2.getPath());
final String message = "This is a multipart post";
@ -144,11 +156,12 @@ public class HttpClientMultipartLiveTest {
final HttpEntity entity = builder.build();
post.setEntity(entity);
response = client.execute(post);
final int statusCode = response.getStatusLine().getStatusCode();
final int statusCode = response.getStatusLine()
.getStatusCode();
final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader);
@ -166,11 +179,12 @@ public class HttpClientMultipartLiveTest {
final HttpEntity entity = builder.build();
post.setEntity(entity);
response = client.execute(post);
final int statusCode = response.getStatusLine().getStatusCode();
final int statusCode = response.getStatusLine()
.getStatusCode();
final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader);
@ -179,7 +193,8 @@ public class HttpClientMultipartLiveTest {
// UTIL
final String getContent() throws IOException {
rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
rd = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
String body = "";
String content = "";
while ((body = rd.readLine()) != null) {
@ -189,7 +204,9 @@ public class HttpClientMultipartLiveTest {
}
final String getContentTypeHeader() throws IOException {
return post.getEntity().getContentType().toString();
return post.getEntity()
.getContentType()
.toString();
}
}

View File

@ -1,11 +1,24 @@
package org.baeldung.httpclient;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.*;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
@ -15,14 +28,6 @@ import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.junit.Test;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
/**
* This test requires a localhost server over HTTPS <br>
* It should only be manually run, not part of the automated build
@ -35,13 +40,15 @@ public class HttpsClientSslLiveTest {
// tests
@Test(expected = SSLException.class)
@Test(expected = SSLHandshakeException.class)
public final void whenHttpsUrlIsConsumed_thenException() throws IOException {
final CloseableHttpClient httpClient = HttpClientBuilder.create().build();
final CloseableHttpClient httpClient = HttpClientBuilder.create()
.build();
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
}
@SuppressWarnings("deprecation")
@ -57,7 +64,8 @@ public class HttpsClientSslLiveTest {
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
}
@ -65,44 +73,62 @@ public class HttpsClientSslLiveTest {
@Test
public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
final CloseableHttpClient httpClient = HttpClients.custom().setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLSocketFactory(sslsf).build();
final CloseableHttpClient httpClient = HttpClients.custom()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
.setSSLSocketFactory(sslsf)
.build();
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
}
@Test
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLHostnameVerifier(hostnameVerifier)
.setSSLSocketFactory(sslsf)
.build();
// new
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
}
@Test
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true).build();
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true)
.build();
final CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
final CloseableHttpClient client = HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
httpGet.setHeader("Accept", "application/xml");
final HttpResponse response = client.execute(httpGet);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.jackson.dtos.withEnum;
public enum DistanceEnumSimple {
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
private String unit;
private final double meters;
private DistanceEnumSimple(String unit, double meters) {
this.unit = unit;
this.meters = meters;
}
public double getMeters() {
return meters;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.jackson.dtos.withEnum;
import com.fasterxml.jackson.annotation.JsonFormat;
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum DistanceEnumWithJsonFormat {
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
private String unit;
private final double meters;
private DistanceEnumWithJsonFormat(String unit, double meters) {
this.unit = unit;
this.meters = meters;
}
public double getMeters() {
return meters;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.jackson.dtos.withEnum;
import com.fasterxml.jackson.annotation.JsonValue;
public enum DistanceEnumWithValue {
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
private String unit;
private final double meters;
private DistanceEnumWithValue(String unit, double meters) {
this.unit = unit;
this.meters = meters;
}
@JsonValue
public double getMeters() {
return meters;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.jackson.dtos.withEnum;
import com.baeldung.jackson.enums.Distance;
public class MyDtoWithEnumCustom {
private String stringValue;
private int intValue;
private boolean booleanValue;
private Distance type;
public MyDtoWithEnumCustom() {
super();
}
public MyDtoWithEnumCustom(final String stringValue, final int intValue, final boolean booleanValue, final Distance type) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
this.type = type;
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
public Distance getType() {
return type;
}
public void setType(final Distance type) {
this.type = type;
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.jackson.dtos.withEnum;
public class MyDtoWithEnumJsonFormat {
private String stringValue;
private int intValue;
private boolean booleanValue;
private DistanceEnumWithJsonFormat distanceType;
public MyDtoWithEnumJsonFormat() {
super();
}
public MyDtoWithEnumJsonFormat(final String stringValue, final int intValue, final boolean booleanValue, final DistanceEnumWithJsonFormat type) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
this.distanceType = type;
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
public DistanceEnumWithJsonFormat getDistanceType() {
return distanceType;
}
public void setDistanceType(final DistanceEnumWithJsonFormat type) {
this.distanceType = type;
}
}

View File

@ -1,6 +1,32 @@
package com.baeldung.jackson.test;
import com.baeldung.jackson.annotation.*;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.junit.Test;
import com.baeldung.jackson.annotation.BeanWithCreator;
import com.baeldung.jackson.annotation.BeanWithCustomAnnotation;
import com.baeldung.jackson.annotation.BeanWithFilter;
import com.baeldung.jackson.annotation.BeanWithGetter;
import com.baeldung.jackson.annotation.BeanWithIgnore;
import com.baeldung.jackson.annotation.BeanWithInject;
import com.baeldung.jackson.annotation.ExtendableBean;
import com.baeldung.jackson.annotation.MyBean;
import com.baeldung.jackson.annotation.PrivateBean;
import com.baeldung.jackson.annotation.RawBean;
import com.baeldung.jackson.annotation.UnwrappedUser;
import com.baeldung.jackson.annotation.UserWithIgnoreType;
import com.baeldung.jackson.annotation.Zoo;
import com.baeldung.jackson.bidirection.ItemWithIdentity;
import com.baeldung.jackson.bidirection.ItemWithRef;
import com.baeldung.jackson.bidirection.UserWithIdentity;
@ -8,7 +34,7 @@ import com.baeldung.jackson.bidirection.UserWithRef;
import com.baeldung.jackson.date.EventWithFormat;
import com.baeldung.jackson.date.EventWithSerializer;
import com.baeldung.jackson.dtos.MyMixInForIgnoreType;
import com.baeldung.jackson.dtos.withEnum.TypeEnumWithValue;
import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue;
import com.baeldung.jackson.exception.UserWithRoot;
import com.baeldung.jackson.jsonview.Item;
import com.baeldung.jackson.jsonview.Views;
@ -20,17 +46,6 @@ import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import org.junit.Test;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class JacksonAnnotationTest {
@ -85,10 +100,10 @@ public class JacksonAnnotationTest {
}
@Test
public void whenSerializingUsingJsonValue_thenCorrect() throws JsonProcessingException {
final String enumAsString = new ObjectMapper().writeValueAsString(TypeEnumWithValue.TYPE1);
public void whenSerializingUsingJsonValue_thenCorrect() throws IOException {
final String enumAsString = new ObjectMapper().writeValueAsString(DistanceEnumWithValue.MILE);
assertThat(enumAsString, is("\"Type A\""));
assertThat(enumAsString, is("1609.34"));
}
@Test

View File

@ -6,14 +6,14 @@ import static org.junit.Assert.assertThat;
import java.io.IOException;
import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnum;
import com.baeldung.jackson.dtos.withEnum.TypeEnum;
import com.baeldung.jackson.dtos.withEnum.TypeEnumSimple;
import com.baeldung.jackson.dtos.withEnum.TypeEnumWithValue;
import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumCustom;
import com.baeldung.jackson.dtos.withEnum.TypeEnumWithCustomSerializer;
import org.junit.Test;
import com.baeldung.jackson.dtos.withEnum.DistanceEnumSimple;
import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithJsonFormat;
import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue;
import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumCustom;
import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumJsonFormat;
import com.baeldung.jackson.enums.Distance;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -24,10 +24,9 @@ public class JacksonSerializationEnumsUnitTest {
@Test
public final void whenSerializingASimpleEnum_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String enumAsString = mapper.writeValueAsString(TypeEnumSimple.TYPE1);
System.out.println(enumAsString);
final String enumAsString = mapper.writeValueAsString(DistanceEnumSimple.MILE);
assertThat(enumAsString, containsString("TYPE1"));
assertThat(enumAsString, containsString("MILE"));
}
// tests - enum with main value
@ -35,10 +34,9 @@ public class JacksonSerializationEnumsUnitTest {
@Test
public final void whenSerializingAEnumWithValue_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String enumAsString = mapper.writeValueAsString(TypeEnumWithValue.TYPE1);
System.out.println(enumAsString);
final String enumAsString = mapper.writeValueAsString(DistanceEnumWithValue.MILE);
assertThat(enumAsString, is("\"Type A\""));
assertThat(enumAsString, is("1609.34"));
}
// tests - enum
@ -46,28 +44,25 @@ public class JacksonSerializationEnumsUnitTest {
@Test
public final void whenSerializingAnEnum_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String enumAsString = mapper.writeValueAsString(TypeEnum.TYPE1);
final String enumAsString = mapper.writeValueAsString(DistanceEnumWithJsonFormat.MILE);
System.out.println(enumAsString);
assertThat(enumAsString, containsString("\"name\":\"Type A\""));
assertThat(enumAsString, containsString("\"meters\":1609.34"));
}
@Test
public final void whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnum("a", 1, true, TypeEnum.TYPE1));
final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumJsonFormat("a", 1, true, DistanceEnumWithJsonFormat.MILE));
System.out.println(enumAsString);
assertThat(enumAsString, containsString("\"name\":\"Type A\""));
assertThat(enumAsString, containsString("\"meters\":1609.34"));
}
@Test
public final void whenSerializingArrayOfEnums_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String json = mapper.writeValueAsString(new TypeEnum[] { TypeEnum.TYPE1, TypeEnum.TYPE2 });
final String json = mapper.writeValueAsString(new DistanceEnumWithJsonFormat[] { DistanceEnumWithJsonFormat.MILE, DistanceEnumWithJsonFormat.KILOMETER });
System.out.println(json);
assertThat(json, containsString("\"name\":\"Type A\""));
assertThat(json, containsString("\"meters\":1609.34"));
}
// tests - enum with custom serializer
@ -75,10 +70,9 @@ public class JacksonSerializationEnumsUnitTest {
@Test
public final void givenCustomSerializer_whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumCustom("a", 1, true, TypeEnumWithCustomSerializer.TYPE1));
final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumCustom("a", 1, true, Distance.MILE));
System.out.println(enumAsString);
assertThat(enumAsString, containsString("\"name\":\"Type A\""));
assertThat(enumAsString, containsString("\"meters\":1609.34"));
}
}

10
jsoup/README.md Normal file
View File

@ -0,0 +1,10 @@
=========
## jsoup Example Project
### Relevant Articles:
- [Parsing HTML in Java with Jsoup](http://www.baeldung.com/java-with-jsoup)
### Build the Project
mvn clean install

View File

@ -25,6 +25,6 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<jsoup.version>1.10.1</jsoup.version>
<jsoup.version>1.10.2</jsoup.version>
</properties>
</project>

View File

@ -1,91 +0,0 @@
package com.baeldung.jsoup;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
public class JsoupParser {
Document doc;
public void loadDocument(String blogUrl) throws IOException {
doc = Jsoup.connect(blogUrl).get();
}
void loadDocumentCustomized(String blogUrl) throws IOException {
doc = Jsoup.connect(blogUrl)
.userAgent("Mozilla")
.timeout(5000)
.cookie("cookiename", "val234")
.cookie("anothercookie", "ilovejsoup")
.referrer("http://google.com")
.header("headersecurity", "xyz123")
.get();
}
void examplesSelectors() {
Elements links = doc.select("a");
Elements logo = doc.select(".spring-logo--container");
Elements pagination = doc.select("#pagination_control");
Elements divsDescendant = doc.select("header div");
Elements divsDirect = doc.select("header > div");
Element pag = doc.getElementById("pagination_control");
Elements desktopOnly = doc.getElementsByClass("desktopOnly");
Elements sections = doc.select("section");
Element firstSection = sections.first();
Elements sectionParagraphs = firstSection.select(".paragraph");
}
void examplesTraversing() {
Elements sections = doc.select("section");
Element firstSection = sections.first();
Element lastSection = sections.last();
Element secondSection = sections.get(2);
Elements allParents = firstSection.parents();
Element parent = firstSection.parent();
Elements children = firstSection.children();
Elements siblings = firstSection.siblingElements();
sections.stream().forEach(el -> System.out.println("section: " + el));
}
void examplesExtracting() {
Element firstArticle = doc.select("article").first();
Element timeElement = firstArticle.select("time").first();
String dateTimeOfFirstArticle = timeElement.attr("datetime");
Element sectionDiv = firstArticle.select("section div").first();
String sectionDivText = sectionDiv.text();
String articleHtml = firstArticle.html();
String outerHtml = firstArticle.outerHtml();
}
void examplesModifying() {
Element firstArticle = doc.select("article").first();
Element timeElement = firstArticle.select("time").first();
Element sectionDiv = firstArticle.select("section div").first();
String dateTimeOfFirstArticle = timeElement.attr("datetime");
timeElement.attr("datetime", "2016-12-16 15:19:54.3");
sectionDiv.text("foo bar");
firstArticle.select("h2").html("<div><span></span></div>");
Element link = new Element(Tag.valueOf("a"), "")
.text("Checkout this amazing website!")
.attr("href", "http://baeldung.com")
.attr("target", "_blank");
firstArticle.appendChild(link);
doc.select("li.navbar-link").remove();
firstArticle.select("img").remove();
}
String getTidyHtml() {
return doc.html();
}
}

View File

@ -1,36 +1,111 @@
package com.baeldung.jsoup;
import java.io.IOException;
import org.jsoup.HttpStatusException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class JsoupParserTest {
JsoupParser jsoupParser;
Document doc;
@Before
public void setUp() {
jsoupParser = new JsoupParser();
public void setUp() throws IOException {
doc = Jsoup.connect("https://spring.io/blog").get();
}
@Test
public void test404() throws IOException {
public void loadDocument404() throws IOException {
try {
jsoupParser.loadDocument("https://spring.io/will-not-be-found");
doc = Jsoup.connect("https://spring.io/will-not-be-found").get();
} catch (HttpStatusException ex) {
assertEquals(404, ex.getStatusCode());
}
}
@Test
public void testChange() throws IOException {
jsoupParser.loadDocument("http://spring.io/blog");
public void loadDocumentCustomized() throws IOException {
doc = Jsoup.connect("https://spring.io/blog")
.userAgent("Mozilla")
.timeout(5000)
.cookie("cookiename", "val234")
.cookie("anothercookie", "ilovejsoup")
.referrer("http://google.com")
.header("headersecurity", "xyz123")
.get();
}
jsoupParser.examplesModifying();
@Test
public void examplesSelectors() {
Elements links = doc.select("a");
Elements logo = doc.select(".spring-logo--container");
Elements pagination = doc.select("#pagination_control");
Elements divsDescendant = doc.select("header div");
Elements divsDirect = doc.select("header > div");
assertTrue(jsoupParser.getTidyHtml().contains("http://baeldung.com"));
Element pag = doc.getElementById("pagination_control");
Elements desktopOnly = doc.getElementsByClass("desktopOnly");
Elements sections = doc.select("section");
Element firstSection = sections.first();
Elements sectionParagraphs = firstSection.select(".paragraph");
}
@Test
public void examplesTraversing() {
Elements sections = doc.select("section");
Element firstSection = sections.first();
Element lastSection = sections.last();
Element secondSection = sections.get(2);
Elements allParents = firstSection.parents();
Element parent = firstSection.parent();
Elements children = firstSection.children();
Elements siblings = firstSection.siblingElements();
sections.forEach(el -> System.out.println("section: " + el));
}
@Test
public void examplesExtracting() {
Element firstArticle = doc.select("article").first();
Element timeElement = firstArticle.select("time").first();
String dateTimeOfFirstArticle = timeElement.attr("datetime");
Element sectionDiv = firstArticle.select("section div").first();
String sectionDivText = sectionDiv.text();
String articleHtml = firstArticle.html();
String outerHtml = firstArticle.outerHtml();
}
@Test
public void examplesModifying() {
Element firstArticle = doc.select("article").first();
Element timeElement = firstArticle.select("time").first();
Element sectionDiv = firstArticle.select("section div").first();
String dateTimeOfFirstArticle = timeElement.attr("datetime");
timeElement.attr("datetime", "2016-12-16 15:19:54.3");
sectionDiv.text("foo bar");
firstArticle.select("h2").html("<div><span></span></div>");
Element link = new Element(Tag.valueOf("a"), "")
.text("Checkout this amazing website!")
.attr("href", "http://baeldung.com")
.attr("target", "_blank");
firstArticle.appendChild(link);
doc.select("li.navbar-link").remove();
firstArticle.select("img").remove();
assertTrue(doc.html().contains("http://baeldung.com"));
}
}

View File

@ -117,6 +117,7 @@
<module>spring-hibernate3</module>
<module>spring-hibernate4</module>
<module>spring-integration</module>
<module>spring-jersey</module>
<module>spring-jms</module>
<module>spring-jooq</module>
<module>spring-jpa</module>

View File

@ -0,0 +1,41 @@
package org.baeldung.taskscheduler;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.PeriodicTrigger;
@Configuration
@ComponentScan(basePackages = "org.baeldung.taskscheduler", basePackageClasses = { ThreadPoolTaskSchedulerExamples.class })
public class ThreadPoolTaskSchedulerConfig {
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(5);
threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
return threadPoolTaskScheduler;
}
@Bean
public CronTrigger cronTrigger() {
return new CronTrigger("10 * * * * ?");
}
@Bean
public PeriodicTrigger periodicTrigger() {
return new PeriodicTrigger(2000, TimeUnit.MICROSECONDS);
}
@Bean
public PeriodicTrigger periodicFixedDelayTrigger() {
PeriodicTrigger periodicTrigger = new PeriodicTrigger(2000, TimeUnit.MICROSECONDS);
periodicTrigger.setFixedRate(true);
periodicTrigger.setInitialDelay(1000);
return periodicTrigger;
}
}

View File

@ -0,0 +1,47 @@
package org.baeldung.taskscheduler;
import java.util.Date;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;
@Component
public class ThreadPoolTaskSchedulerExamples {
@Autowired
private ThreadPoolTaskScheduler taskScheduler;
@Autowired
private CronTrigger cronTrigger;
@Autowired
private PeriodicTrigger periodicTrigger;
@PostConstruct
public void scheduleRunnableWithCronTrigger(){
taskScheduler.schedule(new RunnableTask("Current Date"), new Date());
taskScheduler.scheduleWithFixedDelay(new RunnableTask("Fixed 1 second Delay"), 1000);
taskScheduler.scheduleWithFixedDelay(new RunnableTask("Current Date Fixed 1 second Delay"),new Date() , 1000);
taskScheduler.scheduleAtFixedRate(new RunnableTask("Fixed Rate of 2 seconds"),new Date(), 2000);
taskScheduler.scheduleAtFixedRate(new RunnableTask("Fixed Rate of 2 seconds"), 2000);
taskScheduler.schedule(new RunnableTask("Cron Trigger"), cronTrigger);
taskScheduler.schedule(new RunnableTask("Periodic Trigger"), periodicTrigger);
}
class RunnableTask implements Runnable{
private String message;
public RunnableTask(String message){
this.message = message;
}
@Override
public void run() {
System.out.println("Runnable Task with "+message+" on thread "+Thread.currentThread().getName());
}
}
}

View File

@ -0,0 +1,16 @@
package org.baeldung.taskscheduler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ThreadPoolTaskSchedulerConfig.class }, loader = AnnotationConfigContextLoader.class)
public class ThreadPoolTaskSchedulerTest {
@Test
public void testThreadPoolTaskSchedulerAnnotation() throws InterruptedException {
Thread.sleep(2550);
}
}

View File

@ -1,4 +1,5 @@
<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">
<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>
<groupId>com.baeldung</groupId>

View File

@ -33,7 +33,7 @@ import com.mongodb.gridfs.GridFSDBFile;
@ContextConfiguration("file:src/main/resources/mongoConfig.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class GridFSIntegrationTest {
public class GridFSLiveTest {
private final Logger logger = LoggerFactory.getLogger(getClass());

View File

@ -25,7 +25,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class DocumentQueryIntegrationTest {
public class DocumentQueryLiveTest {
@Autowired
private MongoTemplate mongoTemplate;

View File

@ -28,7 +28,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class MongoTemplateQueryIntegrationTest {
public class MongoTemplateQueryLiveTest {
@Autowired
private MongoTemplate mongoTemplate;

View File

@ -7,7 +7,7 @@ import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
public class BaseQueryIntegrationTest {
public class BaseQueryLiveTest {
@Autowired
protected UserRepository userRepository;

View File

@ -17,7 +17,7 @@ import com.mysema.query.types.Predicate;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class DSLQueryIntegrationTest extends BaseQueryIntegrationTest {
public class DSLQueryLiveTest extends BaseQueryLiveTest {
@Test
public void givenUsersExist_whenFindingUsersByName_thenUserAreFound() {

View File

@ -14,7 +14,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class JSONQueryIntegrationTest extends BaseQueryIntegrationTest {
public class JSONQueryLiveTest extends BaseQueryLiveTest {
@Test
public void givenUsersExist_whenFindingUsersByName_thenUsersAreFound() {

View File

@ -14,7 +14,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class QueryMethodsIntegrationTest extends BaseQueryIntegrationTest {
public class QueryMethodsLiveTest extends BaseQueryLiveTest {
@Test
public void givenUsersExist_whenFindingUsersByName_thenUsersAreFound() {

View File

@ -24,7 +24,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class UserRepositoryIntegrationTest {
public class UserRepositoryLiveTest {
@Autowired
private UserRepository userRepository;

13
spring-jersey/.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

3
spring-jersey/README.md Normal file
View File

@ -0,0 +1,3 @@
=========
## REST API with Jersey & Spring Example Project

210
spring-jersey/pom.xml Normal file
View File

@ -0,0 +1,210 @@
<?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>
<groupId>com.baeldung</groupId>
<artifactId>jersey-api</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<jersey.version>2.25</jersey.version>
<jcl.slf4j.version>1.7.22</jcl.slf4j.version>
<logback.version>1.1.8</logback.version>
<junit.version>4.12</junit.version>
<maven-war-plugin.version>3.0.0</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
<junit.version>4.12</junit.version>
<httpcore.version>4.4.5</httpcore.version>
<httpclient.version>4.5.2</httpclient.version>
<servlet-api-version>3.1.0</servlet-api-version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- core library -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- servlet api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api-version}</version>
<scope>provided</scope>
</dependency>
<!-- optional library -->
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${jcl.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpcore.version}</version>
<scope>test</scope>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>false</wait>
</configuration>
<executions>
<execution>
<id>start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,22 @@
package com.baeldung.server.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
servletContext.addListener(new ContextLoaderListener(context));
servletContext.setInitParameter("contextConfigLocation", "com.baeldung.server");
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.server.config;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import com.baeldung.server.exception.AlreadyExistsExceptionHandler;
import com.baeldung.server.exception.NotFoundExceptionHandler;
import com.baeldung.server.rest.EmployeeResource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@ApplicationPath("/resources")
public class RestConfig extends Application {
public Set<Class<?>> getClasses() {
return new HashSet<Class<?>>(Arrays.asList(EmployeeResource.class, NotFoundExceptionHandler.class, AlreadyExistsExceptionHandler.class));
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.server.exception;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class AlreadyExistsExceptionHandler implements ExceptionMapper<EmployeeAlreadyExists> {
public Response toResponse(EmployeeAlreadyExists ex) {
return Response.status(Response.Status.CONFLICT.getStatusCode()).build();
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.server.exception;
public class EmployeeAlreadyExists extends RuntimeException {
}

View File

@ -0,0 +1,5 @@
package com.baeldung.server.exception;
public class EmployeeNotFound extends RuntimeException {
}

View File

@ -0,0 +1,12 @@
package com.baeldung.server.exception;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class NotFoundExceptionHandler implements ExceptionMapper<EmployeeNotFound> {
public Response toResponse(EmployeeNotFound ex) {
return Response.status(Response.Status.NOT_FOUND).build();
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.server.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Employee {
private int id;
private String firstName;
public Employee() {
}
public Employee(int id, String firstName) {
this.id = id;
this.firstName = firstName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.server.repository;
import java.util.List;
import com.baeldung.server.model.Employee;
public interface EmployeeRepository {
public List<Employee> getAllEmployees();
public Employee getEmployee(int id);
public void updateEmployee(Employee employee, int id);
public void deleteEmployee(int id);
public void addEmployee(Employee employee);
}

View File

@ -0,0 +1,65 @@
package com.baeldung.server.repository;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import com.baeldung.server.exception.EmployeeAlreadyExists;
import com.baeldung.server.exception.EmployeeNotFound;
import com.baeldung.server.model.Employee;
@Component
public class EmployeeRepositoryImpl implements EmployeeRepository {
private List<Employee> employeeList;
public EmployeeRepositoryImpl() {
employeeList = new ArrayList<Employee>();
employeeList.add(new Employee(1, "Jane"));
employeeList.add(new Employee(2, "Jack"));
employeeList.add(new Employee(3, "George"));
}
public List<Employee> getAllEmployees() {
return employeeList;
}
public Employee getEmployee(int id) {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
return emp;
}
}
throw new EmployeeNotFound();
}
public void updateEmployee(Employee employee, int id) {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
emp.setId(employee.getId());
emp.setFirstName(employee.getFirstName());
return;
}
}
throw new EmployeeNotFound();
}
public void deleteEmployee(int id) {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
employeeList.remove(emp);
return;
}
}
throw new EmployeeNotFound();
}
public void addEmployee(Employee employee) {
for (Employee emp : employeeList) {
if (emp.getId() == employee.getId()) {
throw new EmployeeAlreadyExists();
}
}
employeeList.add(employee);
}
}

View File

@ -0,0 +1,64 @@
package com.baeldung.server.rest;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
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;
import org.springframework.beans.factory.annotation.Autowired;
import com.baeldung.server.model.Employee;
import com.baeldung.server.repository.EmployeeRepository;
@Path("/employees")
public class EmployeeResource {
@Autowired
private EmployeeRepository employeeRepository;
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Employee> getAllEmployees() {
return employeeRepository.getAllEmployees();
}
@GET
@Path("/{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Employee getEmployee(@PathParam("id") int id) {
return employeeRepository.getEmployee(id);
}
@PUT
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateEmployee(Employee employee, @PathParam("id") int id) {
employeeRepository.updateEmployee(employee, id);
return Response.status(Response.Status.OK.getStatusCode()).build();
}
@DELETE
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response deleteEmployee(@PathParam("id") int id) {
employeeRepository.deleteEmployee(id);
return Response.status(Response.Status.OK.getStatusCode()).build();
}
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response addEmployee(Employee employee, @Context UriInfo uriInfo) {
employeeRepository.addEmployee(new Employee(employee.getId(), employee.getFirstName()));
return Response.status(Response.Status.CREATED.getStatusCode()).header("Location", String.format("%s/%s", uriInfo.getAbsolutePath().toString(), employee.getId())).build();
}
}

View File

@ -0,0 +1,15 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} -
%message%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,91 @@
package com.baeldung.server;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Test;
import com.baeldung.server.model.Employee;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JerseyApiLiveTest {
private static final String SERVICE_URL = "http://localhost:8082/jersey-api/resources/employees";
@Test
public void givenGetAllEmployees_whenCorrectRequest_thenResponseCodeSuccess() throws ClientProtocolException, IOException {
final HttpUriRequest request = new HttpGet(SERVICE_URL);
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK);
}
@Test
public void givenGetEmployee_whenEmployeeExists_thenResponseCodeSuccess() throws ClientProtocolException, IOException {
final HttpUriRequest request = new HttpGet(SERVICE_URL + "/1");
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK);
}
@Test
public void givenGetEmployee_whenEmployeeDoesNotExist_thenResponseCodeNotFound() throws ClientProtocolException, IOException {
final HttpUriRequest request = new HttpGet(SERVICE_URL + "/1000");
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND);
}
@Test
public void givenGetEmployee_whenJsonRequested_thenCorrectDataRetrieved() throws ClientProtocolException, IOException {
final HttpUriRequest request = new HttpGet(SERVICE_URL + "/1");
request.setHeader("Accept", "application/json");
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
ObjectMapper mapper = new ObjectMapper();
Employee emp = mapper.readValue(httpResponse.getEntity().getContent(), Employee.class);
assert(emp.getFirstName().equals("Jane"));
}
@Test
public void givenAddEmployee_whenJsonRequestSent_thenResponseCodeCreated() throws ClientProtocolException, IOException {
final HttpPost request = new HttpPost(SERVICE_URL);
Employee emp = new Employee(5, "Johny");
ObjectMapper mapper = new ObjectMapper();
String empJson = mapper.writeValueAsString(emp);
StringEntity input = new StringEntity(empJson);
input.setContentType("application/json");
request.setEntity(input);
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED);
}
@Test
public void givenAddEmployee_whenRequestForExistingObjectSent_thenResponseCodeConflict() throws ClientProtocolException, IOException {
final HttpPost request = new HttpPost(SERVICE_URL);
Employee emp = new Employee(1, "Johny");
ObjectMapper mapper = new ObjectMapper();
String empJson = mapper.writeValueAsString(emp);
StringEntity input = new StringEntity(empJson);
input.setContentType("application/json");
request.setEntity(input);
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CONFLICT);
}
}

109
spring-remoting/pom.xml Normal file
View File

@ -0,0 +1,109 @@
<?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>
<groupId>com.baeldung</groupId>
<artifactId>spring-remoting</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-war-plugin.version>3.0.0</maven-war-plugin.version>
<servlet.version>3.1.0</servlet.version>
<logback.version>1.1.7</logback.version>
<spring.version>4.2.4.RELEASE</spring.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- logback -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!-- companion modules -->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>api</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<debug>true</debug>
<optimize>true</optimize>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<showDeprecation>true</showDeprecation>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
<!-- This special setup for maven-war-plugin is needed to use Servlet 3 annotation based configuration, where a WEB-INF/web.xml is not strictl needed. -->
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>remoting-http</module>
</modules>
</project>

View File

@ -0,0 +1,14 @@
<?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">
<parent>
<artifactId>spring-remoting-http</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>api</artifactId>
<name>spring-remoting-http-api</name>
<description>API definition shared between client and server.</description>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.api;
import java.io.Serializable;
public class Address implements Serializable{
private String address;
private String countryCode;
public Address(String address, String countryCode) {
this.address = address;
this.countryCode = countryCode;
}
public String getAddress() {
return address;
}
public String getCountryCode() {
return countryCode;
}
@Override public String toString() {
return address + " (" + countryCode + ")";
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.api;
import java.io.Serializable;
import java.util.Date;
public class Booking implements Serializable {
private int costInCent;
private int etaInSeconds;
private String bookingCode;
private Date pickUptime;
private Address pickUpAddress;
private Address dropOffAddress;
public Booking(Address pickUpAddress, Date pickUptime, Address dropOffAddress, int costInCent, int etaInSeconds, String bookingCode) {
this.costInCent = costInCent;
this.etaInSeconds = etaInSeconds;
this.bookingCode = bookingCode;
this.pickUptime = pickUptime;
this.pickUpAddress = pickUpAddress;
this.dropOffAddress = dropOffAddress;
}
public int getCostInCent() {
return costInCent;
}
public int getEtaInSeconds() {
return etaInSeconds;
}
public String getBookingCode() {
return bookingCode;
}
public Date getPickUptime() {
return pickUptime;
}
public Address getDropOffAddress() {
return dropOffAddress;
}
@Override public String toString() {
return String.format("Booking: pick up @ %tr in %s, drop down in %s after %d minutes, %.2f $.", pickUptime, pickUpAddress, dropOffAddress, etaInSeconds/60, costInCent/100.0);
}
public static void main(String[] args) throws InterruptedException {
System.out.println(
new Booking(new Address("a", "b"), new Date(), new Address("c", "d"), 123_00, 600, "abc")
);
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.api;
public class BookingException extends Exception {
public BookingException(String message) {
super(message);
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.api;
public interface CabBookingService {
Booking bookPickUp(Address pickUpLocation, Address dropOffLocation, int pax) throws BookingException;
}

View File

@ -0,0 +1,30 @@
<?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>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-remoting-http</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>spring-remoting-http-client</artifactId>
<description>Shows how to invoke a remote service using Spring Remoting.</description>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!-- companion modules -->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>api</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,25 @@
package com.baeldug.client;
import com.baeldung.api.*;
public class CabBookingClient {
private CabBookingService cabService;
public CabBookingClient(CabBookingService cabService) {
this.cabService = cabService;
}
public void run() {
Address pickUp = new Address("13 Seagate Blvd, Key Largo, FL 33037", "US");
Address dropDown = new Address("91831 Overseas Hwy, Tavernier, FL 33070", "US");
try {
System.out.println( cabService.bookPickUp(pickUp, dropDown, 3) );
} catch (BookingException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,34 @@
package com.baeldug.client;
import com.baeldung.api.CabBookingService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;
@Configuration
public class Main {
@Bean
public HttpInvokerProxyFactoryBean invoker() {
HttpInvokerProxyFactoryBean invoker = new HttpInvokerProxyFactoryBean();
invoker.setServiceUrl("http://localhost:9090/spring-remoting-http-server/booking");
invoker.setServiceInterface(CabBookingService.class);
return invoker;
}
@Bean
public CabBookingClient client(CabBookingService service){
return new CabBookingClient(service);
}
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext rootContext =
new AnnotationConfigApplicationContext();
rootContext.scan(Main.class.getPackage().getName());
rootContext.refresh();
CabBookingClient bean = rootContext.getBean(CabBookingClient.class);
bean.run();
}
}

View File

@ -0,0 +1,20 @@
<?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>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-remoting</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>spring-remoting-http</artifactId>
<description>Parent for all modules related to HTTP Spring Remoting</description>
<packaging>pom</packaging>
<modules>
<module>server</module>
<module>client</module>
<module>api</module>
</modules>
</project>

View File

@ -0,0 +1,65 @@
<?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>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-remoting-http</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<packaging>war</packaging>
<artifactId>spring-remoting-http-server</artifactId>
<description>Shows how to expose a service using Spring Remoting</description>
<properties>
<tomcat7-maven-plugin.version>2.2</tomcat7-maven-plugin.version>
</properties>
<dependencies>
<!-- spring -->
<!-- spring-webmvc is mainly needed to have access to the Spring's DispatcherServler -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- companion modules -->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>api</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>${tomcat7-maven-plugin.version}</version>
<configuration>
<port>9090</port>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,12 @@
Build and launch with the following command.
mvn clean package tomcat7:run-war
Exposed service is available at following URL.
http://localhost:9090/spring-remoting-http-server/account
## References
<http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#remoting-httpinvoker>

View File

@ -0,0 +1,10 @@
package com.baeldung.server;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CabBookingConfig {
}

View File

@ -0,0 +1,34 @@
package com.baeldung.server;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
public class CabBookingInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(CabBookingConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext =
new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.server;
import com.baeldung.api.Address;
import com.baeldung.api.Booking;
import com.baeldung.api.BookingException;
import com.baeldung.api.CabBookingService;
import java.util.Date;
import static java.lang.Math.random;
import static java.lang.System.currentTimeMillis;
import static java.util.UUID.randomUUID;
public class CabBookingServiceImpl implements CabBookingService {
@Override public Booking bookPickUp(Address pickUpLocation, Address dropOffLocation, int pax) throws BookingException {
if(random()<0.3){
throw new BookingException("Cab unavailable");
}
int tripTimeInMinutes = (int) (5 + random() * 15);
int costInCent = 15_00 + tripTimeInMinutes * 5 * pax;
Date pickUpDate = new Date((long) (currentTimeMillis() + (1000 * 60 * random() * 15)));
return new Booking(pickUpLocation, pickUpDate, dropOffLocation, costInCent, tripTimeInMinutes * 60,
randomUUID().toString());
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.server;
import com.baeldung.api.CabBookingService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter;
@Configuration
public class DispatcherConfig {
@Bean(name = "/booking") HttpInvokerServiceExporter accountService() {
HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
exporter.setService( new CabBookingServiceImpl() );
exporter.setServiceInterface( CabBookingService.class );
return exporter;
}
}

View File

@ -0,0 +1,27 @@
<configuration scan="true" scanPeriod="1 minute">
<variable
name="logPattern"
value="%-30(%d{MMM dd YYYY HH:mm:ss.SSS} [%thread]) %-5level %logger{5} [%file:%line] - %msg%n"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern>${logPattern}</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>C:\Users\danidemi\tmp\baledung\app.log</file>
<append>false</append>
<encoder>
<pattern>${logPattern}</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>
</configuration>

View File

@ -8,6 +8,7 @@
- [Thymeleaf: Custom Layout Dialect](http://www.baeldung.com/thymeleaf-spring-layouts)
- [Spring and Thymeleaf 3: Expressions](http://www.baeldung.com/spring-thymeleaf-3-expressions)
- [Spring MVC + Thymeleaf 3.0: New Features](http://www.baeldung.com/spring-thymeleaf-3)
- [How to Work with Dates in Thymeleaef](http://www.baeldung.com/dates-in-thymeleaf)
### Build the Project