This commit is contained in:
Thai Nguyen 2016-10-18 13:30:03 +07:00
commit fa33f0b4ac
143 changed files with 1334 additions and 802 deletions

View File

@ -1 +1,2 @@
### Relevant Articles:
- [Java Annotation Processing and Creating a Builder](http://www.baeldung.com/java-annotation-processing-builder)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf)

3
assertj/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [AssertJs Java 8 Features](http://www.baeldung.com/assertJ-java-8-features)
- [AssertJ for Guava](http://www.baeldung.com/assertJ-for-guava)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue)

2
cdi/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)

View File

@ -1 +1,2 @@
### Relevant Artiles:
- [Filtering a Stream of Optionals in Java](http://www.baeldung.com/java-filter-stream-of-optional)

View File

@ -13,3 +13,8 @@
- [Java Write to File](http://www.baeldung.com/java-write-to-file)
- [Java Scanner](http://www.baeldung.com/java-scanner)
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
- [Java Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer)
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)

View File

@ -1,211 +1,321 @@
<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-java</artifactId>
<version>0.1.0-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-java</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java</name>
<name>core-java</name>
<dependencies>
<dependencies>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>4.01</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>4.01</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.3</version>
</dependency>
<!-- web -->
<!-- web -->
<!-- marshalling -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- 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.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.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>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</dependencies>
<plugins>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
</configuration>
</plugin>
</build>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<!-- marshalling -->
<jackson.version>2.7.8</jackson.version>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<testng.version>6.8</testng.version>
<assertj.version>3.5.1</assertj.version>
</build>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- marshalling -->
<jackson.version>2.7.8</jackson.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
</properties>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<testng.version>6.8</testng.version>
<assertj.version>3.5.1</assertj.version>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,11 @@
package org.baeldung.executable;
import javax.swing.JOptionPane;
public class ExecutableMavenJar {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
}
}

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Wiring in Spring: @Autowired, @Resource and @Inject](http://www.baeldung.com/spring-annotations-resource-inject-autowire)

2
dozer/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [A Guide to Mapping With Dozer](http://www.baeldung.com/dozer)

View File

@ -3,3 +3,6 @@
This is the implementation of a [spring-hypermedia-api][1] client using Feign.
[1]: https://github.com/eugenp/spring-hypermedia-api
###Relevant Articles:
- [Intro to Feign](http://www.baeldung.com/intro-to-feign)

View File

@ -1 +1,2 @@
### Relevant Articles:
- [Database Migrations with Flyway](http://www.baeldung.com/database-migrations-with-flyway)

2
gatling/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Intro to Gatling](http://www.baeldung.com/introduction-to-gatling)

View File

@ -0,0 +1,6 @@
## Performance of Gson and Jackson
Standalone java programs to measure the performance of both JSON APIs based on file size and object graph complexity.
###Relevant Articles:
- [Jackson vs Gson: A Quick Look At Performance](http://www.baeldung.com/jackson-gson-performance)

View File

@ -5,3 +5,4 @@
### Relevant Articles:
- [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide)
- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson)

View File

@ -15,3 +15,4 @@
- [Guava Lists](http://www.baeldung.com/guava-lists)
- [Guava Sets](http://www.baeldung.com/guava-sets)
- [Guava Maps](http://www.baeldung.com/guava-maps)
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Cachable Static Assets with Spring MVC](http://www.baeldung.com/cachable-static-assets-with-spring-mvc)
- [Minification of JS and CSS Assets with Maven](http://www.baeldung.com/maven-minification-of-js-and-css-assets)

View File

@ -33,7 +33,7 @@ import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.junit.Test;
public class HttpAsyncClientTest {
public class HttpAsyncClientLiveTest {
private static final String HOST = "http://www.google.com";
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";

View File

@ -1,188 +0,0 @@
package org.baeldung.httpclient;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.junit.Ignore;
import org.junit.Test;
public class SandboxTest {
// original example
@Ignore
@Test
public final void whenInterestingDigestAuthScenario_then401UnAuthorized() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
final HttpHost targetHost = new HttpHost("httpbin.org", 80, "http");
// set up the credentials to run agains the server
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user", "passwd"));
// We need a first run to get a 401 to seed the digest auth
// Make a client using those creds
final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
// And make a call to the URL we are after
final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
// Create a context to use
final HttpClientContext context = HttpClientContext.create();
// Get a response from the sever (expect a 401!)
final HttpResponse authResponse = client.execute(targetHost, httpget, context);
// Pull out the auth header that came back from the server
final Header challenge = authResponse.getHeaders("WWW-Authenticate")[0];
// Lets use a digest scheme to solve it
final DigestScheme digest = new DigestScheme();
digest.processChallenge(challenge);
// Make a header with the solution based upon user/password and what the digest got out of the initial 401 reponse
final Header solution = digest.authenticate(new UsernamePasswordCredentials("user", "passwd"), httpget, context);
// Need an auth cache to use the new digest we made
final AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, digest);
// Add the authCache and thus solved digest to the context
context.setAuthCache(authCache);
// Pimp up our http get with the solved header made by the digest
httpget.addHeader(solution);
// use it!
System.out.println("Executing request " + httpget.getRequestLine() + " to target " + targetHost);
for (int i = 0; i < 3; i++) {
final CloseableHttpResponse responseGood = client.execute(targetHost, httpget, context);
try {
System.out.println("----------------------------------------");
System.out.println(responseGood.getStatusLine());
System.out.println(EntityUtils.toString(responseGood.getEntity()));
} finally {
responseGood.close();
}
}
}
@Test
public final void whenInterestingDigestAuthScenario_then200OK() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
final HttpHost targetHost = new HttpHost("httpbin.org", 80, "http");
// set up the credentials to run agains the server
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user", "passwd"));
// This endpoint need fake cookie to work properly
final CookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("fake", "fake_value");
cookie.setDomain("httpbin.org");
cookie.setPath("/");
cookieStore.addCookie(cookie);
// Make a client using those creds
final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credsProvider).build();
// And make a call to the URL we are after
final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
// Create a context to use
final HttpClientContext context = HttpClientContext.create();
// Get a response from the sever (401 implicitly)
final HttpResponse authResponse = client.execute(targetHost, httpget, context);
assertEquals(200, authResponse.getStatusLine().getStatusCode());
// HttpClient will use cached digest parameters for future requests
System.out.println("Executing request " + httpget.getRequestLine() + " to target " + targetHost);
for (int i = 0; i < 3; i++) {
final CloseableHttpResponse responseGood = client.execute(targetHost, httpget, context);
try {
System.out.println("----------------------------------------");
System.out.println(responseGood.getStatusLine());
assertEquals(200, responseGood.getStatusLine().getStatusCode());
} finally {
responseGood.close();
}
}
client.close();
}
// This test needs module spring-security-rest-digest-auth to be running
@Test
public final void whenWeKnowDigestParameters_thenNo401Status() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1Pass"));
final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1");
final HttpClientContext context = HttpClientContext.create();
// == make it preemptive
final AuthCache authCache = new BasicAuthCache();
final DigestScheme digestAuth = new DigestScheme();
digestAuth.overrideParamter("realm", "Custom Realm Name");
digestAuth.overrideParamter("nonce", "nonce value goes here");
authCache.put(targetHost, digestAuth);
context.setAuthCache(authCache);
// == end
System.out.println("Executing The Request knowing the digest parameters ==== ");
final HttpResponse authResponse = client.execute(targetHost, httpget, context);
assertEquals(200, authResponse.getStatusLine().getStatusCode());
client.close();
}
// This test needs module spring-security-rest-digest-auth to be running
@Test
public final void whenDoNotKnowParameters_thenOnlyOne401() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
final HttpClientContext context = HttpClientContext.create();
final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1Pass"));
final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1");
System.out.println("Executing The Request NOT knowing the digest parameters ==== ");
final HttpResponse tempResponse = client.execute(targetHost, httpget, context);
assertEquals(200, tempResponse.getStatusLine().getStatusCode());
for (int i = 0; i < 3; i++) {
System.out.println("No more Challenges or 401");
final CloseableHttpResponse authResponse = client.execute(targetHost, httpget, context);
assertEquals(200, authResponse.getStatusLine().getStatusCode());
authResponse.close();
}
client.close();
}
}

View File

@ -10,9 +10,11 @@ import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.junit.After;
import org.junit.Test;
@ -58,4 +60,14 @@ public class HttpClientSandboxLiveTest {
System.out.println(response.getStatusLine());
}
@Test
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException {
final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
final HttpGet httpGet = new HttpGet("https://sesar3.geoinfogeochem.org/sample/igsn/ODP000002");
httpGet.setHeader("Accept", "application/xml");
response = httpClient.execute(httpGet);
}
}

View File

@ -36,7 +36,7 @@ import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
public class HttpClientConnectionManagementTest {
public class HttpClientConnectionManagementLiveTest {
private static final String SERVER1 = "http://www.petrikainulainen.net/";
private static final String SERVER7 = "http://www.baeldung.com/";

3
hystrix/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Hystrix Integration with Existing Spring Application](http://www.baeldung.com/hystrix-integration-with-spring-aop)
- [Introduction to Hystrix](http://www.baeldung.com/introduction-to-hystrix)

2
immutables/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to Immutables](http://www.baeldung.com/immutables)

View File

@ -19,3 +19,8 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Jackson Decide What Fields Get Serialized/Deserializaed](http://www.baeldung.com/jackson-field-serializable-deserializable-or-not)
- [A Guide to Jackson Annotations](http://www.baeldung.com/jackson-annotations)
- [Working with Tree Model Nodes in Jackson](http://www.baeldung.com/jackson-json-node-tree-model)
- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson)
- [Intro to the Jackson ObjectMapper](http://www.baeldung.com/jackson-object-mapper-tutorial)
- [XML Serialization and Deserialization with Jackson](http://www.baeldung.com/jackson-xml-serialization-and-deserialization)
- [More Jackson Annotations](http://www.baeldung.com/jackson-advanced-annotations)
- [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance)

2
jee7schedule/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Scheduling in Java EE](http://www.baeldung.com/scheduling-in-java-enterprise-edition)

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

@ -0,0 +1,3 @@
### Relevant Articles:
- [Spring Boot Support for jOOQ](http://www.baeldung.com/spring-boot-support-for-jooq)
- [Introduction to jOOQ with Spring](http://www.baeldung.com/jooq-with-spring)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)

4
jsf/README.md Normal file
View File

@ -0,0 +1,4 @@
### Relevant Articles:
- [Introduction to JSF Expression Language 3.0](http://www.baeldung.com/jsf-expression-language-el-3)
- [Introduction to JSF EL 2](http://www.baeldung.com/intro-to-jsf-expression-language)
- [JavaServer Faces (JSF) with Spring](http://www.baeldung.com/spring-jsf)

View File

@ -5,3 +5,5 @@
### Relevant Articles:
- [Introduction to JSON Schema in Java](http://www.baeldung.com/introduction-to-json-schema-in-java)
- [A Guide to FastJson](http://www.baeldung.com/????????)
- [Introduction to JSONForms](http://www.baeldung.com/introduction-to-jsonforms)
- [Introduction to JsonPath](http://www.baeldung.com/guide-to-jayway-jsonpath)

2
junit5/REDAME.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [The Basics of JUnit 5 A Preview](http://www.baeldung.com/junit-5-preview)

2
log4j/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to Java Logging](http://www.baeldung.com/java-logging-intro)

2
lombok/README.md Normal file
View File

@ -0,0 +1,2 @@
## Relevant Articles:
- [Introduction to Project Lombok](http://www.baeldung.com/intro-to-project-lombok)

View File

@ -8,3 +8,5 @@
- [Mockito When/Then Cookbook](http://www.baeldung.com/mockito-behavior)
- [Mockito Using Spies](http://www.baeldung.com/mockito-spy)
- [Mockito @Mock, @Spy, @Captor and @InjectMocks](http://www.baeldung.com/mockito-annotations)
- [Mockitos Mock Methods](http://www.baeldung.com/mockito-mock-methods)
- [Introduction to PowerMock](http://www.baeldung.com/intro-to-powermock)

View File

@ -7,3 +7,4 @@
- [JMockit 101](http://www.baeldung.com/jmockit-101)
- [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations)
- [JMockit Advanced Topics](http://www.baeldung.com/jmockit-advanced-topics)
- [JMockit Advanced Usage](http://www.baeldung.com/jmockit-advanced-usage)

View File

@ -4,3 +4,5 @@
### Relevant Articles:
- [Introduction to Mutation Testing Using the PITest Library](http://www.baeldung.com/java-mutation-testing-with-pitest)
- [Intro to JaCoCo](http://www.baeldung.com/jacoco)
- [Mutation Testing with PITest](http://www.baeldung.com/java-mutation-testing-with-pitest)

View File

@ -1,44 +0,0 @@
<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>org.baeldung.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${com.squareup.okhttp3.version}</version>
</dependency>
<!-- test scoped -->
<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>
</dependencies>
<properties>
<!-- okhttp -->
<com.squareup.okhttp3.version>3.4.1</com.squareup.okhttp3.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
</properties>
</project>

View File

@ -1,113 +0,0 @@
package org.baeldung.okhttp;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpMiscTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest";
//@Test
public void whenSetRequestTimeoutUsingOkHttp_thenFail() throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
//.connectTimeout(10, TimeUnit.SECONDS)
//.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(1, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
.build();
Call call = client.newCall(request);
Response response = call.execute();
response.close();
}
//@Test
public void whenCancelRequestUsingOkHttp_thenCorrect() throws IOException {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
.build();
final int seconds = 1;
//final int seconds = 3;
final long startNanos = System.nanoTime();
final Call call = client.newCall(request);
// Schedule a job to cancel the call in 1 second.
executor.schedule(new Runnable() {
public void run() {
System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
call.cancel();
System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f);
}
}, seconds, TimeUnit.SECONDS);
try {
System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
Response response = call.execute();
System.out.printf("%.2f Call was expected to fail, but completed: %s%n", (System.nanoTime() - startNanos) / 1e9f, response);
} catch (IOException e) {
System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e);
}
}
@Test
public void whenSetResponseCacheUsingOkHttp_thenCorrect() throws IOException {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
File cacheDirectory = new File("src/test/resources/cache");
Cache cache = new Cache(cacheDirectory, cacheSize);
OkHttpClient client = new OkHttpClient.Builder()
.cache(cache)
.build();
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
//.cacheControl(CacheControl.FORCE_NETWORK)
//.cacheControl(CacheControl.FORCE_CACHE)
.build();
Response response1 = client.newCall(request).execute();
String responseBody1 = response1.body().string();
System.out.println("Response 1 response: " + response1);
System.out.println("Response 1 cache response: " + response1.cacheResponse());
System.out.println("Response 1 network response: " + response1.networkResponse());
System.out.println("Response 1 responseBody: " + responseBody1);
Response response2 = client.newCall(request).execute();
String responseBody2 = response2.body().string();
System.out.println("Response 2 response: " + response2);
System.out.println("Response 2 cache response: " + response2.cacheResponse());
System.out.println("Response 2 network response: " + response2.networkResponse());
System.out.println("Response 2 responseBody: " + responseBody2);
}
}

2
orika/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Mapping with Orika](http://www.baeldung.com/orika-mapping)

View File

@ -18,7 +18,7 @@
<module>apache-cxf</module>
<!-- <module>apache-fop</module> --> <!-- TODO: has a compilation issue -->
<module>autovalue-tutorial</module>
<module>cdi</module>
<module>core-java</module>
<module>core-java-8</module>
@ -68,7 +68,6 @@
<module>rest-assured</module>
<module>rest-testing</module>
<module>resteasy</module>
<module>okhttp</module>
<module>spring-all</module>
<module>spring-akka</module>

2
querydsl/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Intro to Querydsl](http://www.baeldung.com/intro-to-querydsl)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Eliminate Redundancies in RAML with Resource Types and Traits](http://www.baeldung.com/simple-raml-with-resource-types-and-traits)

View File

@ -0,0 +1,2 @@
###Relevant Articles:
- [A Guide to REST-assured](http://www.baeldung.com/rest-assured-tutorial)

View File

@ -7,3 +7,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Test a REST API with Java](http://www.baeldung.com/2011/10/13/integration-testing-a-rest-api/)
- [Introduction to WireMock](http://www.baeldung.com/introduction-to-wiremock)
- [REST API Testing with Cucumber](http://www.baeldung.com/cucumber-rest-api-testing)

2
sockets/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)

2
spring-akka/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to Spring with Akka](http://www.baeldung.com/akka-with-spring)

View File

@ -12,3 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Spring Profiles](http://www.baeldung.com/spring-profiles)
- [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor)
- [What's New in Spring 4.3?](http://www.baeldung.com/whats-new-in-spring-4-3/)
- [Guide To Running Logic on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring)
- [Quick Guide to Spring Controllers](http://www.baeldung.com/spring-controllers)
- [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes)

View File

@ -0,0 +1,43 @@
package org.baeldung.ehcache;
import static org.junit.Assert.*;
import org.baeldung.ehcache.calculator.SquaredCalculator;
import org.baeldung.ehcache.config.CacheHelper;
import org.junit.Before;
import org.junit.Test;
public class SquareCalculatorTest {
SquaredCalculator squaredCalculator = new SquaredCalculator();
CacheHelper cacheHelper = new CacheHelper();
@Before
public void setup() {
squaredCalculator.setCache(cacheHelper);
}
@Test
public void whenCalculatingSquareValueOnce_thenCacheDontHaveValues() {
for (int i = 10; i < 15; i++) {
assertFalse(cacheHelper.getSquareNumberCache().containsKey(i));
System.out.println("Square value of " + i + " is: "
+ squaredCalculator.getSquareValueOfNumber(i) + "\n");
}
}
@Test
public void whenCalculatingSquareValueAgain_thenCacheHasAllValues() {
for (int i = 10; i < 15; i++) {
assertFalse(cacheHelper.getSquareNumberCache().containsKey(i));
System.out.println("Square value of " + i + " is: "
+ squaredCalculator.getSquareValueOfNumber(i) + "\n");
}
for (int i = 10; i < 15; i++) {
assertTrue(cacheHelper.getSquareNumberCache().containsKey(i));
System.out.println("Square value of " + i + " is: "
+ squaredCalculator.getSquareValueOfNumber(i) + "\n");
}
}
}

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Guide to Spring @Autowired](http://www.baeldung.com/spring-autowire)

View File

@ -1,2 +1,7 @@
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
###Relevant Articles:
- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot)
- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters)
- [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information)

View File

@ -1 +1,3 @@
### Relevant Articles:
- [Batch Processing with Spring Cloud Data Flow](http://www.baeldung.com/spring-cloud-data-flow-batch-processing)
- [Getting Started with Stream Processing with Spring Cloud Data Flow](http://www.baeldung.com/spring-cloud-data-flow-stream-processing)

View File

@ -1 +1,2 @@
### Relevant Articles:
- [Spring Cloud Bootstrapping](http://www.baeldung.com/spring-cloud-bootstrapping)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to Spring Cloud Netflix Eureka](http://www.baeldung.com/spring-cloud-netflix-eureka)

View File

@ -1 +1,2 @@
### Relevant Articles:
- [A Guide to Spring Cloud Netflix Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Cucumber Spring Integration](http://www.baeldung.com/cucumber-spring-integration)

View File

@ -1,6 +1,10 @@
## Spring Data Elasticsearch
- [Introduction to Spring Data Elasticsearch](http://www.baeldung.com/spring-data-elasticsearch-tutorial)
###Relevant Articles:
- [Elasticsearch Queries with Spring Data](http://www.baeldung.com/spring-data-elasticsearch-queries)
- [Guide to Elasticsearch in Java](http://www.baeldung.com/elasticsearch-java)
### Build the Project with Tests Running
```
mvn clean install

View File

@ -11,8 +11,9 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<org.springframework.data.version>1.3.2.RELEASE</org.springframework.data.version>
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
<junit.version>4.11</junit.version>
@ -27,6 +28,12 @@
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
@ -39,16 +46,13 @@
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency> <groupId>net.java.dev.jna</groupId>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>4.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
@ -81,16 +85,5 @@
<version>1.2.13</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
</project>

View File

@ -32,18 +32,22 @@ public class Config {
public Client client() {
try {
final Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data");
logger.debug(tmpDir.toAbsolutePath().toString());
// @formatter:off
final Settings.Builder elasticsearchSettings =
Settings.settingsBuilder().put("http.enabled", "false")
.put("path.data", tmpDir.toAbsolutePath().toString())
.put("path.home", elasticsearchHome);
return new NodeBuilder()
.local(true)
.settings(elasticsearchSettings)
.node()
.client();
// @formatter:on
logger.debug(tmpDir.toAbsolutePath().toString());
return new NodeBuilder().local(true).settings(elasticsearchSettings.build()).node().client();
} catch (final IOException ioex) {
logger.error("Cannot create temp dir", ioex);
throw new RuntimeException();

View File

@ -10,10 +10,10 @@ import org.springframework.stereotype.Service;
@Service
public class ArticleServiceImpl implements ArticleService {
private ArticleRepository articleRepository;
private final ArticleRepository articleRepository;
@Autowired
public void setArticleRepository(ArticleRepository articleRepository) {
public ArticleServiceImpl(ArticleRepository articleRepository) {
this.articleRepository = articleRepository;
}

View File

@ -8,10 +8,10 @@
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="com.baeldung.config" level="DEBUG" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<!-- in order to debug some elastic issues, this needs to be DEBUG or INFO -->
<logger name="org.elasticsearch" level="INFO" />
<logger name="com.baeldung.spring" level="DEBUG" />
<root level="INFO">
<appender-ref ref="STDOUT" />

View File

@ -34,7 +34,6 @@ import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilde
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.spring.data.es.config.Config;
import com.baeldung.spring.data.es.model.Article;
@ -42,7 +41,7 @@ import com.baeldung.spring.data.es.model.Author;
import com.baeldung.spring.data.es.service.ArticleService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Config.class }, loader = AnnotationConfigContextLoader.class)
@ContextConfiguration(classes = Config.class)
public class ElasticSearchQueryTest {
@Autowired

View File

@ -21,7 +21,6 @@ import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilde
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.spring.data.es.config.Config;
import com.baeldung.spring.data.es.model.Article;
@ -29,7 +28,7 @@ import com.baeldung.spring.data.es.model.Author;
import com.baeldung.spring.data.es.service.ArticleService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Config.class }, loader = AnnotationConfigContextLoader.class)
@ContextConfiguration(classes = Config.class)
public class ElasticSearchTest {
@Autowired

View File

@ -2,6 +2,7 @@
### Relevant Articles:
- [Introduction to Spring Data Redis](http://www.baeldung.com/spring-data-redis-tutorial)
- [PubSub Messaging with Spring Data Redis](http://www.baeldung.com/spring-data-redis-pub-sub)
### Build the Project with Tests Running
```

View File

@ -12,3 +12,6 @@ The application uses [Spring Boot](http://projects.spring.io/spring-boot/), so i
# Viewing the running application
To view the running application, visit [http://localhost:8080](http://localhost:8080) in your browser
###Relevant Articles:
- [Guide to Spring Data REST Validators](http://www.baeldung.com/spring-data-rest-validators)

View File

@ -10,3 +10,4 @@ This project is used to replicate Spring Exceptions only.
- [Spring DataIntegrityViolationException](http://www.baeldung.com/spring-dataIntegrityviolationexception)
- [Spring BeanDefinitionStoreException](http://www.baeldung.com/spring-beandefinitionstoreexception)
- [Spring NoSuchBeanDefinitionException](http://www.baeldung.com/spring-nosuchbeandefinitionexception)
- [Guide to Spring NonTransientDataAccessException](http://www.baeldung.com/nontransientdataaccessexception)

View File

@ -10,6 +10,8 @@
- [Auditing with JPA, Hibernate, and Spring Data JPA](http://www.baeldung.com/database-auditing-jpa)
- [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial)
- [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate/)
- [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading)
- [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries)
### Quick Start

View File

@ -10,3 +10,5 @@
- [JPA Pagination](http://www.baeldung.com/jpa-pagination)
- [Sorting with JPA](http://www.baeldung.com/jpa-sort)
- [Spring JPA Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases)
- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache)
- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource)

View File

@ -3,11 +3,12 @@
<groupId>org.springframework.samples</groupId>
<artifactId>spring-katharsis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.6.RELEASE</version>
<version>1.3.3.RELEASE</version>
</parent>
<dependencies>
@ -62,6 +63,7 @@
<java.version>1.8</java.version>
<katharsis.version>1.0.0</katharsis.version>
<restassured.version>2.4.0</restassured.version>
<cargo-maven2-plugin.version>1.6.0</cargo-maven2-plugin.version>
</properties>
@ -71,7 +73,100 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
</systemPropertyVariables>
</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>tomcat8x</containerId>
<type>embedded</type>
<systemProperties>
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<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>
<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>none</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
<systemPropertyVariables>
<webTarget>cargo</webTarget>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -2,9 +2,10 @@ package org.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
@SpringBootApplication
public class Application {
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);

View File

@ -3,4 +3,7 @@ spring.datasource.username = sa
spring.datasource.password =
spring.jpa.show-sql = false
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
server.port=8082
server.context-path=/spring-katharsis

View File

@ -2,22 +2,14 @@ package org.baeldung.test;
import static org.junit.Assert.assertEquals;
import org.baeldung.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.response.Response;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class JsonApiLiveTest {
private final static String URL_PREFIX = "http://localhost:8080/users";
private final static String URL_PREFIX = "http://localhost:8082/spring-katharsis/users";
@Test
public void whenGettingAllUsers_thenCorrect() {

View File

@ -10,3 +10,9 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Introduction to Pointcut Expressions in Spring](http://www.baeldung.com/spring-aop-pointcut-tutorial)
- [Introduction to Advice Types in Spring](http://www.baeldung.com/spring-aop-advice-tutorial)
- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial)
- [Integration Testing in Spring](http://www.baeldung.com/integration-testing-in-spring)
- [Spring JSON-P with Jackson](http://www.baeldung.com/spring-jackson-jsonp)
- [A Quick Guide to Spring MVC Matrix Variables](http://www.baeldung.com/spring-mvc-matrix-variables)
- [Intro to WebSockets with Spring](http://www.baeldung.com/websockets-spring)
- [File Upload with Spring MVC](http://www.baeldung.com/spring-file-upload)
- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [WebAppConfiguration in Spring Tests](http://www.baeldung.com/spring-webappconfiguration)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Quick Guide to Spring MVC with Velocity](http://www.baeldung.com/spring-mvc-with-velocity)

View File

@ -1 +1,2 @@
### Relevant Articles:
- [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config)

View File

@ -146,17 +146,64 @@
</dependencyManagement>
<build>
<finalName>spring-mvc-web-vs-initializer</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<build>
<finalName>spring-mvc-web-vs-initializer</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<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>
</plugins>
</build>
<profiles>
<profile>
<id>integration</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>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- Spring -->
<org.springframework.version>4.3.1.RELEASE</org.springframework.version>

View File

@ -20,7 +20,7 @@ import org.springframework.web.servlet.ModelAndView;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(loader=AnnotationConfigWebContextLoader.class, classes = MvcConfig.class)
public class JavaServletTest {
public class JavaServletIntegrationTest {
private MockMvc mockMvc;

View File

@ -19,7 +19,7 @@ import org.springframework.web.servlet.ModelAndView;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(loader=GenericXmlWebContextLoader.class, locations = "classpath*:mvc-configuration.xml")
public class XmlServletTest {
public class XmlServletIntegrationTest {
private MockMvc mockMvc;

View File

@ -11,3 +11,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Spring MVC Tutorial](http://www.baeldung.com/spring-mvc-tutorial)
- [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout)
- [Basic Forms with Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial)
- [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Spring REST API with Protocol Buffers](http://www.baeldung.com/spring-rest-api-with-protocol-buffers)

View File

@ -37,7 +37,6 @@
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
</dependencies>
@ -47,12 +46,57 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</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>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest
public class ApplicationTest {
public class ApplicationIntegrationTest {
private static final String COURSE1_URL = "http://localhost:8080/courses/1";

View File

@ -71,30 +71,75 @@
</dependency>
</dependencies>
<build>
<finalName>angular-spring-rest-sample</finalName>
<plugins>
<build>
<finalName>angular-spring-rest-sample</finalName>
<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>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</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>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<guava.version>19.0</guava.version>
</properties>

View File

@ -18,7 +18,7 @@ import static org.hamcrest.core.IsEqual.*;
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("server.port:8888")
public class StudentServiceTest {
public class StudentServiceIntegrationTest {
private static final String ENDPOINT = "http://localhost:8888/student/get";

View File

@ -1,2 +1,5 @@
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
###Relevant Articles:
- [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs)

View File

@ -1,12 +1,12 @@
=========
## Spring REST Example Project
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
### Relevant Articles:
- [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping)
- [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest)
- [Redirect in Spring](http://www.baeldung.com/spring-redirect-and-forward)
- [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code)
- [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp)
- [Binary Data Formats in a Spring REST API](http://www.baeldung.com/spring-rest-api-with-binary-data-formats)

View File

@ -15,7 +15,7 @@
<dependencies>
<!-- Spring Boot Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
@ -71,7 +71,7 @@
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
@ -118,6 +118,14 @@
<artifactId>log4j-over-slf4j</artifactId>
</dependency>
<!-- okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${com.squareup.okhttp3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
@ -153,14 +161,14 @@
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
</dependency>
<!-- -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.esotericsoftware</groupId>
<artifactId>kryo</artifactId>
@ -198,7 +206,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
@ -285,7 +293,7 @@
</build>
</profile>
</profiles>
<properties>
<!-- Spring -->
@ -320,6 +328,9 @@
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<cargo-maven2-plugin.version>1.6.0</cargo-maven2-plugin.version>
<!-- okhttp -->
<com.squareup.okhttp3.version>3.4.1</com.squareup.okhttp3.version>
</properties>
</project>

View File

@ -18,12 +18,12 @@ import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class OkHttpFileUploadingTest {
public class OkHttpFileUploadingLiveTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest";
@Test
public void whenUploadFileUsingOkHttp_thenCorrect() throws IOException {
public void whenUploadFile_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();
@ -45,7 +45,7 @@ public class OkHttpFileUploadingTest {
}
@Test
public void whenGetUploadFileProgressUsingOkHttp_thenCorrect() throws IOException {
public void whenGetUploadFileProgress_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();

View File

@ -14,12 +14,12 @@ import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpGetTest {
public class OkHttpGetLiveTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest";
@Test
public void whenGetRequestUsingOkHttp_thenCorrect() throws IOException {
public void whenGetRequest_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();
@ -34,7 +34,7 @@ public class OkHttpGetTest {
}
@Test
public void whenGetRequestWithQueryParameterUsingOkHttp_thenCorrect() throws IOException {
public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();
@ -54,7 +54,7 @@ public class OkHttpGetTest {
}
@Test
public void whenAsynchronousGetRequestUsingOkHttp_thenCorrect() {
public void whenAsynchronousGetRequest_thenCorrect() {
OkHttpClient client = new OkHttpClient();

View File

@ -9,12 +9,12 @@ import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpHeaderTest {
public class OkHttpHeaderLiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
@Test
public void whenSetHeaderUsingOkHttp_thenCorrect() throws IOException {
public void whenSetHeader_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();
@ -29,7 +29,7 @@ public class OkHttpHeaderTest {
}
@Test
public void whenSetDefaultHeaderUsingOkHttp_thenCorrect() throws IOException {
public void whenSetDefaultHeader_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new DefaultContentTypeInterceptor("application/json"))

View File

@ -0,0 +1,107 @@
package org.baeldung.okhttp;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpMiscLiveTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest";
private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class);
@Test
public void whenSetRequestTimeout_thenFail() throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(1, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
.build();
Call call = client.newCall(request);
Response response = call.execute();
response.close();
}
@Test
public void whenCancelRequest_thenCorrect() throws IOException {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
.build();
final int seconds = 1;
final long startNanos = System.nanoTime();
final Call call = client.newCall(request);
// Schedule a job to cancel the call in 1 second.
executor.schedule(new Runnable() {
public void run() {
logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f);
call.cancel();
logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f);
}
}, seconds, TimeUnit.SECONDS);
try {
logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f);
Response response = call.execute();
logger.debug("Call was expected to fail, but completed: " + (System.nanoTime() - startNanos) / 1e9f, response);
} catch (IOException e) {
logger.debug("Call failed as expected: " + (System.nanoTime() - startNanos) / 1e9f, e);
}
}
@Test
public void whenSetResponseCache_thenCorrect() throws IOException {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
File cacheDirectory = new File("src/test/resources/cache");
Cache cache = new Cache(cacheDirectory, cacheSize);
OkHttpClient client = new OkHttpClient.Builder()
.cache(cache)
.build();
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
Response response1 = client.newCall(request).execute();
logResponse(response1);
Response response2 = client.newCall(request).execute();
logResponse(response2);
}
private void logResponse(Response response) throws IOException {
logger.debug("Response response: " + response);
logger.debug("Response cache response: " + response.cacheResponse());
logger.debug("Response network response: " + response.networkResponse());
logger.debug("Response responseBody: " + response.body().string());
}
}

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