From a8b3f44a2fd25918d25d0237c27d2c77080f67e5 Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Fri, 7 Oct 2016 17:31:28 +0200 Subject: [PATCH 1/7] Code improvement --- okhttp/pom.xml | 98 ++++++++++++------- .../okhttp/ProgressRequestWrapper.java | 10 +- .../okhttp/OkHttpFileUploadingTest.java | 4 +- .../org/baeldung/okhttp/OkHttpGetTest.java | 6 +- .../org/baeldung/okhttp/OkHttpHeaderTest.java | 4 +- .../org/baeldung/okhttp/OkHttpMiscTest.java | 54 +++++----- .../baeldung/okhttp/OkHttpPostingTest.java | 8 +- .../baeldung/okhttp/OkHttpRedirectTest.java | 2 +- 8 files changed, 111 insertions(+), 75 deletions(-) diff --git a/okhttp/pom.xml b/okhttp/pom.xml index ba5bcf9725..4d371f40b0 100644 --- a/okhttp/pom.xml +++ b/okhttp/pom.xml @@ -1,44 +1,76 @@ - - 4.0.0 - org.baeldung.okhttp - okhttp - 0.0.1-SNAPSHOT + + 4.0.0 + org.baeldung.okhttp + okhttp + 0.0.1-SNAPSHOT - + - - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - + - - - junit - junit - ${junit.version} - test - + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + - + + org.slf4j + slf4j-api + ${org.slf4j.version} + - + + ch.qos.logback + logback-classic + ${logback.version} + - - 3.4.1 + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + - - 1.3 - 4.12 - + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + junit + junit + ${junit.version} + test + + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + + + + + 3.4.1 + + + 1.7.13 + 1.1.3 + + + 1.3 + 4.12 + + diff --git a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java b/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java index 6a98f8d20a..255d10b98a 100644 --- a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java +++ b/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java @@ -1,11 +1,16 @@ package org.baeldung.okhttp; -import okhttp3.MediaType; import okhttp3.RequestBody; -import okio.*; +import okhttp3.MediaType; import java.io.IOException; +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + public class ProgressRequestWrapper extends RequestBody { protected RequestBody delegate; @@ -61,6 +66,7 @@ public class ProgressRequestWrapper extends RequestBody { } public interface ProgressListener { + void onRequestProgress(long bytesWritten, long contentLength); } diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java index 32457fc11b..77219b8e22 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java @@ -23,7 +23,7 @@ public class OkHttpFileUploadingTest { 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(); diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java index e8edff92df..de954e3dd7 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java @@ -19,7 +19,7 @@ public class OkHttpGetTest { 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(); diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java index 5b2e89eca8..958eeb51ce 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java @@ -14,7 +14,7 @@ public class OkHttpHeaderTest { 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")) diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java index 829bafe8ef..b72b461158 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java @@ -7,6 +7,8 @@ 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; @@ -17,13 +19,12 @@ import okhttp3.Response; public class OkHttpMiscTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static Logger logger = LoggerFactory.getLogger(OkHttpMiscTest.class); //@Test - public void whenSetRequestTimeoutUsingOkHttp_thenFail() throws IOException { + public void whenSetRequestTimeout_thenFail() throws IOException { OkHttpClient client = new OkHttpClient.Builder() - //.connectTimeout(10, TimeUnit.SECONDS) - //.writeTimeout(10, TimeUnit.SECONDS) .readTimeout(1, TimeUnit.SECONDS) .build(); @@ -36,8 +37,8 @@ public class OkHttpMiscTest { response.close(); } - //@Test - public void whenCancelRequestUsingOkHttp_thenCorrect() throws IOException { + @Test + public void whenCancelRequest_thenCorrect() throws IOException { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); @@ -48,7 +49,6 @@ public class OkHttpMiscTest { .build(); final int seconds = 1; - //final int seconds = 3; final long startNanos = System.nanoTime(); final Call call = client.newCall(request); @@ -57,57 +57,55 @@ public class OkHttpMiscTest { executor.schedule(new Runnable() { public void run() { - System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f); + logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f); call.cancel(); - System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f); + logger.debug("Canceled call: " + (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); + 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) { - System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e); + logger.debug("Call failed as expected: " + (System.nanoTime() - startNanos) / 1e9f, e); } } - @Test - public void whenSetResponseCacheUsingOkHttp_thenCorrect() throws IOException { + //@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(); + .cache(cache) + .build(); Request request = new Request.Builder() - .url("http://publicobject.com/helloworld.txt") - //.cacheControl(CacheControl.FORCE_NETWORK) - //.cacheControl(CacheControl.FORCE_CACHE) - .build(); + .url("http://publicobject.com/helloworld.txt") + .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); + logger.debug("Response 1 response: " + response1); + logger.debug("Response 1 cache response: " + response1.cacheResponse()); + logger.debug("Response 1 network response: " + response1.networkResponse()); + logger.debug("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); + logger.debug("Response 2 response: " + response2); + logger.debug("Response 2 cache response: " + response2.cacheResponse()); + logger.debug("Response 2 network response: " + response2.networkResponse()); + logger.debug("Response 2 responseBody: " + responseBody2); } } diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java index 1ba2d517c5..41a024d2ee 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java @@ -24,7 +24,7 @@ public class OkHttpPostingTest { private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; @Test - public void whenSendPostRequestUsingOkHttp_thenCorrect() throws IOException { + public void whenSendPostRequest_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -45,7 +45,7 @@ public class OkHttpPostingTest { } @Test - public void whenSendPostRequestWithAuthorizationUsingOkHttp_thenCorrect() throws IOException { + public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException { String postBody = "test post"; @@ -64,7 +64,7 @@ public class OkHttpPostingTest { } @Test - public void whenPostJsonUsingOkHttp_thenCorrect() throws IOException { + public void whenPostJson_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -84,7 +84,7 @@ public class OkHttpPostingTest { } @Test - public void whenSendMultipartRequestUsingOkHttp_thenCorrect() throws IOException { + public void whenSendMultipartRequest_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java index 1582a5ff7f..c709253478 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java @@ -15,7 +15,7 @@ import okhttp3.Response; public class OkHttpRedirectTest { @Test - public void whenSetFollowRedirectsUsingOkHttp_thenNotRedirected() throws IOException { + public void whenSetFollowRedirects_thenNotRedirected() throws IOException { OkHttpClient client = new OkHttpClient().newBuilder() .followRedirects(false) From 8692cad3282d0d8e72170bfa8720bb57ea98dd95 Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Fri, 7 Oct 2016 17:47:58 +0200 Subject: [PATCH 2/7] Code improvement --- .../org/baeldung/okhttp/OkHttpMiscTest.java | 24 ++++++++----------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java index b72b461158..fe15a76200 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java @@ -21,7 +21,7 @@ public class OkHttpMiscTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; private static Logger logger = LoggerFactory.getLogger(OkHttpMiscTest.class); - //@Test + @Test public void whenSetRequestTimeout_thenFail() throws IOException { OkHttpClient client = new OkHttpClient.Builder() @@ -75,7 +75,7 @@ public class OkHttpMiscTest { } } - //@Test + @Test public void whenSetResponseCache_thenCorrect() throws IOException { int cacheSize = 10 * 1024 * 1024; // 10 MiB @@ -91,21 +91,17 @@ public class OkHttpMiscTest { .build(); Response response1 = client.newCall(request).execute(); - - String responseBody1 = response1.body().string(); - - logger.debug("Response 1 response: " + response1); - logger.debug("Response 1 cache response: " + response1.cacheResponse()); - logger.debug("Response 1 network response: " + response1.networkResponse()); - logger.debug("Response 1 responseBody: " + responseBody1); + logResponse(response1); Response response2 = client.newCall(request).execute(); + logResponse(response2); + } - String responseBody2 = response2.body().string(); + private void logResponse(Response response) throws IOException { - logger.debug("Response 2 response: " + response2); - logger.debug("Response 2 cache response: " + response2.cacheResponse()); - logger.debug("Response 2 network response: " + response2.networkResponse()); - logger.debug("Response 2 responseBody: " + responseBody2); + 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()); } } From 453b739f6c11cf7c28102f810ac734d956a02f2f Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Tue, 11 Oct 2016 10:38:51 +0200 Subject: [PATCH 3/7] Add OkHttp example --- spring-rest/pom.xml | 23 +++- .../okhttp/DefaultContentTypeInterceptor.java | 26 +++++ .../okhttp/OkHttpFileUploadingTest.java | 81 +++++++++++++ .../org/baeldung/okhttp/OkHttpGetTest.java | 78 +++++++++++++ .../org/baeldung/okhttp/OkHttpHeaderTest.java | 48 ++++++++ .../org/baeldung/okhttp/OkHttpMiscTest.java | 107 +++++++++++++++++ .../baeldung/okhttp/OkHttpPostingTest.java | 109 ++++++++++++++++++ .../baeldung/okhttp/OkHttpRedirectTest.java | 33 ++++++ .../okhttp/ProgressRequestWrapper.java | 74 ++++++++++++ spring-rest/src/test/resources/test.txt | 1 + 10 files changed, 574 insertions(+), 6 deletions(-) create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java create mode 100644 spring-rest/src/test/resources/test.txt diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 18cb1dc72a..69ab4ed361 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -15,7 +15,7 @@ - + org.springframework.boot spring-boot-starter-thymeleaf @@ -71,7 +71,7 @@ com.fasterxml.jackson.core jackson-databind - + com.fasterxml.jackson.dataformat jackson-dataformat-xml @@ -118,6 +118,14 @@ log4j-over-slf4j + + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + + @@ -153,14 +161,14 @@ rest-assured ${rest-assured.version} - + com.google.protobuf protobuf-java 2.6.1 - + com.esotericsoftware kryo @@ -198,7 +206,7 @@ maven-surefire-plugin - **/*LiveTest.java + **/*LiveTest.java @@ -285,7 +293,7 @@ - + @@ -320,6 +328,9 @@ 2.19.1 1.6.0 + + 3.4.1 + diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java b/spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java new file mode 100644 index 0000000000..2a33a1febd --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java @@ -0,0 +1,26 @@ +package org.baeldung.okhttp; + +import java.io.IOException; + +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +public class DefaultContentTypeInterceptor implements Interceptor { + + private final String contentType; + + public DefaultContentTypeInterceptor(String contentType) { + this.contentType = contentType; + } + + public Response intercept(Interceptor.Chain chain) throws IOException { + + Request originalRequest = chain.request(); + Request requestWithUserAgent = originalRequest.newBuilder() + .header("Content-Type", contentType) + .build(); + + return chain.proceed(requestWithUserAgent); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java new file mode 100644 index 0000000000..77219b8e22 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java @@ -0,0 +1,81 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.IOException; + +import org.baeldung.okhttp.ProgressRequestWrapper; +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +public class OkHttpFileUploadingTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + + @Test + public void whenUploadFile_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("file", "file.txt", + RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/upload") + .post(requestBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenGetUploadFileProgress_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("file", "file.txt", + RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) + .build(); + + + ProgressRequestWrapper.ProgressListener listener = new ProgressRequestWrapper.ProgressListener() { + + public void onRequestProgress(long bytesWritten, long contentLength) { + + float percentage = 100f * bytesWritten / contentLength; + assertFalse(Float.compare(percentage, 100) > 0); + } + }; + + ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, listener); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/upload") + .post(countingBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java new file mode 100644 index 0000000000..de954e3dd7 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java @@ -0,0 +1,78 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpGetTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + + @Test + public void whenGetRequest_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(BASE_URL + "/date") + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); + urlBuilder.addQueryParameter("id", "1"); + + String url = urlBuilder.build().toString(); + + Request request = new Request.Builder() + .url(url) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenAsynchronousGetRequest_thenCorrect() { + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(BASE_URL + "/date") + .build(); + + Call call = client.newCall(request); + + call.enqueue(new Callback() { + + public void onResponse(Call call, Response response) throws IOException { + assertThat(response.code(), equalTo(200)); + } + + public void onFailure(Call call, IOException e) { + + } + }); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java new file mode 100644 index 0000000000..958eeb51ce --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java @@ -0,0 +1,48 @@ +package org.baeldung.okhttp; + +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpHeaderTest { + + private static final String SAMPLE_URL = "http://www.github.com"; + + @Test + public void whenSetHeader_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(SAMPLE_URL) + .addHeader("Content-Type", "application/json") + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + response.close(); + } + + @Test + public void whenSetDefaultHeader_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient.Builder() + .addInterceptor(new DefaultContentTypeInterceptor("application/json")) + .build(); + + Request request = new Request.Builder() + .url(SAMPLE_URL) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + response.close(); + } + + +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java new file mode 100644 index 0000000000..fe15a76200 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java @@ -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 OkHttpMiscTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static Logger logger = LoggerFactory.getLogger(OkHttpMiscTest.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()); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java new file mode 100644 index 0000000000..41a024d2ee --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java @@ -0,0 +1,109 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.Credentials; +import okhttp3.FormBody; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +public class OkHttpPostingTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; + + @Test + public void whenSendPostRequest_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody formBody = new FormBody.Builder() + .add("username", "test") + .add("password", "test") + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/users") + .post(formBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException { + + String postBody = "test post"; + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(URL_SECURED_BY_BASIC_AUTHENTICATION) + .addHeader("Authorization", Credentials.basic("test", "test")) + .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody)) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenPostJson_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + String json = "{\"id\":1,\"name\":\"John\"}"; + + RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/detail") + .post(body) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenSendMultipartRequest_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("username", "test") + .addFormDataPart("password", "test") + .addFormDataPart("file", "file.txt", + RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/multipart") + .post(requestBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java new file mode 100644 index 0000000000..c709253478 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java @@ -0,0 +1,33 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpRedirectTest { + + @Test + public void whenSetFollowRedirects_thenNotRedirected() throws IOException { + + OkHttpClient client = new OkHttpClient().newBuilder() + .followRedirects(false) + .build(); + + Request request = new Request.Builder() + .url("http://t.co/I5YYd9tddw") + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(301)); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java b/spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java new file mode 100644 index 0000000000..255d10b98a --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java @@ -0,0 +1,74 @@ +package org.baeldung.okhttp; + +import okhttp3.RequestBody; +import okhttp3.MediaType; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestWrapper extends RequestBody { + + protected RequestBody delegate; + protected ProgressListener listener; + + protected CountingSink countingSink; + + public ProgressRequestWrapper(RequestBody delegate, ProgressListener listener) { + this.delegate = delegate; + this.listener = listener; + } + + @Override + public MediaType contentType() { + return delegate.contentType(); + } + + @Override + public long contentLength() throws IOException { + return delegate.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + + BufferedSink bufferedSink; + + countingSink = new CountingSink(sink); + bufferedSink = Okio.buffer(countingSink); + + delegate.writeTo(bufferedSink); + + bufferedSink.flush(); + } + + protected final class CountingSink extends ForwardingSink { + + private long bytesWritten = 0; + + public CountingSink(Sink delegate) { + super(delegate); + } + + @Override + public void write(Buffer source, long byteCount) throws IOException { + + super.write(source, byteCount); + + bytesWritten += byteCount; + listener.onRequestProgress(bytesWritten, contentLength()); + } + + } + + public interface ProgressListener { + + void onRequestProgress(long bytesWritten, long contentLength); + + } +} + diff --git a/spring-rest/src/test/resources/test.txt b/spring-rest/src/test/resources/test.txt new file mode 100644 index 0000000000..95d09f2b10 --- /dev/null +++ b/spring-rest/src/test/resources/test.txt @@ -0,0 +1 @@ +hello world \ No newline at end of file From ebc1c54bea85af32ef238f1128a46ba6a84c85dc Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Tue, 11 Oct 2016 10:42:45 +0200 Subject: [PATCH 4/7] Add OkHttp example --- spring-rest/src/test/resources/.gitignore | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 spring-rest/src/test/resources/.gitignore diff --git a/spring-rest/src/test/resources/.gitignore b/spring-rest/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/spring-rest/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file From 774b2610504f7c74f6888c89f5687c94d6a94699 Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Tue, 11 Oct 2016 10:44:47 +0200 Subject: [PATCH 5/7] Add OkHttp example --- spring-rest/src/test/resources/.gitignore | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 spring-rest/src/test/resources/.gitignore diff --git a/spring-rest/src/test/resources/.gitignore b/spring-rest/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-rest/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file From 70eb0501c651b13cc74f9fff1164e7d3aac9bd5b Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Thu, 13 Oct 2016 10:02:09 +0200 Subject: [PATCH 6/7] Delete okhttp project --- okhttp/pom.xml | 76 ------------ .../okhttp/DefaultContentTypeInterceptor.java | 26 ----- .../okhttp/ProgressRequestWrapper.java | 74 ------------ .../okhttp/OkHttpFileUploadingTest.java | 81 ------------- .../org/baeldung/okhttp/OkHttpGetTest.java | 78 ------------- .../org/baeldung/okhttp/OkHttpHeaderTest.java | 48 -------- .../org/baeldung/okhttp/OkHttpMiscTest.java | 107 ----------------- .../baeldung/okhttp/OkHttpPostingTest.java | 109 ------------------ .../baeldung/okhttp/OkHttpRedirectTest.java | 33 ------ okhttp/src/test/resources/test.txt | 1 - 10 files changed, 633 deletions(-) delete mode 100644 okhttp/pom.xml delete mode 100644 okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java delete mode 100644 okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java delete mode 100644 okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java delete mode 100644 okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java delete mode 100644 okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java delete mode 100644 okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java delete mode 100644 okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java delete mode 100644 okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java delete mode 100644 okhttp/src/test/resources/test.txt diff --git a/okhttp/pom.xml b/okhttp/pom.xml deleted file mode 100644 index 4d371f40b0..0000000000 --- a/okhttp/pom.xml +++ /dev/null @@ -1,76 +0,0 @@ - - 4.0.0 - org.baeldung.okhttp - okhttp - 0.0.1-SNAPSHOT - - - - - - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - - - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - - junit - junit - ${junit.version} - test - - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - - - - - - 3.4.1 - - - 1.7.13 - 1.1.3 - - - 1.3 - 4.12 - - - - diff --git a/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java b/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java deleted file mode 100644 index 2a33a1febd..0000000000 --- a/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung.okhttp; - -import java.io.IOException; - -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -public class DefaultContentTypeInterceptor implements Interceptor { - - private final String contentType; - - public DefaultContentTypeInterceptor(String contentType) { - this.contentType = contentType; - } - - public Response intercept(Interceptor.Chain chain) throws IOException { - - Request originalRequest = chain.request(); - Request requestWithUserAgent = originalRequest.newBuilder() - .header("Content-Type", contentType) - .build(); - - return chain.proceed(requestWithUserAgent); - } -} diff --git a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java b/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java deleted file mode 100644 index 255d10b98a..0000000000 --- a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.baeldung.okhttp; - -import okhttp3.RequestBody; -import okhttp3.MediaType; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSink; -import okio.ForwardingSink; -import okio.Okio; -import okio.Sink; - -public class ProgressRequestWrapper extends RequestBody { - - protected RequestBody delegate; - protected ProgressListener listener; - - protected CountingSink countingSink; - - public ProgressRequestWrapper(RequestBody delegate, ProgressListener listener) { - this.delegate = delegate; - this.listener = listener; - } - - @Override - public MediaType contentType() { - return delegate.contentType(); - } - - @Override - public long contentLength() throws IOException { - return delegate.contentLength(); - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - - BufferedSink bufferedSink; - - countingSink = new CountingSink(sink); - bufferedSink = Okio.buffer(countingSink); - - delegate.writeTo(bufferedSink); - - bufferedSink.flush(); - } - - protected final class CountingSink extends ForwardingSink { - - private long bytesWritten = 0; - - public CountingSink(Sink delegate) { - super(delegate); - } - - @Override - public void write(Buffer source, long byteCount) throws IOException { - - super.write(source, byteCount); - - bytesWritten += byteCount; - listener.onRequestProgress(bytesWritten, contentLength()); - } - - } - - public interface ProgressListener { - - void onRequestProgress(long bytesWritten, long contentLength); - - } -} - diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java deleted file mode 100644 index 77219b8e22..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.baeldung.okhttp; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - -import java.io.File; -import java.io.IOException; - -import org.baeldung.okhttp.ProgressRequestWrapper; -import org.junit.Test; - -import okhttp3.Call; -import okhttp3.MediaType; -import okhttp3.MultipartBody; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; - -public class OkHttpFileUploadingTest { - - private static final String BASE_URL = "http://localhost:8080/spring-rest"; - - @Test - public void whenUploadFile_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("file", "file.txt", - RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) - .build(); - - Request request = new Request.Builder() - .url(BASE_URL + "/users/upload") - .post(requestBody) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } - - @Test - public void whenGetUploadFileProgress_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("file", "file.txt", - RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) - .build(); - - - ProgressRequestWrapper.ProgressListener listener = new ProgressRequestWrapper.ProgressListener() { - - public void onRequestProgress(long bytesWritten, long contentLength) { - - float percentage = 100f * bytesWritten / contentLength; - assertFalse(Float.compare(percentage, 100) > 0); - } - }; - - ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, listener); - - Request request = new Request.Builder() - .url(BASE_URL + "/users/upload") - .post(countingBody) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - - } -} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java deleted file mode 100644 index de954e3dd7..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.baeldung.okhttp; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; - -import org.junit.Test; - -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -public class OkHttpGetTest { - - private static final String BASE_URL = "http://localhost:8080/spring-rest"; - - @Test - public void whenGetRequest_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - Request request = new Request.Builder() - .url(BASE_URL + "/date") - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } - - @Test - public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); - urlBuilder.addQueryParameter("id", "1"); - - String url = urlBuilder.build().toString(); - - Request request = new Request.Builder() - .url(url) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } - - @Test - public void whenAsynchronousGetRequest_thenCorrect() { - - OkHttpClient client = new OkHttpClient(); - - Request request = new Request.Builder() - .url(BASE_URL + "/date") - .build(); - - Call call = client.newCall(request); - - call.enqueue(new Callback() { - - public void onResponse(Call call, Response response) throws IOException { - assertThat(response.code(), equalTo(200)); - } - - public void onFailure(Call call, IOException e) { - - } - }); - } -} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java deleted file mode 100644 index 958eeb51ce..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.baeldung.okhttp; - -import java.io.IOException; - -import org.junit.Test; - -import okhttp3.Call; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -public class OkHttpHeaderTest { - - private static final String SAMPLE_URL = "http://www.github.com"; - - @Test - public void whenSetHeader_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - Request request = new Request.Builder() - .url(SAMPLE_URL) - .addHeader("Content-Type", "application/json") - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - response.close(); - } - - @Test - public void whenSetDefaultHeader_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient.Builder() - .addInterceptor(new DefaultContentTypeInterceptor("application/json")) - .build(); - - Request request = new Request.Builder() - .url(SAMPLE_URL) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - response.close(); - } - - -} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java deleted file mode 100644 index fe15a76200..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java +++ /dev/null @@ -1,107 +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 org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -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"; - private static Logger logger = LoggerFactory.getLogger(OkHttpMiscTest.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()); - } -} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java deleted file mode 100644 index 41a024d2ee..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.baeldung.okhttp; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.File; -import java.io.IOException; - -import org.junit.Test; - -import okhttp3.Call; -import okhttp3.Credentials; -import okhttp3.FormBody; -import okhttp3.MediaType; -import okhttp3.MultipartBody; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; - -public class OkHttpPostingTest { - - private static final String BASE_URL = "http://localhost:8080/spring-rest"; - private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; - - @Test - public void whenSendPostRequest_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - RequestBody formBody = new FormBody.Builder() - .add("username", "test") - .add("password", "test") - .build(); - - Request request = new Request.Builder() - .url(BASE_URL + "/users") - .post(formBody) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } - - @Test - public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException { - - String postBody = "test post"; - - OkHttpClient client = new OkHttpClient(); - - Request request = new Request.Builder() - .url(URL_SECURED_BY_BASIC_AUTHENTICATION) - .addHeader("Authorization", Credentials.basic("test", "test")) - .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody)) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } - - @Test - public void whenPostJson_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - String json = "{\"id\":1,\"name\":\"John\"}"; - - RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); - - Request request = new Request.Builder() - .url(BASE_URL + "/users/detail") - .post(body) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } - - @Test - public void whenSendMultipartRequest_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("username", "test") - .addFormDataPart("password", "test") - .addFormDataPart("file", "file.txt", - RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) - .build(); - - Request request = new Request.Builder() - .url(BASE_URL + "/users/multipart") - .post(requestBody) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } -} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java deleted file mode 100644 index c709253478..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.baeldung.okhttp; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; - -import org.junit.Test; - -import okhttp3.Call; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -public class OkHttpRedirectTest { - - @Test - public void whenSetFollowRedirects_thenNotRedirected() throws IOException { - - OkHttpClient client = new OkHttpClient().newBuilder() - .followRedirects(false) - .build(); - - Request request = new Request.Builder() - .url("http://t.co/I5YYd9tddw") - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(301)); - } -} diff --git a/okhttp/src/test/resources/test.txt b/okhttp/src/test/resources/test.txt deleted file mode 100644 index 95d09f2b10..0000000000 --- a/okhttp/src/test/resources/test.txt +++ /dev/null @@ -1 +0,0 @@ -hello world \ No newline at end of file From 5329c54f28fc2c6b853454547b62b256f03c2ffc Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Thu, 13 Oct 2016 10:20:18 +0200 Subject: [PATCH 7/7] Code improvement --- pom.xml | 3 +-- spring-rest/README.md | 3 ++- ...ileUploadingTest.java => OkHttpFileUploadingLiveTest.java} | 2 +- .../okhttp/{OkHttpGetTest.java => OkHttpGetLiveTest.java} | 2 +- .../{OkHttpHeaderTest.java => OkHttpHeaderLiveTest.java} | 2 +- .../okhttp/{OkHttpMiscTest.java => OkHttpMiscLiveTest.java} | 4 ++-- .../{OkHttpPostingTest.java => OkHttpPostingLiveTest.java} | 2 +- .../{OkHttpRedirectTest.java => OkHttpRedirectLiveTest.java} | 2 +- 8 files changed, 10 insertions(+), 10 deletions(-) rename spring-rest/src/test/java/org/baeldung/okhttp/{OkHttpFileUploadingTest.java => OkHttpFileUploadingLiveTest.java} (95%) rename spring-rest/src/test/java/org/baeldung/okhttp/{OkHttpGetTest.java => OkHttpGetLiveTest.java} (94%) rename spring-rest/src/test/java/org/baeldung/okhttp/{OkHttpHeaderTest.java => OkHttpHeaderLiveTest.java} (93%) rename spring-rest/src/test/java/org/baeldung/okhttp/{OkHttpMiscTest.java => OkHttpMiscLiveTest.java} (95%) rename spring-rest/src/test/java/org/baeldung/okhttp/{OkHttpPostingTest.java => OkHttpPostingLiveTest.java} (95%) rename spring-rest/src/test/java/org/baeldung/okhttp/{OkHttpRedirectTest.java => OkHttpRedirectLiveTest.java} (91%) diff --git a/pom.xml b/pom.xml index 5526c1e2a3..0808397464 100644 --- a/pom.xml +++ b/pom.xml @@ -18,7 +18,7 @@ apache-cxf autovalue-tutorial - + cdi core-java core-java-8 @@ -69,7 +69,6 @@ rest-assured rest-testing resteasy - okhttp spring-all spring-akka diff --git a/spring-rest/README.md b/spring-rest/README.md index 7d993b38b8..77d12063ed 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -5,8 +5,9 @@ ###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) diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java similarity index 95% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java index 77219b8e22..d1cc67b99a 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -18,7 +18,7 @@ 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"; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java similarity index 94% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index de954e3dd7..9a49c8d9a2 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -14,7 +14,7 @@ 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"; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java similarity index 93% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java index 958eeb51ce..8eddfcb135 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java @@ -9,7 +9,7 @@ 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"; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java similarity index 95% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java index fe15a76200..c44500f4be 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -16,10 +16,10 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -public class OkHttpMiscTest { +public class OkHttpMiscLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; - private static Logger logger = LoggerFactory.getLogger(OkHttpMiscTest.class); + private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class); @Test public void whenSetRequestTimeout_thenFail() throws IOException { diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java similarity index 95% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java index 41a024d2ee..18bd4cdcb3 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java @@ -18,7 +18,7 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; -public class OkHttpPostingTest { +public class OkHttpPostingLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectLiveTest.java similarity index 91% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectLiveTest.java index c709253478..d568a4fdf7 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectLiveTest.java @@ -12,7 +12,7 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -public class OkHttpRedirectTest { +public class OkHttpRedirectLiveTest { @Test public void whenSetFollowRedirects_thenNotRedirected() throws IOException {