Merge branch 'master' into master

This commit is contained in:
Loredana Crusoveanu
2023-07-20 16:30:42 +03:00
committed by GitHub
264 changed files with 3533 additions and 1113 deletions
@@ -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();
}
@@ -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();
@@ -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,7 @@ 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 +43,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 +66,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 +97,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 +133,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 +161,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
@@ -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);
@@ -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());
@@ -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<ClassicHttpResponse> {
@Override
public ClassicHttpResponse handleResponse(ClassicHttpResponse response) {
return response;
}
}
+1 -51
View File
@@ -199,33 +199,7 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
<systemProperties>
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
@@ -233,26 +207,6 @@
<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>
@@ -269,9 +223,6 @@
<includes>
<include>**/*LiveTest.java</include>
</includes>
<systemPropertyVariables>
<webTarget>cargo</webTarget>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
@@ -291,7 +242,6 @@
<httpclient.version>4.5.14</httpclient.version>
<mockserver.version>5.11.2</mockserver.version>
<!-- maven plugins -->
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
</properties>
@@ -0,0 +1,56 @@
package com.baeldung;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import java.io.IOException;
import java.net.ServerSocket;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
public class GetRequestMockServer {
public static ClientAndServer mockServer;
public static int serverPort;
public static String simplePathUrl;
public static final String SERVER_ADDRESS = "127.0.0.1";
public static final String SIMPLE_PATH = "/httpclient-simple/api/bars/1";
@BeforeAll
static void startServer() throws IOException {
serverPort = getFreePort();
System.out.println("Free port " + serverPort);
mockServer = startClientAndServer(serverPort);
simplePathUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + SIMPLE_PATH;
mockGetRequest();
}
@AfterAll
static void stopServer() {
mockServer.stop();
}
private static void mockGetRequest() {
MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort);
client.when(request().withPath(SIMPLE_PATH)
.withMethod("GET"))
.respond(response().withStatusCode(HttpStatus.SC_OK)
.withBody("{\"status\":\"ok\"}"));
}
private static int getFreePort() throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
return serverSocket.getLocalPort();
}
}
}
@@ -10,7 +10,7 @@ import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
@@ -31,10 +31,10 @@ import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import com.baeldung.GetRequestMockServer;
class ClientLiveTest {
class ClientLiveTest extends GetRequestMockServer {
final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
@Test
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
@@ -54,13 +54,13 @@ class ClientLiveTest {
.build();
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(simplePathUrl, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
@Test
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
final HttpGet getMethod = new HttpGet(urlOverHttps);
final HttpGet getMethod = new HttpGet(simplePathUrl);
try (final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLHostnameVerifier(new NoopHostnameVerifier())
@@ -80,20 +80,22 @@ class ClientLiveTest {
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(simplePathUrl, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
@Test
void whenHttpsUrlIsConsumed_thenException() {
String urlOverHttps = "https://localhost:8082/httpclient-simple";
String urlOverHttps = "https://localhost:"+serverPort+"/httpclient-simple/api/bars/1";
HttpGet getMethod = new HttpGet(urlOverHttps);
assertThrows(SSLPeerUnverifiedException.class, () -> {
assertThrows(SSLHandshakeException.class, () -> {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
});
}
}
@@ -1,6 +1,5 @@
package com.baeldung.client;
import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@@ -89,4 +88,5 @@ public class RestClientV4LiveManualTest {
HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
}
@@ -1,77 +0,0 @@
package com.baeldung.httpclient;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.matchers.Times.exactly;
import static org.mockserver.model.HttpRequest.request;
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;
import org.junit.jupiter.api.BeforeAll;
import org.mockserver.client.MockServerClient;
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";
@BeforeAll
static void startServer() throws IOException, URISyntaxException {
serverPort = getFreePort();
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
mockServer = startClientAndServer(serverPort);
mockGetRequest();
}
@AfterAll
static void stopServer() {
mockServer.stop();
}
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\"}")
);
}
private static int getFreePort () throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
return serverSocket.getLocalPort();
}
}
}
@@ -31,6 +31,7 @@ import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.junit.jupiter.api.Test;
import com.baeldung.GetRequestMockServer;
class HttpAsyncClientV4LiveTest extends GetRequestMockServer {
@@ -44,7 +44,9 @@ public class HttpClientCancelRequestV4LiveTest {
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
entity.getContent().close();
}
System.out.println("----------------------------------------");
// Do not feel like reading the response body
@@ -21,7 +21,9 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class HttpClientTimeoutV4LiveTest {
import com.baeldung.GetRequestMockServer;
class HttpClientTimeoutV4LiveTest extends GetRequestMockServer {
private CloseableHttpResponse response;
@@ -97,7 +99,7 @@ class HttpClientTimeoutV4LiveTest {
int timeout = 20; // seconds
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000)
.setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
HttpGet getMethod = new HttpGet("http://localhost:8082/httpclient-simple/api/bars/1");
HttpGet getMethod = new HttpGet(simplePathUrl);
getMethod.setConfig(requestConfig);
int hardTimeout = 5; // seconds
@@ -13,13 +13,15 @@ import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import com.baeldung.GetRequestMockServer;
class ApacheHttpClientUnitTest extends GetRequestMockServer {
@Test
void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpGet httpGet = new HttpGet(serviceOneUrl);
HttpGet httpGet = new HttpGet(simplePathUrl);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
@@ -1,78 +0,0 @@
package com.baeldung.httpclient.httpclient;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.URISyntaxException;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.matchers.Times.exactly;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
public class GetRequestMockServer {
public static ClientAndServer mockServer;
public static String serviceOneUrl;
public static String serviceTwoUrl;
private 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";
@BeforeAll
static void startServer() throws IOException, URISyntaxException {
serverPort = getFreePort();
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
mockServer = startClientAndServer(serverPort);
mockGetRequest();
}
@AfterAll
static void stopServer() {
mockServer.stop();
}
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\"}")
);
}
private static int getFreePort () throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
return serverSocket.getLocalPort();
}
}
}
+1
View File
@@ -1,2 +1,3 @@
## Relevant Articles
- [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values)
- [How to Read Zip Files Entries With Java](https://www.baeldung.com/java-read-zip-files)
@@ -6,3 +6,4 @@
- [Using a Mutex Object in Java](https://www.baeldung.com/java-mutex)
- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded)
- [How to Check if All Runnables Are Done](https://www.baeldung.com/java-runnables-check-status)
- [Parallelize for Loop in Java](https://www.baeldung.com/java-for-loop-parallel)
@@ -8,4 +8,5 @@ This module contains articles about basic Java concurrency.
- [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await)
- [Is CompletableFuture Non-blocking?](https://www.baeldung.com/java-completablefuture-non-blocking)
- [Returning a Value After Finishing Thread’s Job in Java](https://www.baeldung.com/java-return-value-after-thread-finish)
- [CompletableFuture and ThreadPool in Java](https://www.baeldung.com/java-completablefuture-threadpool)
- [[<-- Prev]](../core-java-concurrency-basic-2)
@@ -8,4 +8,5 @@ This module contains articles about date operations in Java.
- [How to Determine Date of the First Day of the Week Using LocalDate in Java](https://www.baeldung.com/java-first-day-of-the-week)
- [Adding One Month to Current Date in Java](https://www.baeldung.com/java-adding-one-month-to-current-date)
- [How to Get Last Day of a Month in Java](https://www.baeldung.com/java-last-day-month)
- [Getting Yesterday’s Date in Java](https://www.baeldung.com/java-find-yesterdays-date)
- [[<-- Prev]](/core-java-modules/core-java-date-operations-2)
@@ -4,13 +4,5 @@ This module contains articles about core Java input/output(IO) APIs.
### Relevant Articles:
- [Constructing a Relative Path From Two Absolute Paths in Java](https://www.baeldung.com/java-relative-path-absolute)
- [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input)
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
- [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer)
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line)
- [Storing Java Scanner Input in an Array](https://www.baeldung.com/java-store-scanner-input-in-array)
- [How to Take Input as String With Spaces in Java Using Scanner?](https://www.baeldung.com/java-scanner-input-with-spaces)
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
- [What’s the Difference between Scanner next() and nextLine() Methods?](https://www.baeldung.com/java-scanner-next-vs-nextline)
- [Handle NoSuchElementException When Reading a File Through Scanner](https://www.baeldung.com/java-scanner-nosuchelementexception-reading-file)
- [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty)
@@ -92,12 +92,6 @@
<version>7.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.5</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-io-apis-2</finalName>
@@ -0,0 +1,71 @@
package com.baeldung.emptyfile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class CheckFileIsEmptyUnitTest {
@Test
void whenTheFileIsEmpty_thenFileLengthIsZero(@TempDir Path tempDir) throws IOException {
File emptyFile = tempDir.resolve("an-empty-file.txt")
.toFile();
emptyFile.createNewFile();
assertTrue(emptyFile.exists());
assertEquals(0, emptyFile.length());
}
@Test
void whenFileDoesNotExist_thenFileLengthIsZero(@TempDir Path tempDir) {
File aNewFile = tempDir.resolve("a-new-file.txt")
.toFile();
assertFalse(aNewFile.exists());
assertEquals(0, aNewFile.length());
}
boolean isFileEmpty(File file) {
if (!file.exists()) {
throw new IllegalArgumentException("Cannot check the file length. The file is not found: " + file.getAbsolutePath());
}
return file.length() == 0;
}
@Test
void whenTheFileDoesNotExist_thenIsFilesEmptyThrowsException(@TempDir Path tempDir) {
File aNewFile = tempDir.resolve("a-new-file.txt")
.toFile();
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> isFileEmpty(aNewFile));
assertEquals(ex.getMessage(), "Cannot check the file length. The file is not found: " + aNewFile.getAbsolutePath());
}
@Test
void whenTheFileIsEmpty_thenIsFilesEmptyReturnsTrue(@TempDir Path tempDir) throws IOException {
File emptyFile = tempDir.resolve("an-empty-file.txt")
.toFile();
emptyFile.createNewFile();
assertTrue(isFileEmpty(emptyFile));
}
@Test
void whenTheFileIsEmpty_thenFilesSizeReturnsTrue(@TempDir Path tempDir) throws IOException {
Path emptyFilePath = tempDir.resolve("an-empty-file.txt");
Files.createFile(emptyFilePath);
assertEquals(0, Files.size(emptyFilePath));
}
@Test
void whenTheFileDoesNotExist_thenFilesSizeThrowsException(@TempDir Path tempDir) {
Path aNewFilePath = tempDir.resolve("a-new-file.txt");
assertThrows(NoSuchFileException.class, () -> Files.size(aNewFilePath));
}
}
@@ -1,6 +0,0 @@
## Core Java IO APIs
This module contains articles about core Java input/output(IO) APIs.
### Relevant Articles:
- [Read Date in Java Using Scanner](https://www.baeldung.com/java-scanner-read-date)
@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-io-apis-3</artifactId>
<name>core-java-io-apis-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>
@@ -10,6 +10,6 @@ This module contains articles about core Java input/output(IO) APIs.
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](https://www.baeldung.com/java-path)
- [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter)
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
- [Java Scanner](https://www.baeldung.com/java-scanner)
- [Scanner nextLine() Method](https://www.baeldung.com/java-scanner-nextline)
- [Java Scanner hasNext() vs. hasNextLine()](https://www.baeldung.com/java-scanner-hasnext-vs-hasnextline)
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line)
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
@@ -31,6 +31,12 @@
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.5</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
@@ -1,36 +1,36 @@
package com.baeldung.multinput;
import java.util.InputMismatchException;
import java.util.Scanner;
public class MultiInputs {
public void UsingSpaceDelimiter(){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("You entered " + num1 + " and " + num2);
}
public void UsingREDelimiter(){
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("[\\s,]+");
System.out.print("Enter two numbers separated by a space or a comma: ");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("You entered " + num1 + " and " + num2);
}
public void UsingCustomDelimiter(){
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(";");
System.out.print("Enter two numbers separated by a semicolon: ");
try { int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("You entered " + num1 + " and " + num2); }
catch (InputMismatchException e)
{ System.out.println("Invalid input. Please enter two integers separated by a semicolon."); }
}
}
package com.baeldung.multinput;
import java.util.InputMismatchException;
import java.util.Scanner;
public class MultiInputs {
public void UsingSpaceDelimiter(){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("You entered " + num1 + " and " + num2);
}
public void UsingREDelimiter(){
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("[\\s,]+");
System.out.print("Enter two numbers separated by a space or a comma: ");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("You entered " + num1 + " and " + num2);
}
public void UsingCustomDelimiter(){
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(";");
System.out.print("Enter two numbers separated by a semicolon: ");
try { int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("You entered " + num1 + " and " + num2); }
catch (InputMismatchException e)
{ System.out.println("Invalid input. Please enter two integers separated by a semicolon."); }
}
}
@@ -1,36 +1,36 @@
package com.baeldung.bufferedreadervsfilereader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
class BufferedReaderUnitTest {
@Test
void whenReadingAFile_thenReadsLineByLine() {
StringBuilder result = new StringBuilder();
final Path filePath = new File("src/test/resources/sampleText1.txt").toPath();
try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(filePath), StandardCharsets.UTF_8))) {
String line;
while((line = br.readLine()) != null) {
result.append(line);
result.append('\n');
}
} catch (IOException e) {
e.printStackTrace();
}
assertEquals("first line\nsecond line\nthird line\n", result.toString());
}
}
package com.baeldung.bufferedreadervsfilereader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
class BufferedReaderUnitTest {
@Test
void whenReadingAFile_thenReadsLineByLine() {
StringBuilder result = new StringBuilder();
final Path filePath = new File("src/test/resources/sampleText1.txt").toPath();
try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(filePath), StandardCharsets.UTF_8))) {
String line;
while((line = br.readLine()) != null) {
result.append(line);
result.append('\n');
}
} catch (IOException e) {
e.printStackTrace();
}
assertEquals("first line\nsecond line\nthird line\n", result.toString());
}
}
@@ -1,30 +1,30 @@
package com.baeldung.bufferedreadervsfilereader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.FileReader;
import java.io.IOException;
import org.junit.jupiter.api.Test;
class FileReaderUnitTest {
@Test
void whenReadingAFile_thenReadsCharByChar() {
StringBuilder result = new StringBuilder();
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
int i = fr.read();
while(i != -1) {
result.append((char)i);
i = fr.read();
}
} catch (IOException e) {
e.printStackTrace();
}
assertEquals("qwerty", result.toString());
}
}
package com.baeldung.bufferedreadervsfilereader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.FileReader;
import java.io.IOException;
import org.junit.jupiter.api.Test;
class FileReaderUnitTest {
@Test
void whenReadingAFile_thenReadsCharByChar() {
StringBuilder result = new StringBuilder();
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
int i = fr.read();
while(i != -1) {
result.append((char)i);
i = fr.read();
}
} catch (IOException e) {
e.printStackTrace();
}
assertEquals("qwerty", result.toString());
}
}

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