commit
3f5bc977bf
@ -8,7 +8,6 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
|||||||
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
|
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
|
||||||
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
||||||
- [Converting Between Roman and Arabic Numerals in Java](https://www.baeldung.com/java-convert-roman-arabic)
|
- [Converting Between Roman and Arabic Numerals in Java](https://www.baeldung.com/java-convert-roman-arabic)
|
||||||
- [Practical Java Examples of the Big O Notation](https://www.baeldung.com/java-algorithm-complexity)
|
|
||||||
- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted)
|
- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted)
|
||||||
- [Checking if a Java Graph Has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
|
- [Checking if a Java Graph Has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
|
||||||
- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique)
|
- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique)
|
||||||
|
@ -7,7 +7,6 @@ import static org.mockserver.model.HttpResponse.response;
|
|||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.ServerSocket;
|
import java.net.ServerSocket;
|
||||||
import java.net.URISyntaxException;
|
|
||||||
|
|
||||||
import org.apache.http.HttpStatus;
|
import org.apache.http.HttpStatus;
|
||||||
import org.junit.jupiter.api.AfterAll;
|
import org.junit.jupiter.api.AfterAll;
|
||||||
@ -18,22 +17,19 @@ import org.mockserver.integration.ClientAndServer;
|
|||||||
public class GetRequestMockServer {
|
public class GetRequestMockServer {
|
||||||
|
|
||||||
public static ClientAndServer mockServer;
|
public static ClientAndServer mockServer;
|
||||||
public static String serviceOneUrl;
|
|
||||||
public static String serviceTwoUrl;
|
|
||||||
|
|
||||||
public static int serverPort;
|
public static int serverPort;
|
||||||
|
|
||||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
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 SECURITY_PATH = "/spring-security-rest-basic-auth/api/foos/1";
|
||||||
public static final String METHOD = "GET";
|
|
||||||
|
public static final String UPLOAD_PATH = "/spring-mvc-java/stub/multipart";
|
||||||
|
|
||||||
@BeforeAll
|
@BeforeAll
|
||||||
static void startServer() throws IOException {
|
static void startServer() throws IOException {
|
||||||
serverPort = getFreePort();
|
serverPort = getFreePort();
|
||||||
System.out.println("Free port "+serverPort);
|
System.out.println("Free port " + serverPort);
|
||||||
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
|
|
||||||
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
|
|
||||||
mockServer = startClientAndServer(serverPort);
|
mockServer = startClientAndServer(serverPort);
|
||||||
mockGetRequest();
|
mockGetRequest();
|
||||||
}
|
}
|
||||||
@ -44,33 +40,36 @@ public class GetRequestMockServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static void mockGetRequest() {
|
private static void mockGetRequest() {
|
||||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
|
||||||
.when(
|
MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort);
|
||||||
request()
|
|
||||||
.withPath(PATH_ONE)
|
client.when(
|
||||||
.withMethod(METHOD),
|
request()
|
||||||
exactly(5)
|
.withPath(SECURITY_PATH)
|
||||||
)
|
.withMethod("GET"),
|
||||||
.respond(
|
exactly(1)
|
||||||
response()
|
)
|
||||||
.withStatusCode(HttpStatus.SC_OK)
|
.respond(
|
||||||
.withBody("{\"status\":\"ok\"}")
|
response()
|
||||||
);
|
.withStatusCode(HttpStatus.SC_OK)
|
||||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
.withBody("{\"status\":\"ok\"}")
|
||||||
.when(
|
);
|
||||||
request()
|
|
||||||
.withPath(PATH_TWO)
|
client.when(
|
||||||
.withMethod(METHOD),
|
request()
|
||||||
exactly(1)
|
.withPath(UPLOAD_PATH)
|
||||||
)
|
.withMethod("POST"),
|
||||||
.respond(
|
exactly(4)
|
||||||
response()
|
)
|
||||||
.withStatusCode(HttpStatus.SC_OK)
|
.respond(
|
||||||
.withBody("{\"status\":\"ok\"}")
|
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)) {
|
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||||
return serverSocket.getLocalPort();
|
return serverSocket.getLocalPort();
|
||||||
}
|
}
|
||||||
|
@ -19,7 +19,7 @@ class HttpClientCancelRequestLiveTest {
|
|||||||
void whenRequestIsCanceled_thenCorrect() throws IOException {
|
void whenRequestIsCanceled_thenCorrect() throws IOException {
|
||||||
HttpGet request = new HttpGet(SAMPLE_URL);
|
HttpGet request = new HttpGet(SAMPLE_URL);
|
||||||
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
||||||
httpClient.execute(request, response -> {
|
httpClient.execute(request, response -> {
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
|
|
||||||
System.out.println("----------------------------------------");
|
System.out.println("----------------------------------------");
|
||||||
@ -28,6 +28,12 @@ class HttpClientCancelRequestLiveTest {
|
|||||||
System.out.println("Response content length: " + entity.getContentLength());
|
System.out.println("Response content length: " + entity.getContentLength());
|
||||||
}
|
}
|
||||||
System.out.println("----------------------------------------");
|
System.out.println("----------------------------------------");
|
||||||
|
|
||||||
|
if (entity != null) {
|
||||||
|
// Closes this stream and releases any system resources
|
||||||
|
entity.close();
|
||||||
|
}
|
||||||
|
|
||||||
// Do not feel like reading the response body
|
// Do not feel like reading the response body
|
||||||
// Call abort on the request object
|
// Call abort on the request object
|
||||||
request.abort();
|
request.abort();
|
||||||
|
@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
|
|||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
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.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
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.MultipartEntityBuilder;
|
||||||
import org.apache.hc.client5.http.entity.mime.StringBody;
|
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.CloseableHttpClient;
|
||||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
|
||||||
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
||||||
|
|
||||||
import org.apache.hc.core5.http.ContentType;
|
import org.apache.hc.core5.http.ContentType;
|
||||||
@ -28,9 +28,7 @@ import java.io.InputStream;
|
|||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
|
|
||||||
import com.baeldung.httpclient.handler.CustomHttpClientResponseHandler;
|
class HttpClientMultipartLiveTest extends GetRequestMockServer {
|
||||||
|
|
||||||
class HttpClientMultipartLiveTest {
|
|
||||||
|
|
||||||
// No longer available
|
// No longer available
|
||||||
// private static final String SERVER = "http://echo.200please.com";
|
// private static final String SERVER = "http://echo.200please.com";
|
||||||
@ -45,13 +43,15 @@ class HttpClientMultipartLiveTest {
|
|||||||
@BeforeEach
|
@BeforeEach
|
||||||
public void before() {
|
public void before() {
|
||||||
post = new HttpPost(SERVER);
|
post = new HttpPost(SERVER);
|
||||||
|
String URL = "http://localhost:" + serverPort + "/spring-mvc-java/stub/multipart";
|
||||||
|
post = new HttpPost(URL);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
|
void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
|
||||||
final URL url = Thread.currentThread()
|
final URL url = Thread.currentThread()
|
||||||
.getContextClassLoader()
|
.getContextClassLoader()
|
||||||
.getResource("uploads/" + TEXTFILENAME);
|
.getResource("uploads/" + TEXTFILENAME);
|
||||||
|
|
||||||
final File file = new File(url.getPath());
|
final File file = new File(url.getPath());
|
||||||
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
|
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
|
||||||
@ -66,27 +66,28 @@ class HttpClientMultipartLiveTest {
|
|||||||
final HttpEntity entity = builder.build();
|
final HttpEntity entity = builder.build();
|
||||||
|
|
||||||
post.setEntity(entity);
|
post.setEntity(entity);
|
||||||
try(CloseableHttpClient client = HttpClientBuilder.create()
|
try (CloseableHttpClient client = HttpClientBuilder.create()
|
||||||
.build();
|
.build()) {
|
||||||
|
|
||||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
client.execute(post, response -> {
|
||||||
.execute(post, new CustomHttpClientResponseHandler())){
|
final int statusCode = response.getCode();
|
||||||
final int statusCode = response.getCode();
|
final String responseString = getContent(response.getEntity());
|
||||||
final String responseString = getContent(response.getEntity());
|
final String contentTypeInHeader = getContentTypeHeader();
|
||||||
final String contentTypeInHeader = getContentTypeHeader();
|
|
||||||
|
|
||||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
assertTrue(contentTypeInHeader.contains("multipart/form-data"));
|
||||||
System.out.println(responseString);
|
System.out.println(responseString);
|
||||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||||
|
return response;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
|
void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
|
||||||
final URL url = Thread.currentThread()
|
final URL url = Thread.currentThread()
|
||||||
.getContextClassLoader()
|
.getContextClassLoader()
|
||||||
.getResource("uploads/" + TEXTFILENAME);
|
.getResource("uploads/" + TEXTFILENAME);
|
||||||
final File file = new File(url.getPath());
|
final File file = new File(url.getPath());
|
||||||
final String message = "This is a multipart post";
|
final String message = "This is a multipart post";
|
||||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||||
@ -96,30 +97,31 @@ class HttpClientMultipartLiveTest {
|
|||||||
final HttpEntity entity = builder.build();
|
final HttpEntity entity = builder.build();
|
||||||
post.setEntity(entity);
|
post.setEntity(entity);
|
||||||
|
|
||||||
try(CloseableHttpClient client = HttpClientBuilder.create()
|
try (CloseableHttpClient client = HttpClientBuilder.create()
|
||||||
.build();
|
.build()) {
|
||||||
|
|
||||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
client.execute(post, response -> {
|
||||||
.execute(post, new CustomHttpClientResponseHandler())){
|
|
||||||
|
|
||||||
final int statusCode = response.getCode();
|
final int statusCode = response.getCode();
|
||||||
final String responseString = getContent(response.getEntity());
|
final String responseString = getContent(response.getEntity());
|
||||||
final String contentTypeInHeader = getContentTypeHeader();
|
final String contentTypeInHeader = getContentTypeHeader();
|
||||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
assertTrue(contentTypeInHeader.contains("multipart/form-data"));
|
||||||
System.out.println(responseString);
|
System.out.println(responseString);
|
||||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||||
|
return response;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
|
void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
|
||||||
final URL url = Thread.currentThread()
|
final URL url = Thread.currentThread()
|
||||||
.getContextClassLoader()
|
.getContextClassLoader()
|
||||||
.getResource("uploads/" + ZIPFILENAME);
|
.getResource("uploads/" + ZIPFILENAME);
|
||||||
final URL url2 = Thread.currentThread()
|
final URL url2 = Thread.currentThread()
|
||||||
.getContextClassLoader()
|
.getContextClassLoader()
|
||||||
.getResource("uploads/" + IMAGEFILENAME);
|
.getResource("uploads/" + IMAGEFILENAME);
|
||||||
final InputStream inputStream = new FileInputStream(url.getPath());
|
final InputStream inputStream = new FileInputStream(url.getPath());
|
||||||
final File file = new File(url2.getPath());
|
final File file = new File(url2.getPath());
|
||||||
final String message = "This is a multipart post";
|
final String message = "This is a multipart post";
|
||||||
@ -131,25 +133,25 @@ class HttpClientMultipartLiveTest {
|
|||||||
final HttpEntity entity = builder.build();
|
final HttpEntity entity = builder.build();
|
||||||
post.setEntity(entity);
|
post.setEntity(entity);
|
||||||
|
|
||||||
try(CloseableHttpClient client = HttpClientBuilder.create()
|
try (CloseableHttpClient client = HttpClientBuilder.create()
|
||||||
.build();
|
.build()) {
|
||||||
|
|
||||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
client.execute(post, response -> {
|
||||||
.execute(post, new CustomHttpClientResponseHandler())){
|
final int statusCode = response.getCode();
|
||||||
|
final String responseString = getContent(response.getEntity());
|
||||||
final int statusCode = response.getCode();
|
final String contentTypeInHeader = getContentTypeHeader();
|
||||||
final String responseString = getContent(response.getEntity());
|
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||||
final String contentTypeInHeader = getContentTypeHeader();
|
assertTrue(contentTypeInHeader.contains("multipart/form-data;"));
|
||||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
System.out.println(responseString);
|
||||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||||
System.out.println(responseString);
|
inputStream.close();
|
||||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
return response;
|
||||||
inputStream.close();
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
|
void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException, ParseException {
|
||||||
final String message = "This is a multipart post";
|
final String message = "This is a multipart post";
|
||||||
final byte[] bytes = "binary code".getBytes();
|
final byte[] bytes = "binary code".getBytes();
|
||||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||||
@ -159,21 +161,20 @@ class HttpClientMultipartLiveTest {
|
|||||||
final HttpEntity entity = builder.build();
|
final HttpEntity entity = builder.build();
|
||||||
post.setEntity(entity);
|
post.setEntity(entity);
|
||||||
|
|
||||||
try(CloseableHttpClient client = HttpClientBuilder.create()
|
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
|
||||||
.build();
|
.build()) {
|
||||||
|
|
||||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
httpClient.execute(post, response -> {
|
||||||
.execute(post, new CustomHttpClientResponseHandler())){
|
final int statusCode = response.getCode();
|
||||||
|
final String responseString = getContent(response.getEntity());
|
||||||
final int statusCode = response.getCode();
|
final String contentTypeInHeader = getContentTypeHeader();
|
||||||
final String responseString = getContent(response.getEntity());
|
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||||
final String contentTypeInHeader = getContentTypeHeader();
|
assertTrue(contentTypeInHeader.contains("multipart/form-data;"));
|
||||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
System.out.println(responseString);
|
||||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||||
System.out.println(responseString);
|
return response;
|
||||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// UTIL
|
// UTIL
|
||||||
|
@ -43,7 +43,7 @@ public class HttpClientLiveTest {
|
|||||||
|
|
||||||
@Test(expected = ConnectTimeoutException.class)
|
@Test(expected = ConnectTimeoutException.class)
|
||||||
public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException {
|
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);
|
final HttpGet request = new HttpGet(SAMPLE_URL);
|
||||||
request.setConfig(requestConfig);
|
request.setConfig(requestConfig);
|
||||||
response = instance.execute(request);
|
response = instance.execute(request);
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
package com.baeldung.httpclient.base;
|
package com.baeldung.httpclient.base;
|
||||||
|
|
||||||
|
import com.baeldung.httpclient.GetRequestMockServer;
|
||||||
import com.baeldung.httpclient.ResponseUtil;
|
import com.baeldung.httpclient.ResponseUtil;
|
||||||
import org.apache.http.auth.AuthScope;
|
import org.apache.http.auth.AuthScope;
|
||||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
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.BasicCredentialsProvider;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* NOTE : Need module spring-security-rest-basic-auth to be running
|
* NOTE : Need module spring-security-rest-basic-auth to be running
|
||||||
*/
|
*/
|
||||||
public class HttpClientSandboxLiveTest {
|
public class HttpClientSandboxLiveTest extends GetRequestMockServer {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
|
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
|
||||||
@ -26,7 +27,7 @@ public class HttpClientSandboxLiveTest {
|
|||||||
|
|
||||||
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
|
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);
|
final CloseableHttpResponse response = client.execute(httpGet);
|
||||||
|
|
||||||
System.out.println(response.getStatusLine());
|
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;
|
|
||||||
}
|
|
||||||
}
|
|
@ -199,33 +199,7 @@
|
|||||||
<filtering>true</filtering>
|
<filtering>true</filtering>
|
||||||
</resource>
|
</resource>
|
||||||
</resources>
|
</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>
|
</build>
|
||||||
|
|
||||||
<profiles>
|
<profiles>
|
||||||
@ -233,26 +207,6 @@
|
|||||||
<id>live</id>
|
<id>live</id>
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<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>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
@ -269,9 +223,6 @@
|
|||||||
<includes>
|
<includes>
|
||||||
<include>**/*LiveTest.java</include>
|
<include>**/*LiveTest.java</include>
|
||||||
</includes>
|
</includes>
|
||||||
<systemPropertyVariables>
|
|
||||||
<webTarget>cargo</webTarget>
|
|
||||||
</systemPropertyVariables>
|
|
||||||
</configuration>
|
</configuration>
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
@ -291,7 +242,6 @@
|
|||||||
<httpclient.version>4.5.14</httpclient.version>
|
<httpclient.version>4.5.14</httpclient.version>
|
||||||
<mockserver.version>5.11.2</mockserver.version>
|
<mockserver.version>5.11.2</mockserver.version>
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
|
||||||
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
|
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
|
||||||
</properties>
|
</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 java.security.GeneralSecurityException;
|
||||||
|
|
||||||
import javax.net.ssl.SSLContext;
|
import javax.net.ssl.SSLContext;
|
||||||
import javax.net.ssl.SSLPeerUnverifiedException;
|
import javax.net.ssl.SSLHandshakeException;
|
||||||
|
|
||||||
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpResponse;
|
||||||
import org.apache.http.client.methods.HttpGet;
|
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.http.client.HttpComponentsClientHttpRequestFactory;
|
||||||
import org.springframework.web.client.RestTemplate;
|
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
|
@Test
|
||||||
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
|
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
|
||||||
@ -54,13 +54,13 @@ class ClientLiveTest {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
|
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));
|
assertThat(response.getStatusCode().value(), equalTo(200));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
|
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
|
||||||
final HttpGet getMethod = new HttpGet(urlOverHttps);
|
final HttpGet getMethod = new HttpGet(simplePathUrl);
|
||||||
|
|
||||||
try (final CloseableHttpClient httpClient = HttpClients.custom()
|
try (final CloseableHttpClient httpClient = HttpClients.custom()
|
||||||
.setSSLHostnameVerifier(new NoopHostnameVerifier())
|
.setSSLHostnameVerifier(new NoopHostnameVerifier())
|
||||||
@ -80,20 +80,22 @@ class ClientLiveTest {
|
|||||||
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
|
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||||
requestFactory.setHttpClient(httpClient);
|
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));
|
assertThat(response.getStatusCode().value(), equalTo(200));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenHttpsUrlIsConsumed_thenException() {
|
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);
|
HttpGet getMethod = new HttpGet(urlOverHttps);
|
||||||
|
|
||||||
assertThrows(SSLPeerUnverifiedException.class, () -> {
|
assertThrows(SSLHandshakeException.class, () -> {
|
||||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||||
HttpResponse response = httpClient.execute(getMethod);
|
HttpResponse response = httpClient.execute(getMethod);
|
||||||
assertThat(response.getStatusLine()
|
assertThat(response.getStatusLine()
|
||||||
.getStatusCode(), equalTo(200));
|
.getStatusCode(), equalTo(200));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.client;
|
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.MatcherAssert.assertThat;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
|
||||||
@ -89,4 +88,5 @@ public class RestClientV4LiveManualTest {
|
|||||||
HttpResponse response = httpClient.execute(getMethod);
|
HttpResponse response = httpClient.execute(getMethod);
|
||||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
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.apache.http.ssl.SSLContexts;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.baeldung.GetRequestMockServer;
|
||||||
|
|
||||||
class HttpAsyncClientV4LiveTest extends GetRequestMockServer {
|
class HttpAsyncClientV4LiveTest extends GetRequestMockServer {
|
||||||
|
|
||||||
|
@ -44,7 +44,9 @@ public class HttpClientCancelRequestV4LiveTest {
|
|||||||
System.out.println(response.getStatusLine());
|
System.out.println(response.getStatusLine());
|
||||||
if (entity != null) {
|
if (entity != null) {
|
||||||
System.out.println("Response content length: " + entity.getContentLength());
|
System.out.println("Response content length: " + entity.getContentLength());
|
||||||
|
entity.getContent().close();
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println("----------------------------------------");
|
System.out.println("----------------------------------------");
|
||||||
|
|
||||||
// Do not feel like reading the response body
|
// 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.Disabled;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
class HttpClientTimeoutV4LiveTest {
|
import com.baeldung.GetRequestMockServer;
|
||||||
|
|
||||||
|
class HttpClientTimeoutV4LiveTest extends GetRequestMockServer {
|
||||||
|
|
||||||
private CloseableHttpResponse response;
|
private CloseableHttpResponse response;
|
||||||
|
|
||||||
@ -97,7 +99,7 @@ class HttpClientTimeoutV4LiveTest {
|
|||||||
int timeout = 20; // seconds
|
int timeout = 20; // seconds
|
||||||
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000)
|
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000)
|
||||||
.setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
|
.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);
|
getMethod.setConfig(requestConfig);
|
||||||
|
|
||||||
int hardTimeout = 5; // seconds
|
int hardTimeout = 5; // seconds
|
||||||
|
@ -13,13 +13,15 @@ import org.apache.http.impl.client.HttpClientBuilder;
|
|||||||
import org.apache.http.util.EntityUtils;
|
import org.apache.http.util.EntityUtils;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.baeldung.GetRequestMockServer;
|
||||||
|
|
||||||
class ApacheHttpClientUnitTest extends GetRequestMockServer {
|
class ApacheHttpClientUnitTest extends GetRequestMockServer {
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
|
void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
|
||||||
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
|
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
|
||||||
HttpGet httpGet = new HttpGet(serviceOneUrl);
|
HttpGet httpGet = new HttpGet(simplePathUrl);
|
||||||
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
|
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
EntityUtils.consume(entity);
|
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,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>apache-poi-2</artifactId>
|
<artifactId>apache-poi-2</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
@ -100,7 +100,6 @@
|
|||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
||||||
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
|
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-groovy-2</artifactId>
|
<artifactId>core-groovy-2</artifactId>
|
||||||
@ -117,11 +118,11 @@
|
|||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>2.20.1</version>
|
<version>2.20.1</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<useFile>false</useFile>
|
<useFile>false</useFile>
|
||||||
<includes>
|
<includes>
|
||||||
<include>**/*Test.java</include>
|
<include>**/*Test.java</include>
|
||||||
<include>**/*Spec.java</include>
|
<include>**/*Spec.java</include>
|
||||||
</includes>
|
</includes>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<!-- Maven Assembly Plugin: needed to run the jar through command line -->
|
<!-- Maven Assembly Plugin: needed to run the jar through command line -->
|
||||||
|
@ -4,29 +4,84 @@ import org.junit.jupiter.api.Assertions;
|
|||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.net.Socket;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
import java.net.http.HttpClient;
|
import java.net.http.HttpClient;
|
||||||
import java.net.http.HttpRequest;
|
import java.net.http.HttpRequest;
|
||||||
import java.net.http.HttpResponse;
|
import java.net.http.HttpResponse;
|
||||||
|
import java.security.KeyManagementException;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.security.cert.X509Certificate;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import javax.net.ssl.SSLContext;
|
||||||
|
import javax.net.ssl.SSLEngine;
|
||||||
|
import javax.net.ssl.TrustManager;
|
||||||
|
import javax.net.ssl.X509ExtendedTrustManager;
|
||||||
|
|
||||||
public class HttpClientSSLBypassUnitTest {
|
public class HttpClientSSLBypassUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenHttpsRequest_thenCorrect() throws IOException, InterruptedException {
|
public void givenDisableUsingJVMProperty_whenByPassCertificationVerification_thenSuccessHttpResponse() throws IOException, InterruptedException {
|
||||||
final Properties props = System.getProperties();
|
final Properties props = System.getProperties();
|
||||||
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());
|
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());
|
||||||
|
|
||||||
HttpClient httpClient = HttpClient.newBuilder()
|
HttpClient httpClient = HttpClient.newBuilder()
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
HttpRequest request = HttpRequest.newBuilder()
|
HttpRequest request = HttpRequest.newBuilder()
|
||||||
.uri(URI.create("https://wrong.host.badssl.com/"))
|
.uri(URI.create("https://wrong.host.badssl.com/"))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.FALSE.toString());
|
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.FALSE.toString());
|
||||||
|
|
||||||
Assertions.assertEquals(200, response.statusCode());
|
Assertions.assertEquals(200, response.statusCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMockTrustManager_whenByPassCertificateVerification_thenSuccessHttpResponse() throws IOException, InterruptedException, NoSuchAlgorithmException, KeyManagementException, URISyntaxException {
|
||||||
|
SSLContext sslContext = SSLContext.getInstance("SSL"); // OR TLS
|
||||||
|
sslContext.init(null, new TrustManager[]{ MOCK_TRUST_MANAGER }, new SecureRandom());
|
||||||
|
HttpClient httpClient = HttpClient.newBuilder().sslContext(sslContext).build();
|
||||||
|
HttpRequest request = HttpRequest.newBuilder()
|
||||||
|
.uri(new URI("https://wrong.host.badssl.com/"))
|
||||||
|
.build();
|
||||||
|
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
|
Assertions.assertEquals(200, response.statusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private static final TrustManager MOCK_TRUST_MANAGER = new X509ExtendedTrustManager() {
|
||||||
|
@Override
|
||||||
|
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
||||||
|
return new java.security.cert.X509Certificate[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) {
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
@ -72,7 +72,7 @@
|
|||||||
<mainClass>org.openjdk.jmh.Main</mainClass>
|
<mainClass>org.openjdk.jmh.Main</mainClass>
|
||||||
</transformer>
|
</transformer>
|
||||||
<transformer
|
<transformer
|
||||||
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
|
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
|
||||||
</transformers>
|
</transformers>
|
||||||
<filters>
|
<filters>
|
||||||
<filter>
|
<filter>
|
||||||
|
@ -1,2 +1,3 @@
|
|||||||
## Relevant Articles
|
## Relevant Articles
|
||||||
- [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values)
|
- [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)
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.core-java-modules</groupId>
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.convertpaths;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.nio.file.FileSystems;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
|
public class RelativePathConverter {
|
||||||
|
|
||||||
|
public static String convertToAbsoluteUsePathsClass(String relativePath) {
|
||||||
|
Path absolutePath = Paths.get(relativePath).toAbsolutePath();
|
||||||
|
return absolutePath.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String convertToAbsoluteUseFileClass(String relativePath) {
|
||||||
|
File file = new File(relativePath);
|
||||||
|
return file.getAbsolutePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String convertToAbsoluteUseFileSystemsClass(String relativePath) {
|
||||||
|
Path absolutePath = FileSystems.getDefault().getPath(relativePath).toAbsolutePath();
|
||||||
|
return absolutePath.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
String relativePath = "myFolder/myFile.txt";
|
||||||
|
String absolutePath = convertToAbsoluteUseFileSystemsClass(relativePath);
|
||||||
|
System.out.println("Absolute Path: " + absolutePath);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.convertpaths;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class RelativePathConverterUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRelativePath_whenConvertingToAbsolutePath_thenPrintOutput() {
|
||||||
|
String relativePath = "data/sample.txt";
|
||||||
|
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUsePathsClass(relativePath));
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUseFileClass(relativePath));
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUseFileSystemsClass(relativePath));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAbsolutePath_whenConvertingToAbsolutePath_thenPrintOutput() {
|
||||||
|
String absolutePath = "/var/www/index.html";
|
||||||
|
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUsePathsClass(absolutePath));
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUseFileClass(absolutePath));
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUseFileSystemsClass(absolutePath));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptyPath_whenConvertingToAbsolutePath_thenPrintOutput() {
|
||||||
|
String emptyPath = "";
|
||||||
|
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUsePathsClass(emptyPath));
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUseFileClass(emptyPath));
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUseFileSystemsClass(emptyPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenParentDirectoryPath_whenConvertingToAbsolutePath_thenPrintOutput() {
|
||||||
|
String relativePath = "../data/sample.txt";
|
||||||
|
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUsePathsClass(relativePath));
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUseFileClass(relativePath));
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUseFileSystemsClass(relativePath));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRelativePathContainingDots_whenConvertingToAbsolutePath_thenPrintOutput() {
|
||||||
|
String relativePath = "././data/sample.txt";
|
||||||
|
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUsePathsClass(relativePath));
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUseFileClass(relativePath));
|
||||||
|
System.out.println(RelativePathConverter.convertToAbsoluteUseFileSystemsClass(relativePath));
|
||||||
|
}
|
||||||
|
}
|
@ -7,7 +7,7 @@ import java.net.URISyntaxException;
|
|||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
public class ZipEntryReaderTest {
|
public class ZipEntryReaderUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenZipFile_thenReadEntriesAndValidateContent() throws URISyntaxException, IOException {
|
public void givenZipFile_thenReadEntriesAndValidateContent() throws URISyntaxException, IOException {
|
@ -1,55 +1,55 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>core-java-9-jigsaw</artifactId>
|
<artifactId>core-java-9-jigsaw</artifactId>
|
||||||
<version>0.2-SNAPSHOT</version>
|
<version>0.2-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>library-core</artifactId>
|
<artifactId>library-core</artifactId>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<maven.compiler.source>19</maven.compiler.source>
|
<maven.compiler.source>19</maven.compiler.source>
|
||||||
<maven.compiler.target>19</maven.compiler.target>
|
<maven.compiler.target>19</maven.compiler.target>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.junit.jupiter</groupId>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
<artifactId>junit-jupiter-api</artifactId>
|
<artifactId>junit-jupiter-api</artifactId>
|
||||||
<version>5.9.2</version>
|
<version>5.9.2</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.junit.jupiter</groupId>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
<artifactId>junit-jupiter-engine</artifactId>
|
<artifactId>junit-jupiter-engine</artifactId>
|
||||||
<version>5.9.2</version>
|
<version>5.9.2</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.8.1</version>
|
<version>3.8.1</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<release>9</release>
|
<release>9</release>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>3.0.0-M5</version>
|
<version>3.0.0-M5</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<useModulePath>false</useModulePath>
|
<useModulePath>false</useModulePath>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
</project>
|
</project>
|
@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-java-collections-5</artifactId>
|
<artifactId>core-java-collections-5</artifactId>
|
||||||
<name>core-java-collections-5</name>
|
<name>core-java-collections-5</name>
|
||||||
|
@ -0,0 +1,74 @@
|
|||||||
|
package com.baeldung.convertlisttoarray;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.google.common.primitives.Longs;
|
||||||
|
|
||||||
|
public class LongListToLongArrayConversionUnitTest {
|
||||||
|
|
||||||
|
private List<Long> list;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() {
|
||||||
|
list = Arrays.asList(1L, 2L, 3L, 4L, 5L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenALongList_whenConvertWithListToArray_thenReturnLongArray() {
|
||||||
|
|
||||||
|
// Init an array with the same size as the list to convert
|
||||||
|
Long[] arrayWithSettedSize = new Long[list.size()];
|
||||||
|
arrayWithSettedSize = list.toArray(arrayWithSettedSize);
|
||||||
|
assertTrue(list.size() == arrayWithSettedSize.length);
|
||||||
|
|
||||||
|
// Init an empty array
|
||||||
|
Long[] arrayWithNoSettedSize = new Long[0];
|
||||||
|
arrayWithNoSettedSize = list.toArray(arrayWithNoSettedSize);
|
||||||
|
assertTrue(list.size() == arrayWithNoSettedSize.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenALongList_whenConvertWithLongsToArray_thenReturnLongArray() {
|
||||||
|
// Convertion using Guava library Longs.toArray() method
|
||||||
|
long[] array = Longs.toArray(list);
|
||||||
|
assertTrue(compareListWithArray(list, array));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenALongList_whenConvertWithStreamMapToLong_thenReturnLongArray() {
|
||||||
|
// Using mapToLong() - lambda expression
|
||||||
|
long[] arrayUsingLambda = list.stream()
|
||||||
|
.mapToLong(l -> l)
|
||||||
|
.toArray();
|
||||||
|
assertTrue(compareListWithArray(list, arrayUsingLambda));
|
||||||
|
|
||||||
|
// Using mapToLong() - method reference
|
||||||
|
long[] arrayUsingMethodReference = list.stream()
|
||||||
|
.mapToLong(Long::longValue)
|
||||||
|
.toArray();
|
||||||
|
assertTrue(compareListWithArray(list, arrayUsingMethodReference));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean compareListWithArray(List<Long> list, long[] array) {
|
||||||
|
// Check if the sizes of the array and list are equal
|
||||||
|
if (array.length != list.size()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compare each element of the array with the corresponding element in the list
|
||||||
|
for (int i = 0; i < array.length; i++) {
|
||||||
|
// Convert Long to long for comparison
|
||||||
|
if (array[i] != list.get(i)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
@ -9,5 +9,5 @@ This module contains articles about the Java List collection
|
|||||||
- [Check if a List Contains an Element From Another List in Java](https://www.baeldung.com/java-check-elements-between-lists)
|
- [Check if a List Contains an Element From Another List in Java](https://www.baeldung.com/java-check-elements-between-lists)
|
||||||
- [Array vs. List Performance in Java](https://www.baeldung.com/java-array-vs-list-performance)
|
- [Array vs. List Performance in Java](https://www.baeldung.com/java-array-vs-list-performance)
|
||||||
- [Set Default Value for Elements in List](https://www.baeldung.com/java-list-set-default-values)
|
- [Set Default Value for Elements in List](https://www.baeldung.com/java-list-set-default-values)
|
||||||
- [Get Unique Values From an ArrayList In Java](https://www.baeldung.com/java-unique-values-arraylist)
|
- [Get Unique Values From an ArrayList in Java](https://www.baeldung.com/java-unique-values-arraylist)
|
||||||
- [Converting a Java List to a Json Array](https://www.baeldung.com/java-converting-list-to-json-array)
|
- [Converting a Java List to a Json Array](https://www.baeldung.com/java-converting-list-to-json-array)
|
||||||
|
@ -14,7 +14,7 @@
|
|||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.openjdk.jmh</groupId>
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
<artifactId>jmh-core</artifactId>
|
<artifactId>jmh-core</artifactId>
|
||||||
<version>1.36</version>
|
<version>1.36</version>
|
||||||
@ -45,7 +45,7 @@
|
|||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<jmh.version>1.21</jmh.version>
|
<jmh.version>1.21</jmh.version>
|
||||||
<commons-lang.version>2.2</commons-lang.version>
|
<commons-lang.version>2.2</commons-lang.version>
|
||||||
<commons-lang3.version>3.12.0</commons-lang3.version>
|
<commons-lang3.version>3.12.0</commons-lang3.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
@ -3,3 +3,5 @@
|
|||||||
- [Convert Hashmap to JSON Object in Java](https://www.baeldung.com/java-convert-hashmap-to-json-object)
|
- [Convert Hashmap to JSON Object in Java](https://www.baeldung.com/java-convert-hashmap-to-json-object)
|
||||||
- [Converting Map<String, Object> to Map<String, String> in Java](https://www.baeldung.com/java-converting-map-string-object-to-string-string)
|
- [Converting Map<String, Object> to Map<String, String> in Java](https://www.baeldung.com/java-converting-map-string-object-to-string-string)
|
||||||
- [Converting Object To Map in Java](https://www.baeldung.com/java-convert-object-to-map)
|
- [Converting Object To Map in Java](https://www.baeldung.com/java-convert-object-to-map)
|
||||||
|
- [Difference Between Map.clear() and Instantiating a New Map](https://www.baeldung.com/java-map-clear-vs-new-map)
|
||||||
|
- [Converting JsonNode Object to Map](https://www.baeldung.com/jackson-jsonnode-map)
|
||||||
|
@ -0,0 +1,98 @@
|
|||||||
|
package com.baeldung.map.changekey;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class Player {
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public Player(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!(o instanceof Player)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Player player = (Player) o;
|
||||||
|
|
||||||
|
return name.equals(player.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return name.hashCode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class HashmapChangeKeyUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRemoveThenPutWithTheNewKey_thenGetExpectedResult() {
|
||||||
|
Map<String, Integer> playerMap = new HashMap<>();
|
||||||
|
|
||||||
|
playerMap.put("Kai", 42);
|
||||||
|
playerMap.put("Amanda", 88);
|
||||||
|
playerMap.put("Tom", 200);
|
||||||
|
|
||||||
|
// now replace Kai with Eric
|
||||||
|
playerMap.put("Eric", playerMap.remove("Kai"));
|
||||||
|
|
||||||
|
assertFalse(playerMap.containsKey("Kai"));
|
||||||
|
assertTrue(playerMap.containsKey("Eric"));
|
||||||
|
assertEquals(42, playerMap.get("Eric"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenChangeTheKey_thenMayNotGetExpectedResult() {
|
||||||
|
Map<Player, Integer> myMap = new HashMap<>();
|
||||||
|
Player kai = new Player("Kai");
|
||||||
|
Player tom = new Player("Tom");
|
||||||
|
Player amanda = new Player("Amanda");
|
||||||
|
|
||||||
|
myMap.put(kai, 42);
|
||||||
|
myMap.put(amanda, 88);
|
||||||
|
myMap.put(tom, 200);
|
||||||
|
|
||||||
|
assertTrue(myMap.containsKey(kai));
|
||||||
|
|
||||||
|
//change Kai's name to Eric
|
||||||
|
kai.setName("Eric");
|
||||||
|
assertEquals("Eric", kai.getName());
|
||||||
|
|
||||||
|
Player eric = new Player("Eric");
|
||||||
|
assertEquals(eric, kai);
|
||||||
|
|
||||||
|
// the map contains neither Kai nor Eric:
|
||||||
|
assertFalse(myMap.containsKey(kai));
|
||||||
|
assertFalse(myMap.containsKey(eric));
|
||||||
|
|
||||||
|
// although the Player("Eric") exists:
|
||||||
|
long ericCount = myMap.keySet()
|
||||||
|
.stream()
|
||||||
|
.filter(player -> player.getName()
|
||||||
|
.equals("Eric"))
|
||||||
|
.count();
|
||||||
|
|
||||||
|
assertEquals(1, ericCount);
|
||||||
|
}
|
||||||
|
}
|
@ -6,3 +6,4 @@
|
|||||||
- [Using a Mutex Object in Java](https://www.baeldung.com/java-mutex)
|
- [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)
|
- [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)
|
- [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,6 @@ This module contains articles about basic Java concurrency.
|
|||||||
- [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await)
|
- [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)
|
- [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)
|
- [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)
|
||||||
|
- [CompletableFuture allOf().join() vs. CompletableFuture.join()](https://www.baeldung.com/java-completablefuture-allof-join)
|
||||||
- [[<-- Prev]](../core-java-concurrency-basic-2)
|
- [[<-- Prev]](../core-java-concurrency-basic-2)
|
||||||
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.concurrent.completablefuture.threadpool;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
public class CustomCompletableFuture<T> extends CompletableFuture<T> {
|
||||||
|
private static final Executor executor = Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "Custom-Single-Thread"));
|
||||||
|
|
||||||
|
public static <TYPE> CustomCompletableFuture<TYPE> supplyAsync(Supplier<TYPE> supplier) {
|
||||||
|
CustomCompletableFuture<TYPE> future = new CustomCompletableFuture<>();
|
||||||
|
executor.execute(() -> {
|
||||||
|
try {
|
||||||
|
future.complete(supplier.get());
|
||||||
|
} catch (Exception ex) {
|
||||||
|
future.completeExceptionally(ex);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return future;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Executor defaultExecutor() {
|
||||||
|
return executor;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,112 @@
|
|||||||
|
package com.baeldung.concurrent.completablefuture.allofvsjoin;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class CompletableFutureAllOffUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallingJoin_thenBlocksThreadAndGetValue() {
|
||||||
|
CompletableFuture<String> future = waitAndReturn(1_000, "Harry");
|
||||||
|
assertEquals("Harry", future.join());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallingJoin_thenBlocksThreadAndThrowException() {
|
||||||
|
CompletableFuture<String> futureError = waitAndThrow(1_000);
|
||||||
|
assertThrows(RuntimeException.class, futureError::join);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallingJoinTwoTimes_thenBlocksThreadAndGetValues() {
|
||||||
|
CompletableFuture<String> f1 = waitAndReturn(1_000, "Harry");
|
||||||
|
CompletableFuture<String> f2 = waitAndReturn(2_000, "Ron");
|
||||||
|
|
||||||
|
assertEquals("Harry", f1.join());
|
||||||
|
assertEquals("Ron", f2.join());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallingAllOfJoin_thenBlocksThreadAndGetValues() {
|
||||||
|
CompletableFuture<String> f1 = waitAndReturn(1_000, "Harry");
|
||||||
|
CompletableFuture<String> f2 = waitAndReturn(2_000, "Ron");
|
||||||
|
|
||||||
|
CompletableFuture<Void> combinedFutures = CompletableFuture.allOf(f1, f2);
|
||||||
|
combinedFutures.join();
|
||||||
|
|
||||||
|
assertEquals("Harry", f1.join());
|
||||||
|
assertEquals("Ron", f2.join());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallingJoinInaLoop_thenProcessesDataPartially() {
|
||||||
|
CompletableFuture<String> f1 = waitAndReturn(1_000, "Harry");
|
||||||
|
CompletableFuture<String> f2 = waitAndThrow(2_000);
|
||||||
|
CompletableFuture<String> f3 = waitAndReturn(1_000, "Ron");
|
||||||
|
|
||||||
|
assertThrows(RuntimeException.class, () -> Stream.of(f1, f2, f3)
|
||||||
|
.map(CompletableFuture::join)
|
||||||
|
.forEach(this::sayHello));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallingAllOfJoin_thenFailsForAll() {
|
||||||
|
CompletableFuture<String> f1 = waitAndReturn(1_000, "Harry");
|
||||||
|
CompletableFuture<String> f2 = waitAndThrow(2_000);
|
||||||
|
CompletableFuture<String> f3 = waitAndReturn(1_000, "Ron");
|
||||||
|
|
||||||
|
assertThrows(RuntimeException.class, () -> CompletableFuture.allOf(f1, f2, f3)
|
||||||
|
.join());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallingExceptionally_thenRecoversWithDefaultValue() {
|
||||||
|
CompletableFuture<String> f1 = waitAndReturn(1_000, "Harry");
|
||||||
|
CompletableFuture<String> f2 = waitAndThrow(2_000);
|
||||||
|
CompletableFuture<String> f3 = waitAndReturn(1_000, "Ron");
|
||||||
|
|
||||||
|
CompletableFuture<String> names = CompletableFuture.allOf(f1, f2, f3)
|
||||||
|
.thenApply(__ -> f1.join() + "," + f2.join() + "," + f3.join())
|
||||||
|
.exceptionally(err -> {
|
||||||
|
System.out.println("oops, there was a problem! " + err.getMessage());
|
||||||
|
return "names not found!";
|
||||||
|
});
|
||||||
|
|
||||||
|
assertEquals("names not found!", names.join());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sayHello(String name) {
|
||||||
|
System.out.println(LocalDateTime.now() + " - " + name);
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompletableFuture<String> waitAndReturn(long millis, String value) {
|
||||||
|
return CompletableFuture.supplyAsync(() -> {
|
||||||
|
try {
|
||||||
|
// Thread.sleep() is commented to avoid slowing down the pipeline
|
||||||
|
// Thread.sleep(millis);
|
||||||
|
return value;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompletableFuture<String> waitAndThrow(long millis) {
|
||||||
|
return CompletableFuture.supplyAsync(() -> {
|
||||||
|
try {
|
||||||
|
// Thread.sleep() is commented to avoid slowing down the pipeline
|
||||||
|
// Thread.sleep(millis);
|
||||||
|
} finally {
|
||||||
|
throw new RuntimeException();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,88 @@
|
|||||||
|
package com.baeldung.concurrent.completablefuture.threadpool;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.fail;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class CompletableFutureThreadPoolUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingNonAsync_thenUsesMainThread() throws ExecutionException, InterruptedException {
|
||||||
|
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung");
|
||||||
|
|
||||||
|
CompletableFuture<Integer> nameLength = name.thenApply(value -> {
|
||||||
|
printCurrentThread();
|
||||||
|
return value.length();
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThat(nameLength.get()).isEqualTo(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingNonAsync_thenUsesCallersThread() throws InterruptedException {
|
||||||
|
Runnable test = () -> {
|
||||||
|
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung");
|
||||||
|
|
||||||
|
CompletableFuture<Integer> nameLength = name.thenApply(value -> {
|
||||||
|
printCurrentThread();
|
||||||
|
return value.length();
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
assertThat(nameLength.get()).isEqualTo(8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
fail(e.getMessage());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
new Thread(test, "test-thread").start();
|
||||||
|
Thread.sleep(100l);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingAsync_thenUsesCommonPool() throws ExecutionException, InterruptedException {
|
||||||
|
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung");
|
||||||
|
|
||||||
|
CompletableFuture<Integer> nameLength = name.thenApplyAsync(value -> {
|
||||||
|
printCurrentThread();
|
||||||
|
return value.length();
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThat(nameLength.get()).isEqualTo(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingAsync_thenUsesCustomExecutor() throws ExecutionException, InterruptedException {
|
||||||
|
Executor testExecutor = Executors.newFixedThreadPool(5);
|
||||||
|
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung");
|
||||||
|
|
||||||
|
CompletableFuture<Integer> nameLength = name.thenApplyAsync(value -> {
|
||||||
|
printCurrentThread();
|
||||||
|
return value.length();
|
||||||
|
}, testExecutor);
|
||||||
|
|
||||||
|
assertThat(nameLength.get()).isEqualTo(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenOverridingDefaultThreadPool_thenUsesCustomExecutor() throws ExecutionException, InterruptedException {
|
||||||
|
CompletableFuture<String> name = CustomCompletableFuture.supplyAsync(() -> "Baeldung");
|
||||||
|
|
||||||
|
CompletableFuture<Integer> nameLength = name.thenApplyAsync(value -> {
|
||||||
|
printCurrentThread();
|
||||||
|
return value.length();
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThat(nameLength.get()).isEqualTo(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void printCurrentThread() {
|
||||||
|
System.out.println(Thread.currentThread().getName());
|
||||||
|
}
|
||||||
|
}
|
@ -10,4 +10,5 @@ This module contains articles about basic Java concurrency
|
|||||||
- [ExecutorService – Waiting for Threads to Finish](https://www.baeldung.com/java-executor-wait-for-threads)
|
- [ExecutorService – Waiting for Threads to Finish](https://www.baeldung.com/java-executor-wait-for-threads)
|
||||||
- [Runnable vs. Callable in Java](https://www.baeldung.com/java-runnable-callable)
|
- [Runnable vs. Callable in Java](https://www.baeldung.com/java-runnable-callable)
|
||||||
- [What Is Thread-Safety and How to Achieve It?](https://www.baeldung.com/java-thread-safety)
|
- [What Is Thread-Safety and How to Achieve It?](https://www.baeldung.com/java-thread-safety)
|
||||||
|
- [How to Get Notified When a Task Completes in Java Executors](https://www.baeldung.com/java-executors-task-completed-notification)
|
||||||
- [[Next -->]](/core-java-modules/core-java-concurrency-basic-2)
|
- [[Next -->]](/core-java-modules/core-java-concurrency-basic-2)
|
||||||
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.concurrent.notificationforcompletetask;
|
||||||
|
|
||||||
|
import java.util.concurrent.FutureTask;
|
||||||
|
|
||||||
|
public class AlertingFutureTask extends FutureTask<String> {
|
||||||
|
|
||||||
|
private final CallbackInterface callback;
|
||||||
|
|
||||||
|
public AlertingFutureTask(Runnable runnable, Callback callback) {
|
||||||
|
super(runnable, null);
|
||||||
|
this.callback = callback;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void done() {
|
||||||
|
callback.taskDone("task details here");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.concurrent.notificationforcompletetask;
|
||||||
|
|
||||||
|
import java.util.concurrent.ArrayBlockingQueue;
|
||||||
|
import java.util.concurrent.ThreadPoolExecutor;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
public class AlertingThreadPoolExecutor extends ThreadPoolExecutor {
|
||||||
|
|
||||||
|
private final CallbackInterface callback;
|
||||||
|
|
||||||
|
public AlertingThreadPoolExecutor(CallbackInterface callback) {
|
||||||
|
super(1, 1, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
|
||||||
|
this.callback = callback;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void afterExecute(Runnable r, Throwable t) {
|
||||||
|
super.afterExecute(r, t);
|
||||||
|
callback.taskDone("runnable details here");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.concurrent.notificationforcompletetask;
|
||||||
|
|
||||||
|
public class Callback implements CallbackInterface {
|
||||||
|
|
||||||
|
public void taskDone(String details){
|
||||||
|
System.out.println("task complete: " + details);
|
||||||
|
// Alerts/notifications go here
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.concurrent.notificationforcompletetask;
|
||||||
|
|
||||||
|
public interface CallbackInterface {
|
||||||
|
void taskDone(String details);
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.concurrent.notificationforcompletetask;
|
||||||
|
|
||||||
|
public class RunnableImpl implements Runnable {
|
||||||
|
|
||||||
|
private final Runnable task;
|
||||||
|
|
||||||
|
private final CallbackInterface callback;
|
||||||
|
|
||||||
|
private final String taskDoneMessage;
|
||||||
|
|
||||||
|
public RunnableImpl(Runnable task, CallbackInterface callback, String taskDoneMessage) {
|
||||||
|
this.task = task;
|
||||||
|
this.callback = callback;
|
||||||
|
this.taskDoneMessage = taskDoneMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
task.run();
|
||||||
|
callback.taskDone(taskDoneMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
package com.baeldung.concurrent.notificationforcompletetask;
|
||||||
|
|
||||||
|
public class Task implements Runnable{
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
System.out.println("Task in progress");
|
||||||
|
// Business logic goes here
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,45 @@
|
|||||||
|
package com.baeldung.concurrent.notificationforcompletetask;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.FutureTask;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class NotificationsForCompleteTasksUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenImplementingRunnable_thenReceiveNotificationOfCompletedTask() {
|
||||||
|
Task task = new Task();
|
||||||
|
Callback callback = new Callback();
|
||||||
|
RunnableImpl runnableImpl = new RunnableImpl(task, callback, "ready for next task");
|
||||||
|
runnableImpl.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingCompletableFuture_thenReceiveNotificationOfCompletedTask() {
|
||||||
|
Task task = new Task();
|
||||||
|
Callback callback = new Callback();
|
||||||
|
CompletableFuture.runAsync(task)
|
||||||
|
.thenAccept(result -> callback.taskDone("completion details: " + result));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingThreadPoolExecutor_thenReceiveNotificationOfCompletedTask(){
|
||||||
|
Task task = new Task();
|
||||||
|
Callback callback = new Callback();
|
||||||
|
AlertingThreadPoolExecutor executor = new AlertingThreadPoolExecutor(callback);
|
||||||
|
executor.submit(task);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingFutureTask_thenReceiveNotificationOfCompletedTask(){
|
||||||
|
Task task = new Task();
|
||||||
|
Callback callback = new Callback();
|
||||||
|
FutureTask<String> future = new AlertingFutureTask(task, callback);
|
||||||
|
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||||
|
executor.submit(future);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -19,6 +19,16 @@
|
|||||||
<artifactId>jansi</artifactId>
|
<artifactId>jansi</artifactId>
|
||||||
<version>2.4.0</version>
|
<version>2.4.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.vintage</groupId>
|
||||||
|
<artifactId>junit-vintage-engine</artifactId>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -56,7 +66,7 @@
|
|||||||
<argument>-Xmx300m</argument>
|
<argument>-Xmx300m</argument>
|
||||||
<argument>-XX:+UseParallelGC</argument>
|
<argument>-XX:+UseParallelGC</argument>
|
||||||
<argument>-classpath</argument>
|
<argument>-classpath</argument>
|
||||||
<classpath />
|
<classpath/>
|
||||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||||
</arguments>
|
</arguments>
|
||||||
</configuration>
|
</configuration>
|
||||||
@ -70,6 +80,16 @@
|
|||||||
<target>${target.version}</target>
|
<target>${target.version}</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>3.1.2</version>
|
||||||
|
<configuration>
|
||||||
|
<excludeJUnit5Engines>
|
||||||
|
<engine>junit-vintage-engine</engine>
|
||||||
|
</excludeJUnit5Engines>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
@ -120,7 +140,7 @@
|
|||||||
<executable>java</executable>
|
<executable>java</executable>
|
||||||
<arguments>
|
<arguments>
|
||||||
<argument>-classpath</argument>
|
<argument>-classpath</argument>
|
||||||
<classpath />
|
<classpath/>
|
||||||
<argument>org.openjdk.jmh.Main</argument>
|
<argument>org.openjdk.jmh.Main</argument>
|
||||||
<argument>.*</argument>
|
<argument>.*</argument>
|
||||||
</arguments>
|
</arguments>
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
package com.baeldung.asciiart;
|
package com.baeldung.asciiart;
|
||||||
|
|
||||||
import com.baeldung.asciiart.AsciiArt.Settings;
|
import java.awt.Font;
|
||||||
|
|
||||||
import java.awt.*;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.baeldung.asciiart.AsciiArt.Settings;
|
||||||
|
|
||||||
public class AsciiArtIntegrationTest {
|
public class AsciiArtIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -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)
|
- [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)
|
- [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)
|
- [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)
|
- [[<-- Prev]](/core-java-modules/core-java-date-operations-2)
|
||||||
|
@ -0,0 +1,71 @@
|
|||||||
|
package com.baeldung.date;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.GregorianCalendar;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.time.DateUtils;
|
||||||
|
import org.joda.time.Instant;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class GetYesterdayDateUnitTest {
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
@Test
|
||||||
|
void givenDate_whenUsingDateClass_thenReturnYesterday() {
|
||||||
|
Date currentDate = new Date(2023, Calendar.DECEMBER, 20);
|
||||||
|
Date yesterdayDate = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000);
|
||||||
|
Date expectedYesterdayDate = new Date(2023, Calendar.DECEMBER, 19);
|
||||||
|
|
||||||
|
assertEquals(expectedYesterdayDate, yesterdayDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenDate_whenUsingCalendarClass_thenReturnYesterday() {
|
||||||
|
Calendar date = new GregorianCalendar(2023, Calendar.APRIL, 20, 4, 0);
|
||||||
|
date.add(Calendar.DATE, -1);
|
||||||
|
Calendar expectedYesterdayDate = new GregorianCalendar(2023, Calendar.APRIL, 19, 4, 0);
|
||||||
|
|
||||||
|
assertEquals(expectedYesterdayDate, date);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenDate_whenUsingLocalDateClass_thenReturnYesterday() {
|
||||||
|
LocalDate localDate = LocalDate.of(2023, 12, 20);
|
||||||
|
LocalDate yesterdayDate = localDate.minusDays(1);
|
||||||
|
LocalDate expectedYesterdayDate = LocalDate.of(2023, 12, 19);
|
||||||
|
|
||||||
|
assertEquals(expectedYesterdayDate, yesterdayDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenDate_whenUsingInstantClass_thenReturnYesterday() {
|
||||||
|
Instant date = Instant.parse("2023-10-25");
|
||||||
|
Instant yesterdayDate = date.minus(24 * 60 * 60 * 1000);
|
||||||
|
Instant expectedYesterdayDate = Instant.parse("2023-10-24");
|
||||||
|
|
||||||
|
assertEquals(expectedYesterdayDate, yesterdayDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenDate_whenUsingJodaTimeLocalDateClass_thenReturnYesterday() {
|
||||||
|
org.joda.time.LocalDate localDate = new org.joda.time.LocalDate(2023, 12, 20);
|
||||||
|
org.joda.time.LocalDate yesterdayDate = localDate.minusDays(1);
|
||||||
|
org.joda.time.LocalDate expectedYesterdayDate = new org.joda.time.LocalDate(2023, 12, 19);
|
||||||
|
|
||||||
|
assertEquals(expectedYesterdayDate, yesterdayDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenDate_whenUsingApacheCommonsLangDateUtils_thenReturnYesterday() {
|
||||||
|
Date date = new GregorianCalendar(2023, Calendar.MAY, 16, 4, 0).getTime();
|
||||||
|
Date yesterdayDate = DateUtils.addDays(date, -1);
|
||||||
|
Date expectedYesterdayDate = new GregorianCalendar(2023, Calendar.MAY, 15, 4, 0).getTime();
|
||||||
|
|
||||||
|
assertEquals(expectedYesterdayDate, yesterdayDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,55 @@
|
|||||||
|
package com.baeldung.firstandlastdayofyear;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.time.DayOfWeek;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.Month;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static java.time.temporal.TemporalAdjusters.firstDayOfYear;
|
||||||
|
import static java.time.temporal.TemporalAdjusters.lastDayOfYear;
|
||||||
|
|
||||||
|
public class FirstAndLastDayOfYearUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCurrentDate_whenGettingFirstAndLastDayOfYear_thenCorrectDatesReturned() {
|
||||||
|
LocalDate today = LocalDate.now();
|
||||||
|
LocalDate firstDay = today.with(firstDayOfYear());
|
||||||
|
LocalDate lastDay = today.with(lastDayOfYear());
|
||||||
|
|
||||||
|
assertEquals("2023-01-01", firstDay.toString());
|
||||||
|
assertEquals("2023-12-31", lastDay.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCalendarSetToFirstDayOfYear_whenFormattingDateToISO8601_thenFormattedDateMatchesFirstDay() {
|
||||||
|
Calendar cal = Calendar.getInstance();
|
||||||
|
cal.set(Calendar.YEAR, 2023);
|
||||||
|
cal.set(Calendar.DAY_OF_YEAR, 1);
|
||||||
|
Date firstDay = cal.getTime();
|
||||||
|
|
||||||
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||||
|
String formattedDate = sdf.format(firstDay);
|
||||||
|
|
||||||
|
assertEquals("2023-01-01", formattedDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCalendarSetToFirstDayOfYear_whenFormattingDateToISO8601_thenFormattedDateMatchesLastDay() {
|
||||||
|
Calendar cal = Calendar.getInstance();
|
||||||
|
cal.set(Calendar.YEAR, 2023);
|
||||||
|
cal.set(Calendar.MONTH, 11);
|
||||||
|
cal.set(Calendar.DAY_OF_MONTH, 31);
|
||||||
|
Date lastDay = cal.getTime();
|
||||||
|
|
||||||
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||||
|
String formattedDate = sdf.format(lastDay);
|
||||||
|
|
||||||
|
assertEquals("2023-12-31", formattedDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -4,13 +4,5 @@ This module contains articles about core Java input/output(IO) APIs.
|
|||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Constructing a Relative Path From Two Absolute Paths in Java](https://www.baeldung.com/java-relative-path-absolute)
|
- [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)
|
- [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)
|
- [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty)
|
||||||
- [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)
|
|
@ -92,12 +92,6 @@
|
|||||||
<version>7.1.0</version>
|
<version>7.1.0</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.testng</groupId>
|
|
||||||
<artifactId>testng</artifactId>
|
|
||||||
<version>7.5</version>
|
|
||||||
<scope>compile</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<build>
|
<build>
|
||||||
<finalName>core-java-io-apis-2</finalName>
|
<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)
|
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](https://www.baeldung.com/java-path)
|
||||||
- [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter)
|
- [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter)
|
||||||
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
||||||
- [Java Scanner](https://www.baeldung.com/java-scanner)
|
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||||
- [Scanner nextLine() Method](https://www.baeldung.com/java-scanner-nextline)
|
- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
||||||
- [Java Scanner hasNext() vs. hasNextLine()](https://www.baeldung.com/java-scanner-hasnext-vs-hasnextline)
|
- [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>
|
<version>${lombok.version}</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.testng</groupId>
|
||||||
|
<artifactId>testng</artifactId>
|
||||||
|
<version>7.5</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -1,10 +1,12 @@
|
|||||||
package com.baeldung.multinput;
|
package com.baeldung.multinput;
|
||||||
import java.io.ByteArrayInputStream;
|
|
||||||
import java.io.InputStream;
|
import java.io.ByteArrayInputStream;
|
||||||
import java.util.InputMismatchException;
|
import java.io.InputStream;
|
||||||
import org.junit.jupiter.api.Assertions;
|
import java.util.InputMismatchException;
|
||||||
import org.testng.annotations.Test;
|
|
||||||
import com.baeldung.multinput.MultiInputs;
|
import org.junit.jupiter.api.Assertions;
|
||||||
|
import org.testng.annotations.Test;
|
||||||
|
|
||||||
public class TestMultipleInputsUnitTest {
|
public class TestMultipleInputsUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() {
|
public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() {
|
@ -64,7 +64,7 @@
|
|||||||
<argument>-Xmx300m</argument>
|
<argument>-Xmx300m</argument>
|
||||||
<argument>-XX:+UseParallelGC</argument>
|
<argument>-XX:+UseParallelGC</argument>
|
||||||
<argument>-classpath</argument>
|
<argument>-classpath</argument>
|
||||||
<classpath />
|
<classpath/>
|
||||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||||
</arguments>
|
</arguments>
|
||||||
</configuration>
|
</configuration>
|
||||||
@ -116,7 +116,7 @@
|
|||||||
<executable>java</executable>
|
<executable>java</executable>
|
||||||
<arguments>
|
<arguments>
|
||||||
<argument>-classpath</argument>
|
<argument>-classpath</argument>
|
||||||
<classpath />
|
<classpath/>
|
||||||
<argument>org.openjdk.jmh.Main</argument>
|
<argument>org.openjdk.jmh.Main</argument>
|
||||||
<argument>.*</argument>
|
<argument>.*</argument>
|
||||||
</arguments>
|
</arguments>
|
||||||
|
@ -4,7 +4,7 @@ This module contains articles about JAR files
|
|||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
|
||||||
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
|
- [How to Create an Executable JAR with Maven](https://www.baeldung.com/executable-jar-with-maven)
|
||||||
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
|
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
|
||||||
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)
|
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)
|
||||||
- [Get Names of Classes Inside a JAR File](https://www.baeldung.com/jar-file-get-class-names)
|
- [Get Names of Classes Inside a JAR File](https://www.baeldung.com/jar-file-get-class-names)
|
||||||
|
@ -189,7 +189,7 @@
|
|||||||
<argument>-Xmx300m</argument>
|
<argument>-Xmx300m</argument>
|
||||||
<argument>-XX:+UseParallelGC</argument>
|
<argument>-XX:+UseParallelGC</argument>
|
||||||
<argument>-classpath</argument>
|
<argument>-classpath</argument>
|
||||||
<classpath />
|
<classpath/>
|
||||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||||
</arguments>
|
</arguments>
|
||||||
</configuration>
|
</configuration>
|
||||||
@ -253,7 +253,7 @@
|
|||||||
<executable>java</executable>
|
<executable>java</executable>
|
||||||
<arguments>
|
<arguments>
|
||||||
<argument>-classpath</argument>
|
<argument>-classpath</argument>
|
||||||
<classpath />
|
<classpath/>
|
||||||
<argument>org.openjdk.jmh.Main</argument>
|
<argument>org.openjdk.jmh.Main</argument>
|
||||||
<argument>.*</argument>
|
<argument>.*</argument>
|
||||||
</arguments>
|
</arguments>
|
||||||
|
@ -168,6 +168,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<javaassist.version>3.27.0-GA</javaassist.version>
|
<javaassist.version>3.27.0-GA</javaassist.version>
|
||||||
|
<esapi.version>2.5.2.0</esapi.version>
|
||||||
<jol-core.version>0.10</jol-core.version>
|
<jol-core.version>0.10</jol-core.version>
|
||||||
<asm.version>9.4</asm.version>
|
<asm.version>9.4</asm.version>
|
||||||
<bcel.version>6.5.0</bcel.version>
|
<bcel.version>6.5.0</bcel.version>
|
||||||
|
8
core-java-modules/core-java-lang-6/README.md
Normal file
8
core-java-modules/core-java-lang-6/README.md
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
## Core Java Lang (Part 6)
|
||||||
|
|
||||||
|
This module contains articles about core features in the Java language
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Convert One Enum to Another Enum in Java](https://www.baeldung.com/java-convert-enums)
|
||||||
|
- [What Is the Maximum Depth of the Java Call Stack?](https://www.baeldung.com/java-call-stack-max-depth)
|
52
core-java-modules/core-java-lang-6/pom.xml
Normal file
52
core-java-modules/core-java-lang-6/pom.xml
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
<?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>
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
|
<artifactId>core-java-modules</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>core-java-lang-6</artifactId>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mapstruct</groupId>
|
||||||
|
<artifactId>mapstruct</artifactId>
|
||||||
|
<version>${mapstruct.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.5.1</version>
|
||||||
|
<configuration>
|
||||||
|
<source>17</source>
|
||||||
|
<target>17</target>
|
||||||
|
<annotationProcessorPaths>
|
||||||
|
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor -->
|
||||||
|
<path>
|
||||||
|
<groupId>org.mapstruct</groupId>
|
||||||
|
<artifactId>mapstruct-processor</artifactId>
|
||||||
|
<version>${mapstruct.version}</version>
|
||||||
|
</path>
|
||||||
|
</annotationProcessorPaths>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.source>17</maven.compiler.source>
|
||||||
|
<maven.compiler.target>17</maven.compiler.target>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<mapstruct.version>1.5.5.Final</mapstruct.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.baeldung.callstack;
|
||||||
|
|
||||||
|
public class RecursiveCallStackOverflow {
|
||||||
|
static int depth = 0;
|
||||||
|
|
||||||
|
private static void recursiveStackOverflow() {
|
||||||
|
depth++;
|
||||||
|
recursiveStackOverflow();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
recursiveStackOverflow();
|
||||||
|
} catch (StackOverflowError e) {
|
||||||
|
System.out.println("Maximum depth of the call stack is " + depth);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.enums.mapping;
|
||||||
|
|
||||||
|
import org.mapstruct.Mapper;
|
||||||
|
import org.mapstruct.MappingConstants;
|
||||||
|
import org.mapstruct.ValueMapping;
|
||||||
|
|
||||||
|
import com.baeldung.enums.mapping.order.CmsOrderStatus;
|
||||||
|
import com.baeldung.enums.mapping.order.OrderStatus;
|
||||||
|
import com.baeldung.enums.mapping.user.ExternalUserStatus;
|
||||||
|
import com.baeldung.enums.mapping.user.UserStatus;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface EnumMapper {
|
||||||
|
|
||||||
|
CmsOrderStatus map(OrderStatus orderStatus);
|
||||||
|
|
||||||
|
@ValueMapping(source = "PENDING", target = "INACTIVE")
|
||||||
|
@ValueMapping(source = "BLOCKED", target = "INACTIVE")
|
||||||
|
@ValueMapping(source = "INACTIVATED_BY_SYSTEM", target = "INACTIVE")
|
||||||
|
@ValueMapping(source = "DELETED", target = "INACTIVE")
|
||||||
|
ExternalUserStatus map(UserStatus userStatus);
|
||||||
|
|
||||||
|
@ValueMapping(source = MappingConstants.ANY_REMAINING, target = "INACTIVE")
|
||||||
|
ExternalUserStatus mapDefault(UserStatus userStatus);
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.enums.mapping.order;
|
||||||
|
|
||||||
|
public enum CmsOrderStatus {
|
||||||
|
PENDING, APPROVED, PACKED, DELIVERED
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.enums.mapping.order;
|
||||||
|
|
||||||
|
public enum OrderStatus {
|
||||||
|
PENDING, APPROVED, PACKED, DELIVERED;
|
||||||
|
|
||||||
|
public CmsOrderStatus toCmsOrderStatus() {
|
||||||
|
return CmsOrderStatus.valueOf(this.name());
|
||||||
|
}
|
||||||
|
|
||||||
|
public CmsOrderStatus toCmsOrderStatusOrdinal() {
|
||||||
|
return CmsOrderStatus.values()[this.ordinal()];
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.enums.mapping.user;
|
||||||
|
|
||||||
|
public enum ExternalUserStatus {
|
||||||
|
ACTIVE, INACTIVE
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.enums.mapping.user;
|
||||||
|
|
||||||
|
public enum UserStatus {
|
||||||
|
PENDING, ACTIVE, BLOCKED, INACTIVATED_BY_SYSTEM, DELETED;
|
||||||
|
|
||||||
|
public ExternalUserStatus toExternalUserStatusViaSwitchStatement() {
|
||||||
|
return switch (this) {
|
||||||
|
case PENDING, BLOCKED, INACTIVATED_BY_SYSTEM, DELETED -> ExternalUserStatus.INACTIVE;
|
||||||
|
case ACTIVE -> ExternalUserStatus.ACTIVE;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public ExternalUserStatus toExternalUserStatusViaRegularSwitch() {
|
||||||
|
switch (this) {
|
||||||
|
case PENDING:
|
||||||
|
case BLOCKED:
|
||||||
|
case INACTIVATED_BY_SYSTEM:
|
||||||
|
case DELETED:
|
||||||
|
return ExternalUserStatus.INACTIVE;
|
||||||
|
case ACTIVE:
|
||||||
|
return ExternalUserStatus.ACTIVE;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.enums.mapping.user;
|
||||||
|
|
||||||
|
import java.util.EnumMap;
|
||||||
|
|
||||||
|
public class UserStatusMapper {
|
||||||
|
public static EnumMap<UserStatus, ExternalUserStatus> statusesMap;
|
||||||
|
|
||||||
|
static {
|
||||||
|
statusesMap = new EnumMap<>(UserStatus.class);
|
||||||
|
statusesMap.put(UserStatus.PENDING, ExternalUserStatus.INACTIVE);
|
||||||
|
statusesMap.put(UserStatus.BLOCKED, ExternalUserStatus.INACTIVE);
|
||||||
|
statusesMap.put(UserStatus.DELETED, ExternalUserStatus.INACTIVE);
|
||||||
|
statusesMap.put(UserStatus.INACTIVATED_BY_SYSTEM, ExternalUserStatus.INACTIVE);
|
||||||
|
statusesMap.put(UserStatus.ACTIVE, ExternalUserStatus.ACTIVE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ExternalUserStatus toExternalUserStatus(UserStatus userStatus) {
|
||||||
|
return statusesMap.get(userStatus);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.baeldung.enums.mapping.user;
|
||||||
|
|
||||||
|
public enum UserStatusWithFieldVariable {
|
||||||
|
PENDING(ExternalUserStatus.INACTIVE),
|
||||||
|
ACTIVE(ExternalUserStatus.ACTIVE),
|
||||||
|
BLOCKED(ExternalUserStatus.INACTIVE),
|
||||||
|
INACTIVATED_BY_SYSTEM(ExternalUserStatus.INACTIVE),
|
||||||
|
DELETED(ExternalUserStatus.INACTIVE);
|
||||||
|
|
||||||
|
private final ExternalUserStatus externalUserStatus;
|
||||||
|
|
||||||
|
UserStatusWithFieldVariable(ExternalUserStatus externalUserStatus) {
|
||||||
|
this.externalUserStatus = externalUserStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ExternalUserStatus toExternalUserStatus() {
|
||||||
|
return externalUserStatus;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,120 @@
|
|||||||
|
package com.baeldung.enums.mapping;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.baeldung.enums.mapping.order.CmsOrderStatus;
|
||||||
|
import com.baeldung.enums.mapping.order.OrderStatus;
|
||||||
|
import com.baeldung.enums.mapping.user.ExternalUserStatus;
|
||||||
|
import com.baeldung.enums.mapping.user.UserStatus;
|
||||||
|
import com.baeldung.enums.mapping.user.UserStatusMapper;
|
||||||
|
import com.baeldung.enums.mapping.user.UserStatusWithFieldVariable;
|
||||||
|
|
||||||
|
public class EnumConversionUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingSwitchStatement_thenEnumConverted() {
|
||||||
|
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||||
|
UserStatus userStatusPending = UserStatus.PENDING;
|
||||||
|
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||||
|
|
||||||
|
assertEquals(ExternalUserStatus.INACTIVE, userStatusDeleted.toExternalUserStatusViaSwitchStatement());
|
||||||
|
assertEquals(ExternalUserStatus.INACTIVE, userStatusPending.toExternalUserStatusViaSwitchStatement());
|
||||||
|
assertEquals(ExternalUserStatus.ACTIVE, userStatusActive.toExternalUserStatusViaSwitchStatement());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingSwitch_thenEnumConverted() {
|
||||||
|
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||||
|
UserStatus userStatusPending = UserStatus.PENDING;
|
||||||
|
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||||
|
|
||||||
|
assertEquals(ExternalUserStatus.INACTIVE, userStatusDeleted.toExternalUserStatusViaRegularSwitch());
|
||||||
|
assertEquals(ExternalUserStatus.INACTIVE, userStatusPending.toExternalUserStatusViaRegularSwitch());
|
||||||
|
assertEquals(ExternalUserStatus.ACTIVE, userStatusActive.toExternalUserStatusViaRegularSwitch());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingFieldVariable_thenEnumConverted() {
|
||||||
|
UserStatusWithFieldVariable userStatusDeleted = UserStatusWithFieldVariable.DELETED;
|
||||||
|
UserStatusWithFieldVariable userStatusPending = UserStatusWithFieldVariable.PENDING;
|
||||||
|
UserStatusWithFieldVariable userStatusActive = UserStatusWithFieldVariable.ACTIVE;
|
||||||
|
|
||||||
|
assertEquals(ExternalUserStatus.INACTIVE, userStatusDeleted.toExternalUserStatus());
|
||||||
|
assertEquals(ExternalUserStatus.INACTIVE, userStatusPending.toExternalUserStatus());
|
||||||
|
assertEquals(ExternalUserStatus.ACTIVE, userStatusActive.toExternalUserStatus());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingEnumMap_thenEnumConverted() {
|
||||||
|
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||||
|
UserStatus userStatusPending = UserStatus.PENDING;
|
||||||
|
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||||
|
|
||||||
|
assertEquals(ExternalUserStatus.INACTIVE, UserStatusMapper.toExternalUserStatus(userStatusDeleted));
|
||||||
|
assertEquals(ExternalUserStatus.INACTIVE, UserStatusMapper.toExternalUserStatus(userStatusPending));
|
||||||
|
assertEquals(ExternalUserStatus.ACTIVE, UserStatusMapper.toExternalUserStatus(userStatusActive));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingOrdinalApproach_thenEnumConverted() {
|
||||||
|
OrderStatus orderStatusApproved = OrderStatus.APPROVED;
|
||||||
|
OrderStatus orderStatusDelivered = OrderStatus.DELIVERED;
|
||||||
|
OrderStatus orderStatusPending = OrderStatus.PENDING;
|
||||||
|
|
||||||
|
assertEquals(CmsOrderStatus.APPROVED, orderStatusApproved.toCmsOrderStatusOrdinal());
|
||||||
|
assertEquals(CmsOrderStatus.DELIVERED, orderStatusDelivered.toCmsOrderStatusOrdinal());
|
||||||
|
assertEquals(CmsOrderStatus.PENDING, orderStatusPending.toCmsOrderStatusOrdinal());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingEnumName_thenEnumConverted() {
|
||||||
|
OrderStatus orderStatusApproved = OrderStatus.APPROVED;
|
||||||
|
OrderStatus orderStatusDelivered = OrderStatus.DELIVERED;
|
||||||
|
OrderStatus orderStatusPending = OrderStatus.PENDING;
|
||||||
|
|
||||||
|
assertEquals(CmsOrderStatus.APPROVED, orderStatusApproved.toCmsOrderStatus());
|
||||||
|
assertEquals(CmsOrderStatus.DELIVERED, orderStatusDelivered.toCmsOrderStatus());
|
||||||
|
assertEquals(CmsOrderStatus.PENDING, orderStatusPending.toCmsOrderStatus());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingDefaultMapstruct_thenEnumConverted() {
|
||||||
|
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||||
|
UserStatus userStatusPending = UserStatus.PENDING;
|
||||||
|
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||||
|
|
||||||
|
EnumMapper enumMapper = new EnumMapperImpl();
|
||||||
|
|
||||||
|
assertEquals(ExternalUserStatus.INACTIVE, enumMapper.map(userStatusDeleted));
|
||||||
|
assertEquals(ExternalUserStatus.INACTIVE, enumMapper.map(userStatusPending));
|
||||||
|
assertEquals(ExternalUserStatus.ACTIVE, enumMapper.map(userStatusActive));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingConfiguredMapstruct_thenEnumConverted() {
|
||||||
|
OrderStatus orderStatusApproved = OrderStatus.APPROVED;
|
||||||
|
OrderStatus orderStatusDelivered = OrderStatus.DELIVERED;
|
||||||
|
OrderStatus orderStatusPending = OrderStatus.PENDING;
|
||||||
|
|
||||||
|
EnumMapper enumMapper = new EnumMapperImpl();
|
||||||
|
|
||||||
|
assertEquals(CmsOrderStatus.APPROVED, enumMapper.map(orderStatusApproved));
|
||||||
|
assertEquals(CmsOrderStatus.DELIVERED, enumMapper.map(orderStatusDelivered));
|
||||||
|
assertEquals(CmsOrderStatus.PENDING, enumMapper.map(orderStatusPending));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingConfiguredWithRemainingMapstruct_thenEnumConverted() {
|
||||||
|
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||||
|
UserStatus userStatusPending = UserStatus.PENDING;
|
||||||
|
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||||
|
|
||||||
|
EnumMapper enumMapper = new EnumMapperImpl();
|
||||||
|
|
||||||
|
assertEquals(ExternalUserStatus.INACTIVE, enumMapper.mapDefault(userStatusDeleted));
|
||||||
|
assertEquals(ExternalUserStatus.INACTIVE, enumMapper.mapDefault(userStatusPending));
|
||||||
|
assertEquals(ExternalUserStatus.ACTIVE, enumMapper.mapDefault(userStatusActive));
|
||||||
|
}
|
||||||
|
}
|
@ -5,7 +5,6 @@
|
|||||||
### Relevant articles:
|
### Relevant articles:
|
||||||
|
|
||||||
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
|
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
|
||||||
- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm)
|
|
||||||
- [Check if Two Rectangles Overlap in Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
|
- [Check if Two Rectangles Overlap in Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
|
||||||
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
|
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
|
||||||
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
|
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
|
||||||
|
@ -29,7 +29,7 @@
|
|||||||
<source>${maven.compiler.source}</source>
|
<source>${maven.compiler.source}</source>
|
||||||
<target>${maven.compiler.target}</target>
|
<target>${maven.compiler.target}</target>
|
||||||
<compilerArguments>
|
<compilerArguments>
|
||||||
<Xlint:unchecked />
|
<Xlint:unchecked/>
|
||||||
</compilerArguments>
|
</compilerArguments>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.demeter;
|
||||||
|
|
||||||
|
public class DemeterApplication {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
Expenses expenses = new Expenses(100, 10);
|
||||||
|
Employee employee = new Employee();
|
||||||
|
employee.getDepartment()
|
||||||
|
.getManager()
|
||||||
|
.approveExpense(expenses);
|
||||||
|
|
||||||
|
Manager mgr = new Manager();
|
||||||
|
Employee emp = new Employee(mgr);
|
||||||
|
emp.submitExpense(expenses);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,11 @@
|
|||||||
|
package com.baeldung.demeter;
|
||||||
|
|
||||||
|
public class Department {
|
||||||
|
|
||||||
|
private Manager manager = new Manager();
|
||||||
|
|
||||||
|
public Manager getManager() {
|
||||||
|
return manager;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.demeter;
|
||||||
|
|
||||||
|
public class Employee {
|
||||||
|
private Department department = new Department();
|
||||||
|
private Manager manager;
|
||||||
|
|
||||||
|
public Employee() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
Employee(Manager manager) {
|
||||||
|
this.manager = manager;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Department getDepartment() {
|
||||||
|
return department;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void submitExpense(Expenses expenses) {
|
||||||
|
manager.approveExpense(expenses);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.demeter;
|
||||||
|
|
||||||
|
public class Expenses {
|
||||||
|
|
||||||
|
private double total;
|
||||||
|
private double tax;
|
||||||
|
|
||||||
|
public Expenses(double total, double tax) {
|
||||||
|
this.total = total;
|
||||||
|
this.tax = tax;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double total() {
|
||||||
|
return total + tax;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.demeter;
|
||||||
|
|
||||||
|
public class Greetings {
|
||||||
|
|
||||||
|
HelloCountries helloCountries = new HelloCountries();
|
||||||
|
|
||||||
|
private static HelloCountries helloCountriesStatic = new HelloCountries();
|
||||||
|
|
||||||
|
public String generalGreeting() {
|
||||||
|
return "Welcome" + world();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String world() {
|
||||||
|
return "Hello World";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getHelloBrazil() {
|
||||||
|
HelloCountries helloCountries = new HelloCountries();
|
||||||
|
return helloCountries.helloBrazil();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getHelloIndia(HelloCountries helloCountries) {
|
||||||
|
return helloCountries.helloIndia();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getHelloJapan() {
|
||||||
|
return helloCountries.helloJapan();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getHellStaticWorld() {
|
||||||
|
return helloCountriesStatic.helloStaticWorld();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.demeter;
|
||||||
|
|
||||||
|
public class HelloCountries {
|
||||||
|
|
||||||
|
public String helloBrazil() {
|
||||||
|
return "Hello Brazil";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String helloIndia() {
|
||||||
|
return "Hello India";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String helloJapan() {
|
||||||
|
return "Hello Japan";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String helloStaticWorld() {
|
||||||
|
return "Hello Static World";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
package com.baeldung.demeter;
|
||||||
|
|
||||||
|
public class Manager {
|
||||||
|
|
||||||
|
public void approveExpense(Expenses expenses) {
|
||||||
|
System.out.println("Expense approved" + expenses.total());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -9,3 +9,4 @@ This module contains articles about Object-oriented programming (OOP) patterns i
|
|||||||
- [How to Make a Deep Copy of an Object in Java](https://www.baeldung.com/java-deep-copy)
|
- [How to Make a Deep Copy of an Object in Java](https://www.baeldung.com/java-deep-copy)
|
||||||
- [Using an Interface vs. Abstract Class in Java](https://www.baeldung.com/java-interface-vs-abstract-class)
|
- [Using an Interface vs. Abstract Class in Java](https://www.baeldung.com/java-interface-vs-abstract-class)
|
||||||
- [Should We Create an Interface for Only One Implementation?](https://www.baeldung.com/java-interface-single-implementation)
|
- [Should We Create an Interface for Only One Implementation?](https://www.baeldung.com/java-interface-single-implementation)
|
||||||
|
- [How to Deep Copy an ArrayList in Java](https://www.baeldung.com/java-arraylist-deep-copy)
|
||||||
|
@ -36,7 +36,7 @@ public class Course implements Serializable, Cloneable {
|
|||||||
try {
|
try {
|
||||||
return (Course) super.clone();
|
return (Course) super.clone();
|
||||||
} catch (CloneNotSupportedException e) {
|
} catch (CloneNotSupportedException e) {
|
||||||
throw new AssertionError();
|
throw new IllegalStateException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -95,7 +95,7 @@ public class Student implements Serializable, Cloneable {
|
|||||||
try {
|
try {
|
||||||
student = (Student) super.clone();
|
student = (Student) super.clone();
|
||||||
} catch (CloneNotSupportedException e) {
|
} catch (CloneNotSupportedException e) {
|
||||||
throw new AssertionError();
|
throw new IllegalStateException(e);
|
||||||
}
|
}
|
||||||
student.course = this.course.clone();
|
student.course = this.course.clone();
|
||||||
return student;
|
return student;
|
||||||
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.stateless;
|
||||||
|
|
||||||
|
public enum BubbleSort implements SortingStrategy {
|
||||||
|
|
||||||
|
INSTANCE;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void sort(int[] array) {
|
||||||
|
int n = array.length;
|
||||||
|
for (int i = 0; i < n - 1; i++) {
|
||||||
|
for (int j = 0; j < n - i - 1; j++) {
|
||||||
|
if (array[j] > array[j + 1]) {
|
||||||
|
int swap = array[j];
|
||||||
|
array[j] = array[j + 1];
|
||||||
|
array[j + 1] = swap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.stateless;
|
||||||
|
|
||||||
|
public enum QuickSort implements SortingStrategy {
|
||||||
|
|
||||||
|
INSTANCE;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void sort(int[] array) {
|
||||||
|
quickSort(array, 0, array.length - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void quickSort(int[] array, int begin, int end) {
|
||||||
|
if (begin < end) {
|
||||||
|
int pi = partition(array, begin, end);
|
||||||
|
quickSort(array, begin, pi - 1);
|
||||||
|
quickSort(array, pi + 1, end);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int partition(int[] array, int low, int high) {
|
||||||
|
int pivot = array[high];
|
||||||
|
int i = low - 1;
|
||||||
|
for (int j = low; j < high; j++) {
|
||||||
|
if (array[j] < pivot) {
|
||||||
|
i++;
|
||||||
|
int swap = array[i];
|
||||||
|
array[i] = array[j];
|
||||||
|
array[j] = swap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int swap = array[i + 1];
|
||||||
|
array[i + 1] = array[high];
|
||||||
|
array[high] = swap;
|
||||||
|
return i + 1;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,7 @@
|
|||||||
|
package com.baeldung.stateless;
|
||||||
|
|
||||||
|
public interface SortingStrategy {
|
||||||
|
|
||||||
|
public void sort(int[] array);
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.stateless;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class ArraySortingUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenArray_whenBubbleSorting_thenSorted() {
|
||||||
|
int[] arrayToSort = {17, 6, 11, 41, 5, 3, 4, -9};
|
||||||
|
int[] sortedArray = {-9, 3, 4, 5, 6, 11, 17, 41};
|
||||||
|
|
||||||
|
SortingStrategy sortingStrategy = BubbleSort.INSTANCE;
|
||||||
|
sortingStrategy.sort(arrayToSort);
|
||||||
|
assertArrayEquals(sortedArray, arrayToSort);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenArray_whenQuickSortSorting_thenSorted() {
|
||||||
|
int[] arrayToSort = {17, 6, 11, 41, 5, 3, 4, -9};
|
||||||
|
int[] sortedArray = {-9, 3, 4, 5, 6, 11, 17, 41};
|
||||||
|
|
||||||
|
SortingStrategy sortingStrategy = QuickSort.INSTANCE;
|
||||||
|
sortingStrategy.sort(arrayToSort);
|
||||||
|
assertArrayEquals(sortedArray, arrayToSort);
|
||||||
|
}
|
||||||
|
}
|
@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-java-networking</artifactId>
|
<artifactId>core-java-networking</artifactId>
|
||||||
<name>core-java-networking</name>
|
<name>core-java-networking</name>
|
||||||
|
@ -65,6 +65,7 @@ public class NioVsNio2UnitTest {
|
|||||||
public void listFilesUsingWalk() throws Exception {
|
public void listFilesUsingWalk() throws Exception {
|
||||||
Path path = Paths.get("src/test");
|
Path path = Paths.get("src/test");
|
||||||
Stream<Path> walk = Files.walk(path);
|
Stream<Path> walk = Files.walk(path);
|
||||||
walk.forEach(System.out::println);
|
|
||||||
|
assertThat(walk.findAny()).isPresent();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,42 @@
|
|||||||
|
package com.baeldung.randomnumbers;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.OptionalInt;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
public class RandomNumbersGeneratorWithExclusion {
|
||||||
|
|
||||||
|
public static int getRandomWithExclusionUsingMathRandom(int min, int max, int[] exclude) {
|
||||||
|
Arrays.sort(exclude);
|
||||||
|
int random = min + (int) ((max - min + 1 - exclude.length) * Math.random());
|
||||||
|
for (int ex : exclude) {
|
||||||
|
if (random < ex) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
random++;
|
||||||
|
}
|
||||||
|
return random;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int getRandomNumberWithExclusionUsingNextInt(int min, int max, int[] exclude) {
|
||||||
|
Random rnd = new Random();
|
||||||
|
Arrays.sort(exclude);
|
||||||
|
int random = min + rnd.nextInt(max - min + 1 - exclude.length);
|
||||||
|
for (int ex : exclude) {
|
||||||
|
if (random < ex) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
random++;
|
||||||
|
}
|
||||||
|
return random;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getRandomWithExclusion(int min, int max, int[] exclude) {
|
||||||
|
Random rnd = new Random();
|
||||||
|
OptionalInt random = rnd.ints(min, max + 1)
|
||||||
|
.filter(num -> Arrays.stream(exclude).noneMatch(ex -> num == ex))
|
||||||
|
.findFirst();
|
||||||
|
return random.orElse(min);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,4 +1,6 @@
|
|||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Java Program to Estimate Pi](https://www.baeldung.com/java-monte-carlo-compute-pi)
|
- [Java Program to Estimate Pi](https://www.baeldung.com/java-monte-carlo-compute-pi)
|
||||||
- [Convert Integer to Hexadecimal in Java](https://www.baeldung.com/java-convert-int-to-hex)
|
- [Convert Integer to Hexadecimal in Java](https://www.baeldung.com/java-convert-int-to-hex)
|
||||||
|
- [Integer.class Vs. Integer.TYPE Vs. int.class](https://www.baeldung.com/java-integer-class-vs-type-vs-int)
|
||||||
|
- [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian)
|
||||||
- More articles: [[<-- prev]](../core-java-numbers-5)
|
- More articles: [[<-- prev]](../core-java-numbers-5)
|
||||||
|
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.endianness;
|
||||||
|
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
|
||||||
|
public class Endianness {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
int value = 123456789;
|
||||||
|
byte[] bytes = ByteBuffer.allocate(4)
|
||||||
|
.putInt(value)
|
||||||
|
.array();
|
||||||
|
|
||||||
|
for (byte b : bytes) {
|
||||||
|
System.out.format("0x%x ", b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user