From 82532d661dcf639255eebafd20090e9982f0918f Mon Sep 17 00:00:00 2001 From: Gaetano Piazzolla Date: Mon, 10 Jul 2023 20:15:49 +0200 Subject: [PATCH] JAVA-22043 | Fixing httpclient live test (#14352) * JAVA-22043 | fixing httpclient live test * JAVA-22043 | fixing httpclient live test using lambda expression for execution --- .../httpclient/GetRequestMockServer.java | 67 +++++---- .../HttpClientCancelRequestLiveTest.java | 8 +- .../HttpClientMultipartLiveTest.java | 128 +++++++++--------- .../httpclient/base/HttpClientLiveTest.java | 2 +- .../base/HttpClientSandboxLiveTest.java | 7 +- .../CustomHttpClientResponseHandler.java | 11 -- 6 files changed, 110 insertions(+), 113 deletions(-) delete mode 100644 apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java index 988a89e7af..f79cc9d601 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java @@ -7,7 +7,6 @@ import static org.mockserver.model.HttpResponse.response; import java.io.IOException; import java.net.ServerSocket; -import java.net.URISyntaxException; import org.apache.http.HttpStatus; import org.junit.jupiter.api.AfterAll; @@ -18,22 +17,19 @@ import org.mockserver.integration.ClientAndServer; public class GetRequestMockServer { public static ClientAndServer mockServer; - public static String serviceOneUrl; - public static String serviceTwoUrl; public static int serverPort; public static final String SERVER_ADDRESS = "127.0.0.1"; - public static final String PATH_ONE = "/test1"; - public static final String PATH_TWO = "/test2"; - public static final String METHOD = "GET"; + + public static final String SECURITY_PATH = "/spring-security-rest-basic-auth/api/foos/1"; + + public static final String UPLOAD_PATH = "/spring-mvc-java/stub/multipart"; @BeforeAll static void startServer() throws IOException { serverPort = getFreePort(); - System.out.println("Free port "+serverPort); - serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE; - serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO; + System.out.println("Free port " + serverPort); mockServer = startClientAndServer(serverPort); mockGetRequest(); } @@ -44,33 +40,36 @@ public class GetRequestMockServer { } private static void mockGetRequest() { - new MockServerClient(SERVER_ADDRESS, serverPort) - .when( - request() - .withPath(PATH_ONE) - .withMethod(METHOD), - exactly(5) - ) - .respond( - response() - .withStatusCode(HttpStatus.SC_OK) - .withBody("{\"status\":\"ok\"}") - ); - new MockServerClient(SERVER_ADDRESS, serverPort) - .when( - request() - .withPath(PATH_TWO) - .withMethod(METHOD), - exactly(1) - ) - .respond( - response() - .withStatusCode(HttpStatus.SC_OK) - .withBody("{\"status\":\"ok\"}") - ); + + MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort); + + client.when( + request() + .withPath(SECURITY_PATH) + .withMethod("GET"), + exactly(1) + ) + .respond( + response() + .withStatusCode(HttpStatus.SC_OK) + .withBody("{\"status\":\"ok\"}") + ); + + client.when( + request() + .withPath(UPLOAD_PATH) + .withMethod("POST"), + exactly(4) + ) + .respond( + response() + .withStatusCode(HttpStatus.SC_OK) + .withBody("{\"status\":\"ok\"}") + .withHeader("Content-Type", "multipart/form-data") + ); } - private static int getFreePort () throws IOException { + private static int getFreePort() throws IOException { try (ServerSocket serverSocket = new ServerSocket(0)) { return serverSocket.getLocalPort(); } diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java index d19e0e1d86..d3e80c4429 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java @@ -19,7 +19,7 @@ class HttpClientCancelRequestLiveTest { void whenRequestIsCanceled_thenCorrect() throws IOException { HttpGet request = new HttpGet(SAMPLE_URL); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - httpClient.execute(request, response -> { + httpClient.execute(request, response -> { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); @@ -28,6 +28,12 @@ class HttpClientCancelRequestLiveTest { System.out.println("Response content length: " + entity.getContentLength()); } System.out.println("----------------------------------------"); + + if (entity != null) { + // Closes this stream and releases any system resources + entity.close(); + } + // Do not feel like reading the response body // Call abort on the request object request.abort(); diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java index 720049378b..ffa14af048 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java @@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.apache.hc.core5.http.ParseException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -13,7 +14,6 @@ import org.apache.hc.client5.http.entity.mime.HttpMultipartMode; import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.client5.http.entity.mime.StringBody; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.core5.http.ContentType; @@ -28,9 +28,8 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; -import com.baeldung.httpclient.handler.CustomHttpClientResponseHandler; -class HttpClientMultipartLiveTest { +class HttpClientMultipartLiveTest extends GetRequestMockServer { // No longer available // private static final String SERVER = "http://echo.200please.com"; @@ -45,13 +44,15 @@ class HttpClientMultipartLiveTest { @BeforeEach public void before() { post = new HttpPost(SERVER); + String URL = "http://localhost:"+serverPort+"/spring-mvc-java/stub/multipart"; + post = new HttpPost(URL); } @Test void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + TEXTFILENAME); + .getContextClassLoader() + .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); @@ -66,27 +67,28 @@ class HttpClientMultipartLiveTest { final HttpEntity entity = builder.build(); post.setEntity(entity); - try(CloseableHttpClient client = HttpClientBuilder.create() - .build(); + try (CloseableHttpClient client = HttpClientBuilder.create() + .build()) { - CloseableHttpResponse response = (CloseableHttpResponse) client - .execute(post, new CustomHttpClientResponseHandler())){ - final int statusCode = response.getCode(); - final String responseString = getContent(response.getEntity()); - final String contentTypeInHeader = getContentTypeHeader(); + client.execute(post, response -> { + final int statusCode = response.getCode(); + final String responseString = getContent(response.getEntity()); + final String contentTypeInHeader = getContentTypeHeader(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); - System.out.println(responseString); - System.out.println("POST Content Type: " + contentTypeInHeader); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + assertTrue(contentTypeInHeader.contains("multipart/form-data")); + System.out.println(responseString); + System.out.println("POST Content Type: " + contentTypeInHeader); + return response; + }); } } @Test void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + TEXTFILENAME); + .getContextClassLoader() + .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final String message = "This is a multipart post"; final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); @@ -96,30 +98,31 @@ class HttpClientMultipartLiveTest { final HttpEntity entity = builder.build(); post.setEntity(entity); - try(CloseableHttpClient client = HttpClientBuilder.create() - .build(); + try (CloseableHttpClient client = HttpClientBuilder.create() + .build()) { - CloseableHttpResponse response = (CloseableHttpResponse) client - .execute(post, new CustomHttpClientResponseHandler())){ + client.execute(post, response -> { - final int statusCode = response.getCode(); - final String responseString = getContent(response.getEntity()); - final String contentTypeInHeader = getContentTypeHeader(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); - System.out.println(responseString); - System.out.println("POST Content Type: " + contentTypeInHeader); + final int statusCode = response.getCode(); + final String responseString = getContent(response.getEntity()); + final String contentTypeInHeader = getContentTypeHeader(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + assertTrue(contentTypeInHeader.contains("multipart/form-data")); + System.out.println(responseString); + System.out.println("POST Content Type: " + contentTypeInHeader); + return response; + }); } } @Test void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + ZIPFILENAME); + .getContextClassLoader() + .getResource("uploads/" + ZIPFILENAME); final URL url2 = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + IMAGEFILENAME); + .getContextClassLoader() + .getResource("uploads/" + IMAGEFILENAME); final InputStream inputStream = new FileInputStream(url.getPath()); final File file = new File(url2.getPath()); final String message = "This is a multipart post"; @@ -131,25 +134,25 @@ class HttpClientMultipartLiveTest { final HttpEntity entity = builder.build(); post.setEntity(entity); - try(CloseableHttpClient client = HttpClientBuilder.create() - .build(); + try (CloseableHttpClient client = HttpClientBuilder.create() + .build()) { - CloseableHttpResponse response = (CloseableHttpResponse) client - .execute(post, new CustomHttpClientResponseHandler())){ - - final int statusCode = response.getCode(); - final String responseString = getContent(response.getEntity()); - final String contentTypeInHeader = getContentTypeHeader(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); - System.out.println(responseString); - System.out.println("POST Content Type: " + contentTypeInHeader); - inputStream.close(); + client.execute(post, response -> { + final int statusCode = response.getCode(); + final String responseString = getContent(response.getEntity()); + final String contentTypeInHeader = getContentTypeHeader(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + assertTrue(contentTypeInHeader.contains("multipart/form-data;")); + System.out.println(responseString); + System.out.println("POST Content Type: " + contentTypeInHeader); + inputStream.close(); + return response; + }); } } @Test - void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { + void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException, ParseException { final String message = "This is a multipart post"; final byte[] bytes = "binary code".getBytes(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); @@ -159,21 +162,20 @@ class HttpClientMultipartLiveTest { final HttpEntity entity = builder.build(); post.setEntity(entity); - try(CloseableHttpClient client = HttpClientBuilder.create() - .build(); + try (CloseableHttpClient httpClient = HttpClientBuilder.create() + .build()) { - CloseableHttpResponse response = (CloseableHttpResponse) client - .execute(post, new CustomHttpClientResponseHandler())){ - - final int statusCode = response.getCode(); - final String responseString = getContent(response.getEntity()); - final String contentTypeInHeader = getContentTypeHeader(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); - System.out.println(responseString); - System.out.println("POST Content Type: " + contentTypeInHeader); + httpClient.execute(post, response -> { + final int statusCode = response.getCode(); + final String responseString = getContent(response.getEntity()); + final String contentTypeInHeader = getContentTypeHeader(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + assertTrue(contentTypeInHeader.contains("multipart/form-data;")); + System.out.println(responseString); + System.out.println("POST Content Type: " + contentTypeInHeader); + return response; + }); } - } // UTIL @@ -184,15 +186,15 @@ class HttpClientMultipartLiveTest { StringBuilder content = new StringBuilder(); while ((body = rd.readLine()) != null) { content.append(body) - .append("\n"); + .append("\n"); } return content.toString() - .trim(); + .trim(); } private String getContentTypeHeader() { return post.getEntity() - .getContentType(); + .getContentType(); } } diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java index 4173909f7d..b8bc536918 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java @@ -43,7 +43,7 @@ public class HttpClientLiveTest { @Test(expected = ConnectTimeoutException.class) public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException { - final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(20).build(); + final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5).setConnectTimeout(5).setSocketTimeout(2).build(); final HttpGet request = new HttpGet(SAMPLE_URL); request.setConfig(requestConfig); response = instance.execute(request); diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientSandboxLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientSandboxLiveTest.java index c667ae36f6..f72aa0c878 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientSandboxLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientSandboxLiveTest.java @@ -1,5 +1,6 @@ package com.baeldung.httpclient.base; +import com.baeldung.httpclient.GetRequestMockServer; import com.baeldung.httpclient.ResponseUtil; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; @@ -9,14 +10,14 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; /* * NOTE : Need module spring-security-rest-basic-auth to be running */ -public class HttpClientSandboxLiveTest { +public class HttpClientSandboxLiveTest extends GetRequestMockServer { @Test public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { @@ -26,7 +27,7 @@ public class HttpClientSandboxLiveTest { final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build(); - final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1"); + final HttpGet httpGet = new HttpGet("http://localhost:" + serverPort + "/spring-security-rest-basic-auth/api/foos/1"); final CloseableHttpResponse response = client.execute(httpGet); System.out.println(response.getStatusLine()); diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java deleted file mode 100644 index 0559854b35..0000000000 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.httpclient.handler; - -import org.apache.hc.core5.http.ClassicHttpResponse; -import org.apache.hc.core5.http.io.HttpClientResponseHandler; - -public class CustomHttpClientResponseHandler implements HttpClientResponseHandler { - @Override - public ClassicHttpResponse handleResponse(ClassicHttpResponse response) { - return response; - } -} \ No newline at end of file