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)
|
||||
- [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)
|
||||
- [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 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)
|
||||
|
|
|
@ -7,7 +7,6 @@ import static org.mockserver.model.HttpResponse.response;
|
|||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
|
@ -18,22 +17,19 @@ import org.mockserver.integration.ClientAndServer;
|
|||
public class GetRequestMockServer {
|
||||
|
||||
public static ClientAndServer mockServer;
|
||||
public static String serviceOneUrl;
|
||||
public static String serviceTwoUrl;
|
||||
|
||||
public static int serverPort;
|
||||
|
||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
public static final String PATH_ONE = "/test1";
|
||||
public static final String PATH_TWO = "/test2";
|
||||
public static final String METHOD = "GET";
|
||||
|
||||
public static final String SECURITY_PATH = "/spring-security-rest-basic-auth/api/foos/1";
|
||||
|
||||
public static final String UPLOAD_PATH = "/spring-mvc-java/stub/multipart";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException {
|
||||
serverPort = getFreePort();
|
||||
System.out.println("Free port "+serverPort);
|
||||
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
|
||||
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
|
||||
System.out.println("Free port " + serverPort);
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
mockGetRequest();
|
||||
}
|
||||
|
@ -44,33 +40,36 @@ public class GetRequestMockServer {
|
|||
}
|
||||
|
||||
private static void mockGetRequest() {
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_ONE)
|
||||
.withMethod(METHOD),
|
||||
exactly(5)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_TWO)
|
||||
.withMethod(METHOD),
|
||||
exactly(1)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
|
||||
MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort);
|
||||
|
||||
client.when(
|
||||
request()
|
||||
.withPath(SECURITY_PATH)
|
||||
.withMethod("GET"),
|
||||
exactly(1)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
|
||||
client.when(
|
||||
request()
|
||||
.withPath(UPLOAD_PATH)
|
||||
.withMethod("POST"),
|
||||
exactly(4)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
.withHeader("Content-Type", "multipart/form-data")
|
||||
);
|
||||
}
|
||||
|
||||
private static int getFreePort () throws IOException {
|
||||
private static int getFreePort() throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
|
|
|
@ -19,7 +19,7 @@ class HttpClientCancelRequestLiveTest {
|
|||
void whenRequestIsCanceled_thenCorrect() throws IOException {
|
||||
HttpGet request = new HttpGet(SAMPLE_URL);
|
||||
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
||||
httpClient.execute(request, response -> {
|
||||
httpClient.execute(request, response -> {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
|
@ -28,6 +28,12 @@ class HttpClientCancelRequestLiveTest {
|
|||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
System.out.println("----------------------------------------");
|
||||
|
||||
if (entity != null) {
|
||||
// Closes this stream and releases any system resources
|
||||
entity.close();
|
||||
}
|
||||
|
||||
// Do not feel like reading the response body
|
||||
// Call abort on the request object
|
||||
request.abort();
|
||||
|
|
|
@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
|
|||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.apache.hc.core5.http.ParseException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
|
@ -13,7 +14,6 @@ import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
|
|||
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
|
||||
import org.apache.hc.client5.http.entity.mime.StringBody;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
||||
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
|
@ -28,9 +28,7 @@ import java.io.InputStream;
|
|||
import java.io.InputStreamReader;
|
||||
import java.net.URL;
|
||||
|
||||
import com.baeldung.httpclient.handler.CustomHttpClientResponseHandler;
|
||||
|
||||
class HttpClientMultipartLiveTest {
|
||||
class HttpClientMultipartLiveTest extends GetRequestMockServer {
|
||||
|
||||
// No longer available
|
||||
// private static final String SERVER = "http://echo.200please.com";
|
||||
|
@ -45,13 +43,15 @@ class HttpClientMultipartLiveTest {
|
|||
@BeforeEach
|
||||
public void before() {
|
||||
post = new HttpPost(SERVER);
|
||||
String URL = "http://localhost:" + serverPort + "/spring-mvc-java/stub/multipart";
|
||||
post = new HttpPost(URL);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
|
||||
final File file = new File(url.getPath());
|
||||
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
|
||||
|
@ -66,27 +66,28 @@ class HttpClientMultipartLiveTest {
|
|||
final HttpEntity entity = builder.build();
|
||||
|
||||
post.setEntity(entity);
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build();
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(post, new CustomHttpClientResponseHandler())){
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
client.execute(post, response -> {
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("multipart/form-data"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
final File file = new File(url.getPath());
|
||||
final String message = "This is a multipart post";
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
|
@ -96,30 +97,31 @@ class HttpClientMultipartLiveTest {
|
|||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build();
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(post, new CustomHttpClientResponseHandler())){
|
||||
client.execute(post, response -> {
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("multipart/form-data"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + ZIPFILENAME);
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + ZIPFILENAME);
|
||||
final URL url2 = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + IMAGEFILENAME);
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + IMAGEFILENAME);
|
||||
final InputStream inputStream = new FileInputStream(url.getPath());
|
||||
final File file = new File(url2.getPath());
|
||||
final String message = "This is a multipart post";
|
||||
|
@ -131,25 +133,25 @@ class HttpClientMultipartLiveTest {
|
|||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build();
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(post, new CustomHttpClientResponseHandler())){
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
inputStream.close();
|
||||
client.execute(post, response -> {
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
inputStream.close();
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
|
||||
void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException, ParseException {
|
||||
final String message = "This is a multipart post";
|
||||
final byte[] bytes = "binary code".getBytes();
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
|
@ -159,21 +161,20 @@ class HttpClientMultipartLiveTest {
|
|||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build();
|
||||
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(post, new CustomHttpClientResponseHandler())){
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
httpClient.execute(post, response -> {
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// UTIL
|
||||
|
|
|
@ -43,7 +43,7 @@ public class HttpClientLiveTest {
|
|||
|
||||
@Test(expected = ConnectTimeoutException.class)
|
||||
public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException {
|
||||
final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(20).build();
|
||||
final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5).setConnectTimeout(5).setSocketTimeout(2).build();
|
||||
final HttpGet request = new HttpGet(SAMPLE_URL);
|
||||
request.setConfig(requestConfig);
|
||||
response = instance.execute(request);
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
package com.baeldung.httpclient.base;
|
||||
|
||||
import com.baeldung.httpclient.GetRequestMockServer;
|
||||
import com.baeldung.httpclient.ResponseUtil;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
|
@ -9,14 +10,14 @@ import org.apache.http.client.methods.HttpGet;
|
|||
import org.apache.http.impl.client.BasicCredentialsProvider;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/*
|
||||
* NOTE : Need module spring-security-rest-basic-auth to be running
|
||||
*/
|
||||
public class HttpClientSandboxLiveTest {
|
||||
public class HttpClientSandboxLiveTest extends GetRequestMockServer {
|
||||
|
||||
@Test
|
||||
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
|
||||
|
@ -26,7 +27,7 @@ public class HttpClientSandboxLiveTest {
|
|||
|
||||
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
|
||||
|
||||
final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1");
|
||||
final HttpGet httpGet = new HttpGet("http://localhost:" + serverPort + "/spring-security-rest-basic-auth/api/foos/1");
|
||||
final CloseableHttpResponse response = client.execute(httpGet);
|
||||
|
||||
System.out.println(response.getStatusLine());
|
||||
|
|
|
@ -1,11 +0,0 @@
|
|||
package com.baeldung.httpclient.handler;
|
||||
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
|
||||
|
||||
public class CustomHttpClientResponseHandler implements HttpClientResponseHandler<ClassicHttpResponse> {
|
||||
@Override
|
||||
public ClassicHttpResponse handleResponse(ClassicHttpResponse response) {
|
||||
return response;
|
||||
}
|
||||
}
|
|
@ -199,33 +199,7 @@
|
|||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<version>${cargo-maven2-plugin.version}</version>
|
||||
<configuration>
|
||||
<wait>true</wait>
|
||||
<container>
|
||||
<containerId>jetty8x</containerId>
|
||||
<type>embedded</type>
|
||||
<systemProperties>
|
||||
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
|
||||
</systemProperties>
|
||||
</container>
|
||||
<configuration>
|
||||
<properties>
|
||||
<cargo.servlet.port>8082</cargo.servlet.port>
|
||||
</properties>
|
||||
</configuration>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
|
@ -233,26 +207,6 @@
|
|||
<id>live</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-server</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>start</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>stop-server</id>
|
||||
<phase>post-integration-test</phase>
|
||||
<goals>
|
||||
<goal>stop</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
|
@ -269,9 +223,6 @@
|
|||
<includes>
|
||||
<include>**/*LiveTest.java</include>
|
||||
</includes>
|
||||
<systemPropertyVariables>
|
||||
<webTarget>cargo</webTarget>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
|
@ -291,7 +242,6 @@
|
|||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<mockserver.version>5.11.2</mockserver.version>
|
||||
<!-- maven plugins -->
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -0,0 +1,56 @@
|
|||
package com.baeldung;
|
||||
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
import static org.mockserver.model.HttpRequest.request;
|
||||
import static org.mockserver.model.HttpResponse.response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.mockserver.integration.ClientAndServer;
|
||||
|
||||
public class GetRequestMockServer {
|
||||
|
||||
public static ClientAndServer mockServer;
|
||||
public static int serverPort;
|
||||
public static String simplePathUrl;
|
||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
public static final String SIMPLE_PATH = "/httpclient-simple/api/bars/1";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException {
|
||||
serverPort = getFreePort();
|
||||
System.out.println("Free port " + serverPort);
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
|
||||
simplePathUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + SIMPLE_PATH;
|
||||
|
||||
mockGetRequest();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
mockServer.stop();
|
||||
}
|
||||
|
||||
private static void mockGetRequest() {
|
||||
|
||||
MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort);
|
||||
|
||||
client.when(request().withPath(SIMPLE_PATH)
|
||||
.withMethod("GET"))
|
||||
.respond(response().withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}"));
|
||||
}
|
||||
|
||||
private static int getFreePort() throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -10,7 +10,7 @@ import java.io.IOException;
|
|||
import java.security.GeneralSecurityException;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLPeerUnverifiedException;
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
|
@ -31,10 +31,10 @@ import org.springframework.http.ResponseEntity;
|
|||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import com.baeldung.GetRequestMockServer;
|
||||
|
||||
class ClientLiveTest {
|
||||
class ClientLiveTest extends GetRequestMockServer {
|
||||
|
||||
final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
|
||||
|
||||
@Test
|
||||
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
|
||||
|
@ -54,13 +54,13 @@ class ClientLiveTest {
|
|||
.build();
|
||||
|
||||
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
|
||||
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
|
||||
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(simplePathUrl, HttpMethod.GET, null, String.class);
|
||||
assertThat(response.getStatusCode().value(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
|
||||
final HttpGet getMethod = new HttpGet(urlOverHttps);
|
||||
final HttpGet getMethod = new HttpGet(simplePathUrl);
|
||||
|
||||
try (final CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setSSLHostnameVerifier(new NoopHostnameVerifier())
|
||||
|
@ -80,20 +80,22 @@ class ClientLiveTest {
|
|||
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
requestFactory.setHttpClient(httpClient);
|
||||
|
||||
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
|
||||
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(simplePathUrl, HttpMethod.GET, null, String.class);
|
||||
assertThat(response.getStatusCode().value(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenHttpsUrlIsConsumed_thenException() {
|
||||
String urlOverHttps = "https://localhost:8082/httpclient-simple";
|
||||
String urlOverHttps = "https://localhost:"+serverPort+"/httpclient-simple/api/bars/1";
|
||||
HttpGet getMethod = new HttpGet(urlOverHttps);
|
||||
|
||||
assertThrows(SSLPeerUnverifiedException.class, () -> {
|
||||
assertThrows(SSLHandshakeException.class, () -> {
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine()
|
||||
.getStatusCode(), equalTo(200));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.client;
|
||||
|
||||
import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
|
@ -89,4 +88,5 @@ public class RestClientV4LiveManualTest {
|
|||
HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,77 +0,0 @@
|
|||
package com.baeldung.httpclient;
|
||||
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
import static org.mockserver.matchers.Times.exactly;
|
||||
import static org.mockserver.model.HttpRequest.request;
|
||||
import static org.mockserver.model.HttpResponse.response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.mockserver.integration.ClientAndServer;
|
||||
|
||||
public class GetRequestMockServer {
|
||||
|
||||
public static ClientAndServer mockServer;
|
||||
public static String serviceOneUrl;
|
||||
public static String serviceTwoUrl;
|
||||
|
||||
public static int serverPort;
|
||||
|
||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
public static final String PATH_ONE = "/test1";
|
||||
public static final String PATH_TWO = "/test2";
|
||||
public static final String METHOD = "GET";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException, URISyntaxException {
|
||||
serverPort = getFreePort();
|
||||
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
|
||||
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
mockGetRequest();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
mockServer.stop();
|
||||
}
|
||||
|
||||
private static void mockGetRequest() {
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_ONE)
|
||||
.withMethod(METHOD),
|
||||
exactly(5)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_TWO)
|
||||
.withMethod(METHOD),
|
||||
exactly(1)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
}
|
||||
|
||||
private static int getFreePort () throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -31,6 +31,7 @@ import org.apache.http.protocol.HttpContext;
|
|||
import org.apache.http.ssl.SSLContexts;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.GetRequestMockServer;
|
||||
|
||||
class HttpAsyncClientV4LiveTest extends GetRequestMockServer {
|
||||
|
||||
|
|
|
@ -44,7 +44,9 @@ public class HttpClientCancelRequestV4LiveTest {
|
|||
System.out.println(response.getStatusLine());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
entity.getContent().close();
|
||||
}
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
|
||||
// Do not feel like reading the response body
|
||||
|
|
|
@ -21,7 +21,9 @@ import org.junit.jupiter.api.AfterEach;
|
|||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class HttpClientTimeoutV4LiveTest {
|
||||
import com.baeldung.GetRequestMockServer;
|
||||
|
||||
class HttpClientTimeoutV4LiveTest extends GetRequestMockServer {
|
||||
|
||||
private CloseableHttpResponse response;
|
||||
|
||||
|
@ -97,7 +99,7 @@ class HttpClientTimeoutV4LiveTest {
|
|||
int timeout = 20; // seconds
|
||||
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000)
|
||||
.setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
|
||||
HttpGet getMethod = new HttpGet("http://localhost:8082/httpclient-simple/api/bars/1");
|
||||
HttpGet getMethod = new HttpGet(simplePathUrl);
|
||||
getMethod.setConfig(requestConfig);
|
||||
|
||||
int hardTimeout = 5; // seconds
|
||||
|
|
|
@ -13,13 +13,15 @@ import org.apache.http.impl.client.HttpClientBuilder;
|
|||
import org.apache.http.util.EntityUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.GetRequestMockServer;
|
||||
|
||||
class ApacheHttpClientUnitTest extends GetRequestMockServer {
|
||||
|
||||
|
||||
@Test
|
||||
void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
|
||||
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
|
||||
HttpGet httpGet = new HttpGet(serviceOneUrl);
|
||||
HttpGet httpGet = new HttpGet(simplePathUrl);
|
||||
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
|
||||
HttpEntity entity = response.getEntity();
|
||||
EntityUtils.consume(entity);
|
||||
|
|
|
@ -1,78 +0,0 @@
|
|||
package com.baeldung.httpclient.httpclient;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.mockserver.integration.ClientAndServer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
import static org.mockserver.matchers.Times.exactly;
|
||||
import static org.mockserver.model.HttpRequest.request;
|
||||
import static org.mockserver.model.HttpResponse.response;
|
||||
|
||||
public class GetRequestMockServer {
|
||||
|
||||
public static ClientAndServer mockServer;
|
||||
public static String serviceOneUrl;
|
||||
public static String serviceTwoUrl;
|
||||
|
||||
private static int serverPort;
|
||||
|
||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
public static final String PATH_ONE = "/test1";
|
||||
public static final String PATH_TWO = "/test2";
|
||||
public static final String METHOD = "GET";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException, URISyntaxException {
|
||||
serverPort = getFreePort();
|
||||
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
|
||||
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
mockGetRequest();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
mockServer.stop();
|
||||
}
|
||||
|
||||
private static void mockGetRequest() {
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_ONE)
|
||||
.withMethod(METHOD),
|
||||
exactly(5)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_TWO)
|
||||
.withMethod(METHOD),
|
||||
exactly(1)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
}
|
||||
|
||||
private static int getFreePort () throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,7 +1,7 @@
|
|||
<?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">
|
||||
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>apache-poi-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
|
|
@ -100,7 +100,6 @@
|
|||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
<properties>
|
||||
<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>
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-groovy-2</artifactId>
|
||||
|
@ -117,11 +118,11 @@
|
|||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.20.1</version>
|
||||
<configuration>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Test.java</include>
|
||||
<include>**/*Spec.java</include>
|
||||
</includes>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Test.java</include>
|
||||
<include>**/*Spec.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!-- 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 java.io.IOException;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
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 javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLEngine;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509ExtendedTrustManager;
|
||||
|
||||
public class HttpClientSSLBypassUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenHttpsRequest_thenCorrect() throws IOException, InterruptedException {
|
||||
public void givenDisableUsingJVMProperty_whenByPassCertificationVerification_thenSuccessHttpResponse() throws IOException, InterruptedException {
|
||||
final Properties props = System.getProperties();
|
||||
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.build();
|
||||
.build();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("https://wrong.host.badssl.com/"))
|
||||
.build();
|
||||
.uri(URI.create("https://wrong.host.badssl.com/"))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.FALSE.toString());
|
||||
|
||||
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>
|
||||
</transformer>
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
|
||||
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
|
||||
</transformers>
|
||||
<filters>
|
||||
<filter>
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
## Relevant Articles
|
||||
- [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values)
|
||||
- [How to Read Zip Files Entries With Java](https://www.baeldung.com/java-read-zip-files)
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
<?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"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<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.Paths;
|
||||
|
||||
public class ZipEntryReaderTest {
|
||||
public class ZipEntryReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenZipFile_thenReadEntriesAndValidateContent() throws URISyntaxException, IOException {
|
|
@ -1,55 +1,55 @@
|
|||
<?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"
|
||||
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</groupId>
|
||||
<artifactId>core-java-9-jigsaw</artifactId>
|
||||
<version>0.2-SNAPSHOT</version>
|
||||
</parent>
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-9-jigsaw</artifactId>
|
||||
<version>0.2-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>library-core</artifactId>
|
||||
<artifactId>library-core</artifactId>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>19</maven.compiler.source>
|
||||
<maven.compiler.target>19</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<properties>
|
||||
<maven.compiler.source>19</maven.compiler.source>
|
||||
<maven.compiler.target>19</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>5.9.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>5.9.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>5.9.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>5.9.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<release>9</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.0.0-M5</version>
|
||||
<configuration>
|
||||
<useModulePath>false</useModulePath>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<release>9</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.0.0-M5</version>
|
||||
<configuration>
|
||||
<useModulePath>false</useModulePath>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -1,7 +1,7 @@
|
|||
<?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">
|
||||
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-collections-5</artifactId>
|
||||
<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)
|
||||
- [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)
|
||||
- [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)
|
||||
|
|
|
@ -14,7 +14,7 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.36</version>
|
||||
|
@ -45,7 +45,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<jmh.version>1.21</jmh.version>
|
||||
<jmh.version>1.21</jmh.version>
|
||||
<commons-lang.version>2.2</commons-lang.version>
|
||||
<commons-lang3.version>3.12.0</commons-lang3.version>
|
||||
</properties>
|
||||
|
|
|
@ -3,3 +3,5 @@
|
|||
- [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 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)
|
||||
- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded)
|
||||
- [How to Check if All Runnables Are Done](https://www.baeldung.com/java-runnables-check-status)
|
||||
- [Parallelize for Loop in Java](https://www.baeldung.com/java-for-loop-parallel)
|
||||
|
|
|
@ -8,4 +8,6 @@ This module contains articles about basic Java concurrency.
|
|||
- [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await)
|
||||
- [Is CompletableFuture Non-blocking?](https://www.baeldung.com/java-completablefuture-non-blocking)
|
||||
- [Returning a Value After Finishing Thread’s Job in Java](https://www.baeldung.com/java-return-value-after-thread-finish)
|
||||
- [CompletableFuture and ThreadPool in Java](https://www.baeldung.com/java-completablefuture-threadpool)
|
||||
- [CompletableFuture allOf().join() vs. CompletableFuture.join()](https://www.baeldung.com/java-completablefuture-allof-join)
|
||||
- [[<-- 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)
|
||||
- [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)
|
||||
- [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)
|
||||
|
|
|
@ -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>
|
||||
<version>2.4.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -56,7 +66,7 @@
|
|||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<classpath/>
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
|
@ -70,6 +80,16 @@
|
|||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</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>
|
||||
</build>
|
||||
|
||||
|
@ -120,7 +140,7 @@
|
|||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<classpath/>
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
package com.baeldung.asciiart;
|
||||
|
||||
import com.baeldung.asciiart.AsciiArt.Settings;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.Font;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.asciiart.AsciiArt.Settings;
|
||||
|
||||
public class AsciiArtIntegrationTest {
|
||||
|
||||
@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)
|
||||
- [Adding One Month to Current Date in Java](https://www.baeldung.com/java-adding-one-month-to-current-date)
|
||||
- [How to Get Last Day of a Month in Java](https://www.baeldung.com/java-last-day-month)
|
||||
- [Getting Yesterday’s Date in Java](https://www.baeldung.com/java-find-yesterdays-date)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-date-operations-2)
|
||||
|
|
|
@ -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:
|
||||
- [Constructing a Relative Path From Two Absolute Paths in Java](https://www.baeldung.com/java-relative-path-absolute)
|
||||
- [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input)
|
||||
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
|
||||
- [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer)
|
||||
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||
- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
||||
- [Storing Java Scanner Input in an Array](https://www.baeldung.com/java-store-scanner-input-in-array)
|
||||
- [How to Take Input as String With Spaces in Java Using Scanner?](https://www.baeldung.com/java-scanner-input-with-spaces)
|
||||
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
|
||||
- [What’s the difference between Scanner next() and nextLine() methods?](https://www.baeldung.com/java-scanner-next-vs-nextline)
|
||||
- [Handle NoSuchElementException When Reading a File Through Scanner](https://www.baeldung.com/java-scanner-nosuchelementexception-reading-file)
|
||||
- [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty)
|
|
@ -92,12 +92,6 @@
|
|||
<version>7.1.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>7.5</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>core-java-io-apis-2</finalName>
|
||||
|
|
|
@ -0,0 +1,71 @@
|
|||
package com.baeldung.emptyfile;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class CheckFileIsEmptyUnitTest {
|
||||
@Test
|
||||
void whenTheFileIsEmpty_thenFileLengthIsZero(@TempDir Path tempDir) throws IOException {
|
||||
File emptyFile = tempDir.resolve("an-empty-file.txt")
|
||||
.toFile();
|
||||
emptyFile.createNewFile();
|
||||
assertTrue(emptyFile.exists());
|
||||
assertEquals(0, emptyFile.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFileDoesNotExist_thenFileLengthIsZero(@TempDir Path tempDir) {
|
||||
File aNewFile = tempDir.resolve("a-new-file.txt")
|
||||
.toFile();
|
||||
assertFalse(aNewFile.exists());
|
||||
assertEquals(0, aNewFile.length());
|
||||
}
|
||||
|
||||
boolean isFileEmpty(File file) {
|
||||
if (!file.exists()) {
|
||||
throw new IllegalArgumentException("Cannot check the file length. The file is not found: " + file.getAbsolutePath());
|
||||
}
|
||||
return file.length() == 0;
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTheFileDoesNotExist_thenIsFilesEmptyThrowsException(@TempDir Path tempDir) {
|
||||
File aNewFile = tempDir.resolve("a-new-file.txt")
|
||||
.toFile();
|
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> isFileEmpty(aNewFile));
|
||||
assertEquals(ex.getMessage(), "Cannot check the file length. The file is not found: " + aNewFile.getAbsolutePath());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTheFileIsEmpty_thenIsFilesEmptyReturnsTrue(@TempDir Path tempDir) throws IOException {
|
||||
File emptyFile = tempDir.resolve("an-empty-file.txt")
|
||||
.toFile();
|
||||
emptyFile.createNewFile();
|
||||
assertTrue(isFileEmpty(emptyFile));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTheFileIsEmpty_thenFilesSizeReturnsTrue(@TempDir Path tempDir) throws IOException {
|
||||
Path emptyFilePath = tempDir.resolve("an-empty-file.txt");
|
||||
Files.createFile(emptyFilePath);
|
||||
assertEquals(0, Files.size(emptyFilePath));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTheFileDoesNotExist_thenFilesSizeThrowsException(@TempDir Path tempDir) {
|
||||
Path aNewFilePath = tempDir.resolve("a-new-file.txt");
|
||||
assertThrows(NoSuchFileException.class, () -> Files.size(aNewFilePath));
|
||||
}
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
## Core Java IO APIs
|
||||
|
||||
This module contains articles about core Java input/output(IO) APIs.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Read Date in Java Using Scanner](https://www.baeldung.com/java-scanner-read-date)
|
|
@ -1,15 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-io-apis-3</artifactId>
|
||||
<name>core-java-io-apis-3</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
</project>
|
|
@ -10,6 +10,6 @@ This module contains articles about core Java input/output(IO) APIs.
|
|||
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](https://www.baeldung.com/java-path)
|
||||
- [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter)
|
||||
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
||||
- [Java Scanner](https://www.baeldung.com/java-scanner)
|
||||
- [Scanner nextLine() Method](https://www.baeldung.com/java-scanner-nextline)
|
||||
- [Java Scanner hasNext() vs. hasNextLine()](https://www.baeldung.com/java-scanner-hasnext-vs-hasnextline)
|
||||
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||
- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
||||
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
|
|
@ -31,6 +31,12 @@
|
|||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>7.5</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -1,36 +1,36 @@
|
|||
package com.baeldung.multinput;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class MultiInputs {
|
||||
public void UsingSpaceDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Enter two numbers: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingREDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter("[\\s,]+");
|
||||
System.out.print("Enter two numbers separated by a space or a comma: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingCustomDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter(";");
|
||||
System.out.print("Enter two numbers separated by a semicolon: ");
|
||||
try { int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2); }
|
||||
catch (InputMismatchException e)
|
||||
{ System.out.println("Invalid input. Please enter two integers separated by a semicolon."); }
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
package com.baeldung.multinput;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class MultiInputs {
|
||||
public void UsingSpaceDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Enter two numbers: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingREDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter("[\\s,]+");
|
||||
System.out.print("Enter two numbers separated by a space or a comma: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingCustomDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter(";");
|
||||
System.out.print("Enter two numbers separated by a semicolon: ");
|
||||
try { int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2); }
|
||||
catch (InputMismatchException e)
|
||||
{ System.out.println("Invalid input. Please enter two integers separated by a semicolon."); }
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -1,36 +1,36 @@
|
|||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BufferedReaderUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReadingAFile_thenReadsLineByLine() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
final Path filePath = new File("src/test/resources/sampleText1.txt").toPath();
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(filePath), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
|
||||
while((line = br.readLine()) != null) {
|
||||
result.append(line);
|
||||
result.append('\n');
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("first line\nsecond line\nthird line\n", result.toString());
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BufferedReaderUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReadingAFile_thenReadsLineByLine() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
final Path filePath = new File("src/test/resources/sampleText1.txt").toPath();
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(filePath), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
|
||||
while((line = br.readLine()) != null) {
|
||||
result.append(line);
|
||||
result.append('\n');
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("first line\nsecond line\nthird line\n", result.toString());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,30 +1,30 @@
|
|||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReadingAFile_thenReadsCharByChar() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
|
||||
int i = fr.read();
|
||||
|
||||
while(i != -1) {
|
||||
result.append((char)i);
|
||||
|
||||
i = fr.read();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("qwerty", result.toString());
|
||||
}
|
||||
}
|
||||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReadingAFile_thenReadsCharByChar() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
|
||||
int i = fr.read();
|
||||
|
||||
while(i != -1) {
|
||||
result.append((char)i);
|
||||
|
||||
i = fr.read();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("qwerty", result.toString());
|
||||
}
|
||||
}
|
|
@ -1,47 +1,49 @@
|
|||
package com.baeldung.multinput;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.InputMismatchException;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.testng.annotations.Test;
|
||||
import com.baeldung.multinput.MultiInputs;
|
||||
public class TestMultipleInputsUnitTest {
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "10 20\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingSpaceDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingREDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "30, 40\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingREDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingCustomDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "50; 60\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingCustomDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidInput_whenUsingSpaceDelimiter_thenExpectInputMismatchException() {
|
||||
String input = "abc\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
Assertions.assertThrows(InputMismatchException.class, mi::UsingSpaceDelimiter);
|
||||
}
|
||||
}
|
||||
package com.baeldung.multinput;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.InputMismatchException;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class TestMultipleInputsUnitTest {
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "10 20\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingSpaceDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingREDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "30, 40\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingREDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingCustomDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "50; 60\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingCustomDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidInput_whenUsingSpaceDelimiter_thenExpectInputMismatchException() {
|
||||
String input = "abc\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
Assertions.assertThrows(InputMismatchException.class, mi::UsingSpaceDelimiter);
|
||||
}
|
||||
}
|
|
@ -64,7 +64,7 @@
|
|||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<classpath/>
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
|
@ -116,7 +116,7 @@
|
|||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<classpath/>
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
|
|
|
@ -4,7 +4,7 @@ This module contains articles about JAR files
|
|||
|
||||
### 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)
|
||||
- [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)
|
||||
|
|
|
@ -189,7 +189,7 @@
|
|||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<classpath/>
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
|
@ -253,7 +253,7 @@
|
|||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<classpath/>
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
|
|
|
@ -168,6 +168,7 @@
|
|||
|
||||
<properties>
|
||||
<javaassist.version>3.27.0-GA</javaassist.version>
|
||||
<esapi.version>2.5.2.0</esapi.version>
|
||||
<jol-core.version>0.10</jol-core.version>
|
||||
<asm.version>9.4</asm.version>
|
||||
<bcel.version>6.5.0</bcel.version>
|
||||
|
|
|
@ -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)
|
|
@ -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:
|
||||
|
||||
- [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)
|
||||
- [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)
|
||||
|
|
|
@ -29,7 +29,7 @@
|
|||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
<compilerArguments>
|
||||
<Xlint:unchecked />
|
||||
<Xlint:unchecked/>
|
||||
</compilerArguments>
|
||||
</configuration>
|
||||
</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)
|
||||
- [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)
|
||||
- [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 {
|
||||
return (Course) super.clone();
|
||||
} catch (CloneNotSupportedException e) {
|
||||
throw new AssertionError();
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -95,7 +95,7 @@ public class Student implements Serializable, Cloneable {
|
|||
try {
|
||||
student = (Student) super.clone();
|
||||
} catch (CloneNotSupportedException e) {
|
||||
throw new AssertionError();
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
student.course = this.course.clone();
|
||||
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);
|
||||
}
|
||||
}
|
|
@ -13,7 +13,7 @@
|
|||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
<?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"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-networking</artifactId>
|
||||
<name>core-java-networking</name>
|
||||
|
|
|
@ -65,6 +65,7 @@ public class NioVsNio2UnitTest {
|
|||
public void listFilesUsingWalk() throws Exception {
|
||||
Path path = Paths.get("src/test");
|
||||
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:
|
||||
- [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)
|
||||
- [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)
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue