diff --git a/.gitignore b/.gitignore
index d68ab983497a..7725bf202ed4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -89,6 +89,7 @@ spring-soap/src/main/java/com/baeldung/springsoap/gen/
/report-*.json
transaction.log
*-shell.log
+customers.xml
apache-cxf/cxf-aegis/baeldung.xml
testing-modules/report-*.json
diff --git a/akka-modules/akka-http/pom.xml b/akka-modules/akka-http/pom.xml
index 3af7c492ca48..9372107fc9f2 100644
--- a/akka-modules/akka-http/pom.xml
+++ b/akka-modules/akka-http/pom.xml
@@ -36,7 +36,6 @@
-
10.0.11
2.5.11
diff --git a/algorithms-modules/algorithms-miscellaneous-7/README.md b/algorithms-modules/algorithms-miscellaneous-7/README.md
index 53c218a40c27..ab07d655f93c 100644
--- a/algorithms-modules/algorithms-miscellaneous-7/README.md
+++ b/algorithms-modules/algorithms-miscellaneous-7/README.md
@@ -2,4 +2,5 @@
- [Algorithm to Identify and Validate a Credit Card Number](https://www.baeldung.com/java-validate-cc-number)
- [Find the N Most Frequent Elements in a Java Array](https://www.baeldung.com/java-n-most-frequent-elements-array)
+- [Getting Pixel Array From Image in Java](https://www.baeldung.com/java-getting-pixel-array-from-image)
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/pixelarray/GetPixelArray.java b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/pixelarray/GetPixelArray.java
new file mode 100644
index 000000000000..ba7fe448083d
--- /dev/null
+++ b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/pixelarray/GetPixelArray.java
@@ -0,0 +1,65 @@
+package com.baeldung.algorithms.pixelarray;
+
+import java.awt.image.BufferedImage;
+import java.awt.image.DataBufferByte;
+public class GetPixelArray {
+
+ public static int[][] get2DPixelArraySlow(BufferedImage sampleImage) {
+ int width = sampleImage.getWidth();
+ int height = sampleImage.getHeight();
+ int[][] result = new int[height][width];
+
+ for (int row = 0; row < height; row++) {
+ for (int col = 0; col < width; col++) {
+ result[row][col] = sampleImage.getRGB(col, row);
+ }
+ }
+
+ return result;
+ }
+
+ public static int[][] get2DPixelArrayFast(BufferedImage image) {
+ final byte[] pixelData = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
+ final int width = image.getWidth();
+ final int height = image.getHeight();
+ final boolean hasAlphaChannel = image.getAlphaRaster() != null;
+
+ int[][] result = new int[height][width];
+ if (hasAlphaChannel) {
+ final int numberOfValues = 4;
+ for (int valueIndex = 0, row = 0, col = 0; valueIndex + numberOfValues - 1 < pixelData.length; valueIndex += numberOfValues) {
+ // Getting the values for each pixel from the pixelData array.
+ int argb = 0;
+ argb += (((int) pixelData[valueIndex] & 0xff) << 24); // alpha value
+ argb += ((int) pixelData[valueIndex + 1] & 0xff); // blue value
+ argb += (((int) pixelData[valueIndex + 2] & 0xff) << 8); // green value
+ argb += (((int) pixelData[valueIndex + 3] & 0xff) << 16); // red value
+ result[row][col] = argb;
+
+ col++;
+ if (col == width) {
+ col = 0;
+ row++;
+ }
+ }
+ } else {
+ final int numberOfValues = 3;
+ for (int valueIndex = 0, row = 0, col = 0; valueIndex + numberOfValues - 1 < pixelData.length; valueIndex += numberOfValues) {
+ int argb = 0;
+ argb += -16777216; // 255 alpha value (fully opaque)
+ argb += ((int) pixelData[valueIndex] & 0xff); // blue value
+ argb += (((int) pixelData[valueIndex + 1] & 0xff) << 8); // green value
+ argb += (((int) pixelData[valueIndex + 2] & 0xff) << 16); // red value
+ result[row][col] = argb;
+
+ col++;
+ if (col == width) {
+ col = 0;
+ row++;
+ }
+ }
+ }
+
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/main/resources/images/sampleImage.jpg b/algorithms-modules/algorithms-miscellaneous-7/src/main/resources/images/sampleImage.jpg
new file mode 100644
index 000000000000..c2f035ae641a
Binary files /dev/null and b/algorithms-modules/algorithms-miscellaneous-7/src/main/resources/images/sampleImage.jpg differ
diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/pixelarray/GetPixelArrayUnitTest.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/pixelarray/GetPixelArrayUnitTest.java
new file mode 100644
index 000000000000..b7bbb462dd94
--- /dev/null
+++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/pixelarray/GetPixelArrayUnitTest.java
@@ -0,0 +1,30 @@
+package com.baeldung.algorithms.pixelarray;
+
+import static com.baeldung.algorithms.pixelarray.GetPixelArray.get2DPixelArrayFast;
+import static com.baeldung.algorithms.pixelarray.GetPixelArray.get2DPixelArraySlow;
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+
+public class GetPixelArrayUnitTest {
+ @Test
+ public void givenImage_whenGetPixelArray_thenBothMethodsReturnEqualValues() {
+ BufferedImage sampleImage = null;
+ try {
+ sampleImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ int[][] firstResult = get2DPixelArraySlow(sampleImage);
+ int[][] secondResult = get2DPixelArrayFast(sampleImage);
+
+ assertTrue(Arrays.deepEquals(firstResult, secondResult));
+ }
+}
diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml
index 2a17242ee5bb..14bbc409e5f8 100644
--- a/annotations/annotation-processing/pom.xml
+++ b/annotations/annotation-processing/pom.xml
@@ -21,7 +21,6 @@
-
1.0-rc2
diff --git a/apache-httpclient-2/README.md b/apache-httpclient-2/README.md
index 45f1e41637b2..a19112476bf2 100644
--- a/apache-httpclient-2/README.md
+++ b/apache-httpclient-2/README.md
@@ -12,6 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string)
- [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies)
- [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging)
-- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
+- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
- More articles: [[<-- prev]](../apache-httpclient)
diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/expandUrl/HttpClientExpandUrlLiveTest.java b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/expandUrl/HttpClientExpandUrlLiveTest.java
new file mode 100644
index 000000000000..c1bb5bdddb08
--- /dev/null
+++ b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/expandUrl/HttpClientExpandUrlLiveTest.java
@@ -0,0 +1,126 @@
+package com.baeldung.httpclient.expandUrl;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+
+import java.io.IOException;
+import java.util.List;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.Pair;
+
+import org.apache.hc.client5.http.classic.methods.HttpHead;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+
+import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpHeaders;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+class HttpClientExpandUrlLiveTest {
+
+ private static CloseableHttpClient httpClient;
+
+ @BeforeAll
+ static void setup() {
+ httpClient = HttpClientBuilder.create()
+ .disableRedirectHandling()
+ .build();
+ }
+
+ @AfterAll
+ static void tearDown() throws IOException {
+ if (httpClient != null) {
+ httpClient.close();
+ }
+ }
+
+ @Test
+ void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException {
+ final String expectedResult = "https://www.baeldung.com/rest-versioning";
+ final String actualResult = expandSingleLevel("http://bit.ly/3LScTri");
+ assertThat(actualResult, equalTo(expectedResult));
+ }
+
+ @Test
+ void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException {
+ final String expectedResult = "https://www.baeldung.com/rest-versioning";
+ final String actualResult = expand("http://t.co/e4rDDbnzmk");
+ assertThat(actualResult, equalTo(expectedResult));
+ }
+
+ private String expand(final String urlArg) throws IOException {
+ String originalUrl = urlArg;
+ String newUrl = expandSingleLevel(originalUrl);
+ while (!originalUrl.equals(newUrl)) {
+ originalUrl = newUrl;
+ newUrl = expandSingleLevel(originalUrl);
+ }
+
+ return newUrl;
+ }
+
+ final String expandSafe(final String urlArg) throws IOException {
+ String originalUrl = urlArg;
+ String newUrl = expandSingleLevelSafe(originalUrl).getRight();
+ final List alreadyVisited = Lists.newArrayList(originalUrl, newUrl);
+ while (!originalUrl.equals(newUrl)) {
+ originalUrl = newUrl;
+ final Pair statusAndUrl = expandSingleLevelSafe(originalUrl);
+ newUrl = statusAndUrl.getRight();
+ final boolean isRedirect = statusAndUrl.getLeft() == 301 || statusAndUrl.getLeft() == 302;
+ if (isRedirect && alreadyVisited.contains(newUrl)) {
+ throw new IllegalStateException("Likely a redirect loop");
+ }
+ alreadyVisited.add(newUrl);
+ }
+
+ return newUrl;
+ }
+
+ private Pair expandSingleLevelSafe(final String url) throws IOException {
+ try {
+ HttpHead request = new HttpHead(url);
+ Pair resp = httpClient.execute(request, response -> {
+ final int statusCode = response.getCode();
+ if (statusCode != 301 && statusCode != 302) {
+ return new ImmutablePair<>(statusCode, url);
+ }
+ final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
+ Preconditions.checkState(headers.length == 1);
+ final String newUrl = headers[0].getValue();
+
+ return new ImmutablePair<>(statusCode, newUrl);
+ });
+ return resp;
+ } catch (final IllegalArgumentException uriEx) {
+ return new ImmutablePair<>(500, url);
+ }
+ }
+
+ private String expandSingleLevel(final String url) throws IOException {
+ try {
+ HttpHead request = new HttpHead(url);
+ String expandedUrl = httpClient.execute(request, response -> {
+ final int statusCode = response.getCode();
+ if (statusCode != 301 && statusCode != 302) {
+ return url;
+ }
+ final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
+ Preconditions.checkState(headers.length == 1);
+
+ return headers[0].getValue();
+ });
+ return expandedUrl;
+ } catch (final IllegalArgumentException uriEx) {
+ return url;
+ }
+ }
+
+}
diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java
index 082c28230690..ab0e4e630876 100644
--- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java
+++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java
@@ -1,7 +1,7 @@
package com.baeldung.httpclient;
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
@@ -9,30 +9,36 @@
import javax.net.ssl.SSLContext;
-import org.apache.http.HttpHost;
-import org.apache.http.HttpResponse;
-import org.apache.http.auth.AuthScope;
-import org.apache.http.auth.UsernamePasswordCredentials;
-import org.apache.http.client.CredentialsProvider;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.protocol.HttpClientContext;
-import org.apache.http.conn.ssl.NoopHostnameVerifier;
-import org.apache.http.conn.ssl.TrustStrategy;
-import org.apache.http.impl.client.BasicCookieStore;
-import org.apache.http.impl.client.BasicCredentialsProvider;
-import org.apache.http.impl.cookie.BasicClientCookie;
-import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
-import org.apache.http.impl.nio.client.HttpAsyncClients;
-import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
-import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
-import org.apache.http.nio.reactor.ConnectingIOReactor;
-import org.apache.http.protocol.BasicHttpContext;
-import org.apache.http.protocol.HttpContext;
-import org.apache.http.ssl.SSLContexts;
-import org.junit.Test;
-
-public class HttpAsyncClientLiveTest {
+import org.junit.jupiter.api.Test;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
+import org.apache.hc.client5.http.auth.AuthScope;
+import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.config.RequestConfig;
+import org.apache.hc.client5.http.cookie.BasicCookieStore;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
+import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
+import org.apache.hc.client5.http.impl.cookie.BasicClientCookie;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
+import org.apache.hc.core5.http.protocol.BasicHttpContext;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.ssl.SSLContexts;
+import org.apache.hc.core5.ssl.TrustStrategy;
+
+
+class HttpAsyncClientLiveTest {
private static final String HOST = "http://www.google.com";
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
@@ -48,23 +54,33 @@ public class HttpAsyncClientLiveTest {
// tests
@Test
- public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
+ void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
+ final HttpHost target = new HttpHost(HOST);
+ final SimpleHttpRequest request = SimpleRequestBuilder.get()
+ .setHttpHost(target)
+ .build();
+
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
- final HttpGet request = new HttpGet(HOST);
- final Future future = client.execute(request, null);
+
+ final Future future = client.execute(request, null);
final HttpResponse response = future.get();
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ assertThat(response.getCode(), equalTo(200));
client.close();
}
@Test
- public void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception {
- final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
- final PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
- final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setConnectionManager(cm).build();
+ void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception {
+ final IOReactorConfig ioReactorConfig = IOReactorConfig
+ .custom()
+ .build();
+
+ final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
+ .setIOReactorConfig(ioReactorConfig)
+ .build();
+
client.start();
final String[] toGet = { "http://www.google.com/", "http://www.apache.org/", "http://www.bing.com/" };
@@ -85,36 +101,68 @@ public void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception {
}
@Test
- public void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
+ void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
final HttpHost proxy = new HttpHost("127.0.0.1", 8080);
final RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
- final HttpGet request = new HttpGet(HOST_WITH_PROXY);
+ final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,HOST_WITH_PROXY);
request.setConfig(config);
- final Future future = client.execute(request, null);
- final HttpResponse response = future.get();
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ final Future future = client.execute(request, new FutureCallback<>(){
+ @Override
+ public void completed(SimpleHttpResponse response) {
+
+ System.out.println("responseData");
+ }
+
+ @Override
+ public void failed(Exception ex) {
+ System.out.println("Error executing HTTP request: " + ex.getMessage());
+ }
+
+ @Override
+ public void cancelled() {
+ System.out.println("HTTP request execution cancelled");
+ }
+ });
+
+ final HttpResponse response = future.get();
+ assertThat(response.getCode(), equalTo(200));
client.close();
}
@Test
- public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
+ void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
- final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
- final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext).build();
+ final SSLContext sslContext = SSLContexts.custom()
+ .loadTrustMaterial(null, acceptingTrustStrategy)
+ .build();
+
+ final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
+ .setSslContext(sslContext)
+ .build();
+
+ final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create()
+ .setTlsStrategy(tlsStrategy)
+ .build();
+
+ final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
+ .setConnectionManager(cm)
+ .build();
client.start();
- final HttpGet request = new HttpGet(HOST_WITH_SSL);
- final Future future = client.execute(request, null);
+
+ final SimpleHttpRequest request = new SimpleHttpRequest("GET",HOST_WITH_SSL);
+ final Future future = client.execute(request, null);
+
final HttpResponse response = future.get();
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ assertThat(response.getCode(), equalTo(200));
client.close();
}
@Test
- public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
+ void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234");
cookie.setDomain(COOKIE_DOMAIN);
@@ -122,29 +170,36 @@ public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
cookieStore.addCookie(cookie);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
client.start();
- final HttpGet request = new HttpGet(HOST_WITH_COOKIE);
+ final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,HOST_WITH_COOKIE);
final HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
- final Future future = client.execute(request, localContext, null);
+ final Future future = client.execute(request, localContext, null);
+
final HttpResponse response = future.get();
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ assertThat(response.getCode(), equalTo(200));
client.close();
}
@Test
- public void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
- final CredentialsProvider provider = new BasicCredentialsProvider();
- final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
- provider.setCredentials(AuthScope.ANY, creds);
- final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build();
+ void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
+ final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
+ final UsernamePasswordCredentials credentials =
+ new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS.toCharArray());
+ credsProvider.setCredentials(new AuthScope(URL_SECURED_BY_BASIC_AUTHENTICATION, 80) ,credentials);
+ final CloseableHttpAsyncClient client = HttpAsyncClients
+ .custom()
+ .setDefaultCredentialsProvider(credsProvider).build();
+
+ final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,URL_SECURED_BY_BASIC_AUTHENTICATION);
- final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
client.start();
- final Future future = client.execute(request, null);
+
+ final Future future = client.execute(request, null);
+
final HttpResponse response = future.get();
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ assertThat(response.getCode(), equalTo(200));
client.close();
}
@@ -163,9 +218,9 @@ static class GetThread extends Thread {
@Override
public void run() {
try {
- final Future future = client.execute(request, context, null);
+ final Future future = client.execute(SimpleHttpRequest.copy(request), context, null);
final HttpResponse response = future.get();
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ assertThat(response.getCode(), equalTo(200));
} catch (final Exception ex) {
System.out.println(ex.getLocalizedMessage());
}
diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java
new file mode 100644
index 000000000000..d19e0e1d86cc
--- /dev/null
+++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java
@@ -0,0 +1,40 @@
+package com.baeldung.httpclient;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.core5.http.HttpEntity;
+import org.apache.hc.core5.http.HttpStatus;
+import org.junit.jupiter.api.Test;
+
+class HttpClientCancelRequestLiveTest {
+
+ private static final String SAMPLE_URL = "http://www.github.com";
+
+ @Test
+ void whenRequestIsCanceled_thenCorrect() throws IOException {
+ HttpGet request = new HttpGet(SAMPLE_URL);
+ try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
+ httpClient.execute(request, response -> {
+ HttpEntity entity = response.getEntity();
+
+ System.out.println("----------------------------------------");
+ System.out.println(response.getCode());
+ if (entity != null) {
+ System.out.println("Response content length: " + entity.getContentLength());
+ }
+ System.out.println("----------------------------------------");
+ // Do not feel like reading the response body
+ // Call abort on the request object
+ request.abort();
+
+ assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
+ return response;
+ });
+ }
+ }
+}
diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientRedirectLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientRedirectLiveTest.java
index 9a03ab02a57d..04fad843336e 100644
--- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientRedirectLiveTest.java
+++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientRedirectLiveTest.java
@@ -1,98 +1,61 @@
package com.baeldung.httpclient;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpHead;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.DefaultRedirectStrategy;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.impl.client.LaxRedirectStrategy;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.util.Arrays;
-
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.classic.methods.HttpPost;
+import org.apache.hc.client5.http.impl.DefaultRedirectStrategy;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.junit.jupiter.api.Test;
+
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-public class HttpClientRedirectLiveTest {
-
- private CloseableHttpClient instance;
-
- private CloseableHttpResponse response;
-
- @Before
- public final void before() {
- instance = HttpClientBuilder.create().build();
- }
-
- @After
- public final void after() throws IllegalStateException, IOException {
- ResponseUtil.closeResponse(response);
- }
- // tests
-
- @Test
- public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
- instance = HttpClients.custom().disableRedirectHandling().build();
-
- final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw");
- response = instance.execute(httpGet);
+import java.io.IOException;
- assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
- }
+class HttpClientRedirectLiveTest {
@Test
- public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
- instance = HttpClientBuilder.create().disableRedirectHandling().build();
- response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw"));
- assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
- }
+ void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
- // redirect with POST
+ final HttpGet request = new HttpGet("http://t.co/I5YYd9tddw");
- @Test
- public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
- instance = HttpClientBuilder.create().build();
- response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
- assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
+ try (CloseableHttpClient httpClient = HttpClients.custom()
+ .disableRedirectHandling()
+ .build()) {
+ httpClient.execute(request, response -> {
+ assertThat(response.getCode(), equalTo(301));
+ return response;
+ });
+ }
}
@Test
- public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
- final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() {
- /** Redirectable methods. */
- private final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME};
+ void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
- @Override
- protected boolean isRedirectable(final String method) {
- return Arrays.stream(REDIRECT_METHODS)
- .anyMatch(m -> m.equalsIgnoreCase(method));
- }
- }).build();
+ final HttpPost request = new HttpPost("http://t.co/I5YYd9tddw");
- response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ try (CloseableHttpClient httpClient = HttpClientBuilder.create()
+ .build()) {
+ httpClient.execute(request, response -> {
+ assertThat(response.getCode(), equalTo(200));
+ return response;
+ });
+ }
}
@Test
- public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
- final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build();
+ void givenRedirectingPOST_whenUsingDefaultRedirectStrategy_thenRedirected() throws IOException {
- response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
- }
+ final HttpPost request = new HttpPost("http://t.co/I5YYd9tddw");
- @Test
- public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
- instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
- response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ try (CloseableHttpClient httpClient = HttpClientBuilder.create()
+ .setRedirectStrategy(new DefaultRedirectStrategy())
+ .build()) {
+ httpClient.execute(request, response -> {
+ assertThat(response.getCode(), equalTo(200));
+ return response;
+ });
+ }
}
-
}
diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java
index ef12c37412f8..4173909f7deb 100644
--- a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java
+++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java
@@ -1,8 +1,8 @@
package com.baeldung.httpclient.base;
import com.baeldung.httpclient.ResponseUtil;
+
import org.apache.http.Header;
-import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
@@ -10,7 +10,6 @@
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.junit.After;
import org.junit.Before;
@@ -73,30 +72,4 @@ public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCo
assertThat(headers, not(emptyArray()));
}
- // tests - cancel request
-
- @Test
- public final void whenRequestIsCanceled_thenCorrect() throws IOException {
- instance = HttpClients.custom().build();
- final HttpGet request = new HttpGet(SAMPLE_URL);
- response = instance.execute(request);
-
- try {
- final HttpEntity entity = response.getEntity();
-
- System.out.println("----------------------------------------");
- System.out.println(response.getStatusLine());
- if (entity != null) {
- System.out.println("Response content length: " + entity.getContentLength());
- }
- System.out.println("----------------------------------------");
-
- // Do not feel like reading the response body
- // Call abort on the request object
- request.abort();
- } finally {
- response.close();
- }
- }
-
}
diff --git a/apache-httpclient4/README.md b/apache-httpclient4/README.md
index dff63a5cc17f..0bc4ac8e83d6 100644
--- a/apache-httpclient4/README.md
+++ b/apache-httpclient4/README.md
@@ -4,11 +4,14 @@ This module contains articles about Apache HttpClient 4.5
### Relevant Articles
+- [Apache HttpClient – Cancel Request](https://www.baeldung.com/httpclient-cancel-request)
- [Apache HttpClient with SSL](https://www.baeldung.com/httpclient-ssl)
- [Apache HttpClient Timeout](https://www.baeldung.com/httpclient-timeout)
- [Custom HTTP Header with the Apache HttpClient](https://www.baeldung.com/httpclient-custom-http-header)
- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
+- [Retrying Requests using Apache HttpClient](https://www.baeldung.com/java-retrying-requests-using-apache-httpclient)
+- [Apache HttpClient – Follow Redirects for POST](https://www.baeldung.com/httpclient-redirect-on-http-post)
### Running the Tests
To run the live tests, use the command: mvn clean install -Plive
diff --git a/apache-httpclient4/pom.xml b/apache-httpclient4/pom.xml
index 1485c94c8c20..e0bf9dd5f607 100644
--- a/apache-httpclient4/pom.xml
+++ b/apache-httpclient4/pom.xml
@@ -1,7 +1,7 @@
+ 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">
4.0.0
apache-httpclient4
0.1-SNAPSHOT
diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java
new file mode 100644
index 000000000000..dc0055c5ae12
--- /dev/null
+++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java
@@ -0,0 +1,174 @@
+package com.baeldung.httpclient;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+
+import java.io.IOException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+import javax.net.ssl.SSLContext;
+
+import org.apache.http.HttpHost;
+import org.apache.http.HttpResponse;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.conn.ssl.TrustStrategy;
+import org.apache.http.impl.client.BasicCookieStore;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.apache.http.impl.cookie.BasicClientCookie;
+import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
+import org.apache.http.impl.nio.client.HttpAsyncClients;
+import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
+import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
+import org.apache.http.nio.reactor.ConnectingIOReactor;
+import org.apache.http.protocol.BasicHttpContext;
+import org.apache.http.protocol.HttpContext;
+import org.apache.http.ssl.SSLContexts;
+import org.junit.jupiter.api.Test;
+
+class HttpAsyncClientV4LiveTest {
+
+ private static final String HOST = "http://www.google.com";
+ private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
+ private static final String HOST_WITH_PROXY = "http://httpbin.org/";
+ private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";// "http://localhost:8080/spring-security-rest-basic-auth/api/foos/1";
+ private static final String DEFAULT_USER = "test";// "user1";
+ private static final String DEFAULT_PASS = "test";// "user1Pass";
+
+ private static final String HOST_WITH_COOKIE = "http://yuilibrary.com/yui/docs/cookie/cookie-simple-example.html"; // "http://github.com";
+ private static final String COOKIE_DOMAIN = ".yuilibrary.com"; // ".github.com";
+ private static final String COOKIE_NAME = "example"; // "JSESSIONID";
+
+ // tests
+
+ @Test
+ void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
+ final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
+ client.start();
+ final HttpGet request = new HttpGet(HOST);
+
+ final Future future = client.execute(request, null);
+ final HttpResponse response = future.get();
+
+ assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ client.close();
+ }
+
+ @Test
+ void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception {
+ final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
+ final PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
+ final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setConnectionManager(cm).build();
+ client.start();
+ final String[] toGet = { "http://www.google.com/", "http://www.apache.org/", "http://www.bing.com/" };
+
+ final GetThread[] threads = new GetThread[toGet.length];
+ for (int i = 0; i < threads.length; i++) {
+ final HttpGet request = new HttpGet(toGet[i]);
+ threads[i] = new GetThread(client, request);
+ }
+
+ for (final GetThread thread : threads) {
+ thread.start();
+ }
+
+ for (final GetThread thread : threads) {
+ thread.join();
+ }
+
+ }
+
+ @Test
+ void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
+ final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
+ client.start();
+ final HttpHost proxy = new HttpHost("127.0.0.1", 8080);
+ final RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
+ final HttpGet request = new HttpGet(HOST_WITH_PROXY);
+ request.setConfig(config);
+ final Future future = client.execute(request, null);
+ final HttpResponse response = future.get();
+ assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ client.close();
+ }
+
+ @Test
+ void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
+ final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
+ final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
+
+ final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext).build();
+
+ client.start();
+ final HttpGet request = new HttpGet(HOST_WITH_SSL);
+ final Future future = client.execute(request, null);
+ final HttpResponse response = future.get();
+ assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ client.close();
+ }
+
+ @Test
+ void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
+ final BasicCookieStore cookieStore = new BasicCookieStore();
+ final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234");
+ cookie.setDomain(COOKIE_DOMAIN);
+ cookie.setPath("/");
+ cookieStore.addCookie(cookie);
+ final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
+ client.start();
+ final HttpGet request = new HttpGet(HOST_WITH_COOKIE);
+
+ final HttpContext localContext = new BasicHttpContext();
+ localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
+
+ final Future future = client.execute(request, localContext, null);
+ final HttpResponse response = future.get();
+ assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ client.close();
+ }
+
+ @Test
+ void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
+ final CredentialsProvider provider = new BasicCredentialsProvider();
+ final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
+ provider.setCredentials(AuthScope.ANY, creds);
+ final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build();
+
+ final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
+ client.start();
+ final Future future = client.execute(request, null);
+ final HttpResponse response = future.get();
+ assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ client.close();
+ }
+
+ static class GetThread extends Thread {
+
+ private final CloseableHttpAsyncClient client;
+ private final HttpContext context;
+ private final HttpGet request;
+
+ GetThread(final CloseableHttpAsyncClient client, final HttpGet request) {
+ this.client = client;
+ context = HttpClientContext.create();
+ this.request = request;
+ }
+
+ @Override
+ public void run() {
+ try {
+ final Future future = client.execute(request, context, null);
+ final HttpResponse response = future.get();
+ assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ } catch (final Exception ex) {
+ System.out.println(ex.getLocalizedMessage());
+ }
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java
new file mode 100644
index 000000000000..226a7b8cf7da
--- /dev/null
+++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java
@@ -0,0 +1,57 @@
+package com.baeldung.httpclient;
+
+import java.io.IOException;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.client.HttpClients;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class HttpClientCancelRequestV4LiveTest {
+
+ private static final String SAMPLE_URL = "http://www.github.com";
+
+ private CloseableHttpClient instance;
+
+ private CloseableHttpResponse response;
+
+ @Before
+ public final void before() {
+ instance = HttpClientBuilder.create().build();
+ }
+
+ @After
+ public final void after() throws IllegalStateException, IOException {
+ ResponseUtil.closeResponse(response);
+ }
+
+ @Test
+ public final void whenRequestIsCanceled_thenCorrect() throws IOException {
+ instance = HttpClients.custom().build();
+ final HttpGet request = new HttpGet(SAMPLE_URL);
+ response = instance.execute(request);
+
+ try {
+ final HttpEntity entity = response.getEntity();
+
+ System.out.println("----------------------------------------");
+ System.out.println(response.getStatusLine());
+ if (entity != null) {
+ System.out.println("Response content length: " + entity.getContentLength());
+ }
+ System.out.println("----------------------------------------");
+
+ // Do not feel like reading the response body
+ // Call abort on the request object
+ request.abort();
+ } finally {
+ response.close();
+ }
+ }
+}
diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientRedirectV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientRedirectV4LiveTest.java
new file mode 100644
index 000000000000..f6d65a8d8f34
--- /dev/null
+++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientRedirectV4LiveTest.java
@@ -0,0 +1,70 @@
+package com.baeldung.httpclient;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+
+import java.io.IOException;
+
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.impl.client.LaxRedirectStrategy;
+
+class HttpClientRedirectV4LiveTest {
+ private CloseableHttpClient instance;
+
+ private CloseableHttpResponse response;
+
+ @BeforeEach
+ public final void before() {
+ instance = HttpClientBuilder.create()
+ .build();
+ }
+
+ @AfterEach
+ public final void after() throws IllegalStateException, IOException {
+ ResponseUtil.closeResponse(response);
+ }
+
+ @Test
+ void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
+ instance = HttpClients.custom()
+ .disableRedirectHandling()
+ .build();
+
+ final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw");
+ response = instance.execute(httpGet);
+
+ assertThat(response.getStatusLine()
+ .getStatusCode(), equalTo(301));
+ }
+
+ // redirect with POST
+
+ @Test
+ void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
+ instance = HttpClientBuilder.create()
+ .build();
+ response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
+ assertThat(response.getStatusLine()
+ .getStatusCode(), equalTo(301));
+ }
+
+ @Test
+ void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
+ instance = HttpClientBuilder.create()
+ .setRedirectStrategy(new LaxRedirectStrategy())
+ .build();
+ response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
+ assertThat(response.getStatusLine()
+ .getStatusCode(), equalTo(200));
+ }
+
+}
\ No newline at end of file
diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryIntegrationTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java
similarity index 99%
rename from apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryIntegrationTest.java
rename to apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java
index cfb51f058aa3..3a8ff252c275 100644
--- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryIntegrationTest.java
+++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java
@@ -24,7 +24,7 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-public class ApacheHttpClientRetryIntegrationTest {
+public class ApacheHttpClientRetryLiveTest {
private Integer requestCounter;
private CloseableHttpClient httpClient;
diff --git a/apache-kafka-2/README.md b/apache-kafka-2/README.md
index ec9e8e2adc14..157078f023ae 100644
--- a/apache-kafka-2/README.md
+++ b/apache-kafka-2/README.md
@@ -7,3 +7,4 @@ You can build the project from the command line using: *mvn clean install*, or i
### Relevant Articles:
- [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running)
+- [Add Custom Headers to a Kafka Message](https://www.baeldung.com/java-kafka-custom-headers)
diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/headers/KafkaMessageHeaders.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/headers/KafkaMessageHeaders.java
new file mode 100644
index 000000000000..2c8c14bfc58d
--- /dev/null
+++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/headers/KafkaMessageHeaders.java
@@ -0,0 +1,88 @@
+package com.baeldung.kafka.headers;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.header.Header;
+import org.apache.kafka.common.header.Headers;
+import org.apache.kafka.common.header.internals.RecordHeader;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class KafkaMessageHeaders {
+
+ private static Logger logger = LoggerFactory.getLogger(KafkaMessageHeaders.class);
+
+ private static String TOPIC = "baeldung";
+ private static String MESSAGE_KEY = "message";
+ private static String MESSAGE_VALUE = "Hello World";
+ private static String HEADER_KEY = "website";
+ private static String HEADER_VALUE = "baeldung.com";
+
+ private static KafkaProducer producer;
+ private static KafkaConsumer consumer;
+
+ public static void main(String[] args) {
+ setup();
+
+ publishMessageWithCustomHeaders();
+
+ consumeMessageWithCustomHeaders();
+ }
+
+ private static void consumeMessageWithCustomHeaders() {
+ consumer.subscribe(Arrays.asList(TOPIC));
+
+ ConsumerRecords records = consumer.poll(Duration.ofMinutes(1));
+ for (ConsumerRecord record : records) {
+ logger.info(record.key());
+ logger.info(record.value());
+
+ Headers headers = record.headers();
+ for (Header header : headers) {
+ logger.info(header.key());
+ logger.info(new String(header.value()));
+ }
+ }
+ }
+
+ private static void publishMessageWithCustomHeaders() {
+ List headers = new ArrayList<>();
+ headers.add(new RecordHeader(HEADER_KEY, HEADER_VALUE.getBytes()));
+
+ ProducerRecord record1 = new ProducerRecord<>(TOPIC, null, MESSAGE_KEY, MESSAGE_VALUE, headers);
+ producer.send(record1);
+
+ ProducerRecord record2 = new ProducerRecord<>(TOPIC, null, System.currentTimeMillis(), MESSAGE_KEY, MESSAGE_VALUE, headers);
+ producer.send(record2);
+ }
+
+ private static void setup() {
+ Properties producerProperties = new Properties();
+ producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
+ producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
+ producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
+
+ Properties consumerProperties = new Properties();
+ consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
+ consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+ consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+ consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
+
+ producer = new KafkaProducer<>(producerProperties);
+ consumer = new KafkaConsumer<>(consumerProperties);
+ }
+
+}
diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessages.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessages.java
new file mode 100644
index 000000000000..94f5907525d0
--- /dev/null
+++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessages.java
@@ -0,0 +1,138 @@
+package com.baeldung.kafka;
+
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.testcontainers.containers.KafkaContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.ExecutionException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+@Testcontainers
+public class KafaConsumeLastNMessages {
+
+ private static String TOPIC1 = "baeldung-github";
+ private static String TOPIC2 = "baeldung-blog";
+ private static String MESSAGE_KEY = "message";
+ private static KafkaProducer producer;
+ private static KafkaConsumer consumer;
+ private static KafkaProducer transactionalProducer;
+
+ @Container
+ private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
+
+ @BeforeAll
+ static void setup() {
+ KAFKA_CONTAINER.addExposedPort(9092);
+
+ Properties producerProperties = new Properties();
+ producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
+ producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
+ producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
+
+ Properties consumerProperties = new Properties();
+ consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
+ consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+ consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+ consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
+
+ Properties transactionalProducerProprieties = new Properties();
+ transactionalProducerProprieties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
+ transactionalProducerProprieties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
+ transactionalProducerProprieties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
+ transactionalProducerProprieties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true");
+ transactionalProducerProprieties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "prod-0");
+
+ producer = new KafkaProducer<>(producerProperties);
+ consumer = new KafkaConsumer<>(consumerProperties);
+ transactionalProducer = new KafkaProducer<>(transactionalProducerProprieties);
+ }
+
+ @AfterAll
+ static void destroy() {
+ KAFKA_CONTAINER.stop();
+ }
+
+ @Test
+ void whenSeekingKafkaTopicCursorToEnd_consumerRetrievesOnlyDesiredNumberOfMessages() throws ExecutionException, InterruptedException {
+ int messagesInTopic = 100;
+ int messagesToRetrieve = 20;
+
+ for (int i = 0; i < messagesInTopic; i++) {
+ producer.send(new ProducerRecord<>(TOPIC1, null, MESSAGE_KEY, String.valueOf(i)))
+ .get();
+ }
+
+ TopicPartition partition = new TopicPartition(TOPIC1, 0);
+ List partitions = new ArrayList<>();
+ partitions.add(partition);
+ consumer.assign(partitions);
+
+ consumer.seekToEnd(partitions);
+ long startIndex = consumer.position(partition) - messagesToRetrieve;
+ consumer.seek(partition, startIndex);
+
+ ConsumerRecords records = consumer.poll(Duration.ofMinutes(1));
+ int recordsReceived = 0;
+ for (ConsumerRecord record : records) {
+ assertEquals(MESSAGE_KEY, record.key());
+ assertTrue(Integer.parseInt(record.value()) >= (messagesInTopic - messagesToRetrieve));
+ recordsReceived++;
+ }
+
+ assertEquals(messagesToRetrieve, recordsReceived);
+ }
+
+ @Test
+ void havingTransactionalProducer_whenSeekingKafkaTopicCursorToEnd_consumerRetrievesLessMessages() throws ExecutionException, InterruptedException {
+ int messagesInTopic = 100;
+ int messagesToRetrieve = 20;
+
+ transactionalProducer.initTransactions();
+ for (int i = 0; i < messagesInTopic; i++) {
+ transactionalProducer.beginTransaction();
+ transactionalProducer.send(new ProducerRecord<>(TOPIC2, null, MESSAGE_KEY, String.valueOf(i)))
+ .get();
+ transactionalProducer.commitTransaction();
+ }
+
+ TopicPartition partition = new TopicPartition(TOPIC2, 0);
+ List partitions = new ArrayList<>();
+ partitions.add(partition);
+ consumer.assign(partitions);
+
+ consumer.seekToEnd(partitions);
+ long startIndex = consumer.position(partition) - messagesToRetrieve;
+ consumer.seek(partition, startIndex);
+
+ ConsumerRecords records = consumer.poll(Duration.ofMinutes(1));
+ int recordsReceived = 0;
+ for (ConsumerRecord record : records) {
+ assertEquals(MESSAGE_KEY, record.key());
+ assertTrue(Integer.parseInt(record.value()) >= (messagesInTopic - messagesToRetrieve));
+ recordsReceived++;
+ }
+
+ assertTrue(messagesToRetrieve > recordsReceived);
+ }
+
+}
diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/headers/KafkaMessageHeadersLiveTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/headers/KafkaMessageHeadersLiveTest.java
new file mode 100644
index 000000000000..42cc572e07d5
--- /dev/null
+++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/headers/KafkaMessageHeadersLiveTest.java
@@ -0,0 +1,104 @@
+package com.baeldung.kafka.headers;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.clients.producer.RecordMetadata;
+import org.apache.kafka.common.header.Header;
+import org.apache.kafka.common.header.Headers;
+import org.apache.kafka.common.header.internals.RecordHeader;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.testcontainers.containers.KafkaContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+// This live test needs a Docker Daemon running so that a kafka container can be created
+
+@Testcontainers
+public class KafkaMessageHeadersLiveTest {
+
+ private static String TOPIC = "baeldung";
+ private static String MESSAGE_KEY = "message";
+ private static String MESSAGE_VALUE = "Hello World";
+ private static String HEADER_KEY = "website";
+ private static String HEADER_VALUE = "baeldung.com";
+
+ private static KafkaProducer producer;
+ private static KafkaConsumer consumer;
+
+ @Container
+ private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
+
+ @BeforeAll
+ static void setup() {
+ KAFKA_CONTAINER.addExposedPort(9092);
+
+ Properties producerProperties = new Properties();
+ producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
+ producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
+ producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
+
+ Properties consumerProperties = new Properties();
+ consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
+ consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+ consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+ consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
+
+ producer = new KafkaProducer<>(producerProperties);
+ consumer = new KafkaConsumer<>(consumerProperties);
+ }
+
+ @AfterAll
+ static void destroy() {
+ KAFKA_CONTAINER.stop();
+ }
+
+ @Test
+ void givenAMessageWithCustomHeaders_whenPublishedToKafkaAndConsumed_thenCheckForCustomHeaders() throws ExecutionException, InterruptedException {
+ List headers = new ArrayList<>();
+ headers.add(new RecordHeader(HEADER_KEY, HEADER_VALUE.getBytes()));
+
+ ProducerRecord record1 = new ProducerRecord<>(TOPIC, null, MESSAGE_KEY, MESSAGE_VALUE, headers);
+ Future future = producer.send(record1);
+
+ RecordMetadata metadata = future.get();
+
+ assertNotNull(metadata);
+
+ consumer.subscribe(Arrays.asList(TOPIC));
+
+ ConsumerRecords records = consumer.poll(Duration.ofMinutes(1));
+ for (ConsumerRecord record : records) {
+ assertEquals(MESSAGE_KEY, record.key());
+ assertEquals(MESSAGE_VALUE, record.value());
+
+ Headers consumedHeaders = record.headers();
+ assertNotNull(consumedHeaders);
+
+ for (Header header : consumedHeaders) {
+ assertEquals(HEADER_KEY, header.key());
+ assertEquals(HEADER_VALUE, new String(header.value()));
+ }
+ }
+ }
+}
diff --git a/apache-kafka/pom.xml b/apache-kafka/pom.xml
index 915583fed87e..494bc949619b 100644
--- a/apache-kafka/pom.xml
+++ b/apache-kafka/pom.xml
@@ -171,7 +171,8 @@
--add-opens java.base/java.time=ALL-UNNAMED
- --add-opens java.base/java.nio=ALL-UNNAMED
+ --add-opens
+ java.base/java.nio=ALL-UNNAMED
--add-opens java.base/java.util=ALL-UNNAMED
@@ -179,8 +180,6 @@
-
-
3.4.0
1.15.3
diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml
index 546eedec5b90..78781cf21522 100644
--- a/apache-poi/pom.xml
+++ b/apache-poi/pom.xml
@@ -30,6 +30,16 @@
+
+ org.dhatim
+ fastexcel
+ ${fastexcel.version}
+
+
+ org.dhatim
+ fastexcel-reader
+ ${fastexcel.version}
+
@@ -52,6 +62,7 @@
5.2.0
1.0.6
+ 0.15.3
3.2.0
diff --git a/apache-poi/src/main/java/com/baeldung/fastexcel/FastexcelHelper.java b/apache-poi/src/main/java/com/baeldung/fastexcel/FastexcelHelper.java
new file mode 100644
index 000000000000..9d6041b66e74
--- /dev/null
+++ b/apache-poi/src/main/java/com/baeldung/fastexcel/FastexcelHelper.java
@@ -0,0 +1,63 @@
+package com.baeldung.fastexcel;
+
+import org.dhatim.fastexcel.Workbook;
+import org.dhatim.fastexcel.Worksheet;
+import org.dhatim.fastexcel.reader.Cell;
+import org.dhatim.fastexcel.reader.ReadableWorkbook;
+import org.dhatim.fastexcel.reader.Row;
+import org.dhatim.fastexcel.reader.Sheet;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+
+public class FastexcelHelper {
+
+ public Map> readExcel(String fileLocation) throws IOException {
+ Map> data = new HashMap<>();
+
+ try (FileInputStream file = new FileInputStream(fileLocation); ReadableWorkbook wb = new ReadableWorkbook(file)) {
+ Sheet sheet = wb.getFirstSheet();
+ try (Stream rows = sheet.openStream()) {
+ rows.forEach(r -> {
+ data.put(r.getRowNum(), new ArrayList<>());
+
+ for (Cell cell : r) {
+ data.get(r.getRowNum()).add(cell.getRawValue());
+ }
+ });
+ }
+ }
+
+ return data;
+ }
+
+ public void writeExcel() throws IOException {
+ File currDir = new File(".");
+ String path = currDir.getAbsolutePath();
+ String fileLocation = path.substring(0, path.length() - 1) + "fastexcel.xlsx";
+
+ try (OutputStream os = Files.newOutputStream(Paths.get(fileLocation)); Workbook wb = new Workbook(os, "MyApplication", "1.0")) {
+ Worksheet ws = wb.newWorksheet("Sheet 1");
+
+ ws.width(0, 25);
+ ws.width(1, 15);
+
+ ws.range(0, 0, 0, 1).style().fontName("Arial").fontSize(16).bold().fillColor("3366FF").set();
+ ws.value(0, 0, "Name");
+ ws.value(0, 1, "Age");
+
+ ws.range(2, 0, 2, 1).style().wrapText(true).set();
+ ws.value(2, 0, "John Smith");
+ ws.value(2, 1, 20L);
+ }
+ }
+}
diff --git a/apache-poi/src/test/java/com/baeldung/fastexcel/FastexcelIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/fastexcel/FastexcelIntegrationTest.java
new file mode 100644
index 000000000000..a36c06e41f6a
--- /dev/null
+++ b/apache-poi/src/test/java/com/baeldung/fastexcel/FastexcelIntegrationTest.java
@@ -0,0 +1,49 @@
+package com.baeldung.fastexcel;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+
+public class FastexcelIntegrationTest {
+
+ private FastexcelHelper fastexcelHelper;
+ private static String FILE_NAME = "fastexcel.xlsx";
+ private String fileLocation;
+
+ @Before
+ public void generateExcelFile() throws IOException {
+
+ File currDir = new File(".");
+ String path = currDir.getAbsolutePath();
+ fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
+
+ fastexcelHelper = new FastexcelHelper();
+ fastexcelHelper.writeExcel();
+ }
+
+ @Test
+ public void whenParsingExcelFile_thenCorrect() throws IOException {
+ Map> data = fastexcelHelper.readExcel(fileLocation);
+
+ assertEquals("Name", data.get(1).get(0));
+ assertEquals("Age", data.get(1).get(1));
+
+ assertEquals("John Smith", data.get(3).get(0));
+ assertEquals("20", data.get(3).get(1));
+ }
+
+ @After
+ public void cleanup() {
+ File testFile = new File(fileLocation);
+ if (testFile.exists()) {
+ testFile.delete();
+ }
+ }
+}
diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml
index 9e61e1340d16..fbb6e9ba5eba 100644
--- a/apache-spark/pom.xml
+++ b/apache-spark/pom.xml
@@ -7,7 +7,6 @@
1.0-SNAPSHOT
apache-spark
jar
- http://maven.apache.org
com.baeldung
@@ -18,17 +17,17 @@
org.apache.spark
- spark-core_2.11
+ spark-core_2.12
${org.apache.spark.spark-core.version}
org.apache.spark
- spark-sql_2.11
+ spark-sql_2.12
${org.apache.spark.spark-sql.version}
org.apache.spark
- spark-graphx_2.11
+ spark-graphx_2.12
${org.apache.spark.spark-graphx.version}
@@ -38,22 +37,22 @@
org.apache.spark
- spark-streaming_2.11
+ spark-streaming_2.12
${org.apache.spark.spark-streaming.version}
org.apache.spark
- spark-mllib_2.11
+ spark-mllib_2.12
${org.apache.spark.spark-mllib.version}
org.apache.spark
- spark-streaming-kafka-0-10_2.11
+ spark-streaming-kafka-0-10_2.12
${org.apache.spark.spark-streaming-kafka.version}
com.datastax.spark
- spark-cassandra-connector_2.11
+ spark-cassandra-connector_2.12
${com.datastax.spark.spark-cassandra-connector.version}
@@ -98,17 +97,17 @@
- 2.4.8
- 2.4.8
- 2.4.8
- 2.4.8
- 2.4.8
+ 3.3.2
+ 3.3.2
+ 3.3.2
+ 3.3.2
+ 3.3.2
0.8.1-spark3.0-s_2.12
- 2.4.8
- 2.5.2
+ 3.3.2
+ 3.3.0
1.6.0-M1
3.3.0
- 42.3.3
+ 42.5.4
\ No newline at end of file
diff --git a/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java
index efbe5f385167..15f70aae61a7 100644
--- a/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java
+++ b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java
@@ -16,8 +16,11 @@
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
+import org.apache.spark.api.java.Optional;
import org.apache.spark.api.java.function.Function2;
+import org.apache.spark.api.java.function.Function3;
import org.apache.spark.streaming.Durations;
+import org.apache.spark.streaming.State;
import org.apache.spark.streaming.StateSpec;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaInputDStream;
@@ -74,7 +77,8 @@ public static void main(String[] args) throws InterruptedException {
JavaPairDStream wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
.reduceByKey((Function2) (i1, i2) -> i1 + i2);
- JavaMapWithStateDStream> cumulativeWordCounts = wordCounts.mapWithState(StateSpec.function((word, one, state) -> {
+ JavaMapWithStateDStream> cumulativeWordCounts =
+ wordCounts.mapWithState(StateSpec.function((Function3, State, Tuple2>) (word, one, state) -> {
int sum = one.orElse(0) + (state.exists() ? state.get() : 0);
Tuple2 output = new Tuple2<>(word, sum);
state.update(sum);
diff --git a/apache-spark/src/main/java/com/baeldung/dataframes/SparkDriver.java b/apache-spark/src/main/java/com/baeldung/dataframes/SparkDriver.java
index adc25170a72c..e5e988b5a8e4 100644
--- a/apache-spark/src/main/java/com/baeldung/dataframes/SparkDriver.java
+++ b/apache-spark/src/main/java/com/baeldung/dataframes/SparkDriver.java
@@ -9,6 +9,7 @@ public class SparkDriver implements Serializable {
public static SparkSession getSparkSession() {
return SparkSession.builder()
.appName("Customer Aggregation pipeline")
+ .config("spark.sql.legacy.timeParserPolicy", "LEGACY")
.master("local")
.getOrCreate();
diff --git a/aws-modules/aws-lambda/.gitignore b/aws-modules/aws-lambda-modules/.gitignore
similarity index 100%
rename from aws-modules/aws-lambda/.gitignore
rename to aws-modules/aws-lambda-modules/.gitignore
diff --git a/aws-modules/aws-lambda/README.md b/aws-modules/aws-lambda-modules/README.md
similarity index 100%
rename from aws-modules/aws-lambda/README.md
rename to aws-modules/aws-lambda-modules/README.md
diff --git a/aws-modules/aws-lambda/lambda/pom.xml b/aws-modules/aws-lambda-modules/lambda-function/pom.xml
similarity index 96%
rename from aws-modules/aws-lambda/lambda/pom.xml
rename to aws-modules/aws-lambda-modules/lambda-function/pom.xml
index 8e47bab4be95..9fff7d1d9acb 100644
--- a/aws-modules/aws-lambda/lambda/pom.xml
+++ b/aws-modules/aws-lambda-modules/lambda-function/pom.xml
@@ -3,14 +3,14 @@
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">
4.0.0
- lambda
+ lambda-function
0.1.0-SNAPSHOT
- lambda
+ lambda-function
jar
com.baeldung
- aws-lambda
+ aws-lambda-modules
1.0.0-SNAPSHOT
diff --git a/aws-modules/aws-lambda/lambda/sam-templates/template-implicit.yaml b/aws-modules/aws-lambda-modules/lambda-function/sam-templates/template-implicit.yaml
similarity index 100%
rename from aws-modules/aws-lambda/lambda/sam-templates/template-implicit.yaml
rename to aws-modules/aws-lambda-modules/lambda-function/sam-templates/template-implicit.yaml
diff --git a/aws-modules/aws-lambda/lambda/sam-templates/template-inline-swagger.yaml b/aws-modules/aws-lambda-modules/lambda-function/sam-templates/template-inline-swagger.yaml
similarity index 100%
rename from aws-modules/aws-lambda/lambda/sam-templates/template-inline-swagger.yaml
rename to aws-modules/aws-lambda-modules/lambda-function/sam-templates/template-inline-swagger.yaml
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/apigateway/model/Person.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/apigateway/model/Person.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/resources/logback.xml b/aws-modules/aws-lambda-modules/lambda-function/src/main/resources/logback.xml
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/resources/logback.xml
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/resources/logback.xml
diff --git a/aws-modules/aws-lambda/pom.xml b/aws-modules/aws-lambda-modules/pom.xml
similarity index 67%
rename from aws-modules/aws-lambda/pom.xml
rename to aws-modules/aws-lambda-modules/pom.xml
index bdd295c0076f..9886ff58d299 100644
--- a/aws-modules/aws-lambda/pom.xml
+++ b/aws-modules/aws-lambda-modules/pom.xml
@@ -3,8 +3,8 @@
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">
4.0.0
- aws-lambda
- aws-lambda
+ aws-lambda-modules
+ aws-lambda-modules
pom
@@ -14,9 +14,9 @@
- lambda
- shipping-tracker/ShippingFunction
- todo-reminder/ToDoFunction
+ lambda-function
+ shipping-tracker-lambda/ShippingFunction
+ todo-reminder-lambda/ToDoFunction
\ No newline at end of file
diff --git a/aws-modules/aws-lambda/shipping-tracker/.gitignore b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/.gitignore
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/.gitignore
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/.gitignore
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/pom.xml b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml
similarity index 97%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/pom.xml
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml
index 24f2a76912a2..abd22ea50c13 100644
--- a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/pom.xml
+++ b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml
@@ -2,7 +2,6 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
- com.baeldung
ShippingFunction
1.0
ShippingFunction
@@ -10,7 +9,7 @@
com.baeldung
- aws-lambda
+ aws-lambda-modules
1.0.0-SNAPSHOT
../../
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/App.java b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/App.java
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/App.java
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/App.java
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Checkin.java b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Checkin.java
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Checkin.java
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Checkin.java
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Consignment.java b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Consignment.java
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Consignment.java
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Consignment.java
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Item.java b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Item.java
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Item.java
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Item.java
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingDao.java b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingDao.java
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingDao.java
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingDao.java
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingService.java b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingService.java
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingService.java
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingService.java
diff --git a/aws-modules/aws-lambda/shipping-tracker/template.yaml b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/template.yaml
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/template.yaml
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/template.yaml
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/pom.xml b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml
similarity index 92%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/pom.xml
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml
index 0dd2e4d14a41..04295e1ab127 100644
--- a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/pom.xml
+++ b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml
@@ -1,6 +1,6 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
helloworld
ToDoFunction
@@ -8,6 +8,13 @@
ToDoFunction
jar
+
+ com.baeldung
+ aws-lambda-modules
+ 1.0.0-SNAPSHOT
+ ../../
+
+
com.amazonaws
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/App.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/App.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/App.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/App.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostApi.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostApi.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostApi.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostApi.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostItem.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostItem.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostItem.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostItem.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoApi.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoApi.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoApi.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoApi.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoItem.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoItem.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoItem.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoItem.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Config.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Config.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Config.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Config.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Credentials.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Credentials.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Credentials.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Credentials.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/ExecutionContext.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/ExecutionContext.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/ExecutionContext.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/ExecutionContext.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Services.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Services.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Services.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Services.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/PostService.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/PostService.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/PostService.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/PostService.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/ToDoReaderService.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/ToDoReaderService.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/ToDoReaderService.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/ToDoReaderService.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/resources/configuration.yml b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/resources/configuration.yml
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/resources/configuration.yml
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/resources/configuration.yml
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/resources/log4j2.xml b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/resources/log4j2.xml
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/resources/log4j2.xml
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/resources/log4j2.xml
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/test/java/com/baeldung/lambda/todo/AppTest.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/test/java/com/baeldung/lambda/todo/AppUnitTest.java
similarity index 98%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/test/java/com/baeldung/lambda/todo/AppTest.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/test/java/com/baeldung/lambda/todo/AppUnitTest.java
index cbdc8c22cbec..952a773f6994 100644
--- a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/test/java/com/baeldung/lambda/todo/AppTest.java
+++ b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/test/java/com/baeldung/lambda/todo/AppUnitTest.java
@@ -21,7 +21,7 @@
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
-public class AppTest {
+public class AppUnitTest {
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Context mockContext;
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/test/java/com/baeldung/lambda/todo/service/ToDoReaderServiceTest.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/test/java/com/baeldung/lambda/todo/service/ToDoReaderServiceUnitTest.java
similarity index 94%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/test/java/com/baeldung/lambda/todo/service/ToDoReaderServiceTest.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/test/java/com/baeldung/lambda/todo/service/ToDoReaderServiceUnitTest.java
index 634c5257ffaa..dd5b52d0739e 100644
--- a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/test/java/com/baeldung/lambda/todo/service/ToDoReaderServiceTest.java
+++ b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/test/java/com/baeldung/lambda/todo/service/ToDoReaderServiceUnitTest.java
@@ -7,7 +7,7 @@
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
-public class ToDoReaderServiceTest {
+public class ToDoReaderServiceUnitTest {
@Rule
public SystemOutRule systemOutRule = new SystemOutRule();
diff --git a/aws-modules/aws-lambda/todo-reminder/template.yaml b/aws-modules/aws-lambda-modules/todo-reminder-lambda/template.yaml
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/template.yaml
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/template.yaml
diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml
index 2b07f1153bc3..036e692d24bd 100644
--- a/aws-modules/aws-miscellaneous/pom.xml
+++ b/aws-modules/aws-miscellaneous/pom.xml
@@ -100,20 +100,12 @@
-
-
- dynamodb-local
- DynamoDB Local Release Repository
- ${dynamodblocal.repository.url}
-
-
1.3.0
1.1.0
2.8.0
- 1.11.86
- https://s3-us-west-2.amazonaws.com/dynamodb-local/release
+ 1.21.1
1.10.L001
0.9.4.0006L
3.1.1
diff --git a/aws-modules/aws-s3/README.md b/aws-modules/aws-s3/README.md
index efebf7d933bf..109a8984052d 100644
--- a/aws-modules/aws-s3/README.md
+++ b/aws-modules/aws-s3/README.md
@@ -6,4 +6,5 @@ This module contains articles about Simple Storage Service (S3) on AWS
- [AWS S3 with Java](https://www.baeldung.com/aws-s3-java)
- [Multipart Uploads in Amazon S3 with Java](https://www.baeldung.com/aws-s3-multipart-upload)
-- [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3)
\ No newline at end of file
+- [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3)
+- [Check if a Specified Key Exists in a Given S3 Bucket Using Java](https://www.baeldung.com/java-aws-s3-check-specified-key-exists)
diff --git a/aws-modules/aws-s3/src/main/java/com/baeldung/s3/AWSS3ObjectUtils.java b/aws-modules/aws-s3/src/main/java/com/baeldung/s3/AWSS3ObjectUtils.java
new file mode 100644
index 000000000000..1c31218ff94b
--- /dev/null
+++ b/aws-modules/aws-s3/src/main/java/com/baeldung/s3/AWSS3ObjectUtils.java
@@ -0,0 +1,42 @@
+package com.baeldung.s3;
+
+import org.apache.http.HttpStatus;
+
+import com.amazonaws.AmazonServiceException;
+import com.amazonaws.services.s3.AmazonS3;
+
+public class AWSS3ObjectUtils {
+
+ private AmazonS3 s3Client;
+
+ public AWSS3ObjectUtils(AmazonS3 s3client) {
+ this.s3Client = s3client;
+ }
+
+ public boolean doesObjectExistByDefaultMethod(String bucket, String key) {
+ return s3Client.doesObjectExist(bucket, key);
+ }
+
+ public boolean doesObjectExistByListObjects(String bucket, String key) {
+ return s3Client.listObjects(bucket)
+ .getObjectSummaries()
+ .stream()
+ .filter(s3ObjectSummary -> s3ObjectSummary.getKey()
+ .equals(key))
+ .findFirst()
+ .isPresent();
+ }
+
+ public boolean doesObjectExistByMetaData(String bucket, String key) {
+ try {
+ s3Client.getObjectMetadata(bucket, key);
+ return true;
+ } catch (AmazonServiceException e) {
+ if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
+ return false;
+ } else {
+ throw e;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectManualTest.java b/aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectManualTest.java
new file mode 100644
index 000000000000..02cc22367a7a
--- /dev/null
+++ b/aws-modules/aws-s3/src/test/java/com/baeldung/s3/AWSS3ObjectManualTest.java
@@ -0,0 +1,49 @@
+package com.baeldung.s3;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
+import com.amazonaws.regions.Regions;
+import com.amazonaws.services.s3.AmazonS3;
+import com.amazonaws.services.s3.AmazonS3ClientBuilder;
+
+/**
+ * Required defined environment variables AWS_ACCESS_KEY_ID & AWS_ACCESS_KEY to access S3.
+ * Required S3 bucket and key that exist.
+ */
+
+public class AWSS3ObjectManualTest {
+
+ private static final String BUCKET = "your-bucket";
+ private static final String KEY_THAT_EXIST = "your-key-that-exist";
+ private AWSS3ObjectUtils s3ObjectUtils;
+
+ @Before
+ public void setUp() {
+ AmazonS3 client = AmazonS3ClientBuilder.standard()
+ .withRegion(Regions.DEFAULT_REGION)
+ .withCredentials(new EnvironmentVariableCredentialsProvider())
+ .build();
+
+ s3ObjectUtils = new AWSS3ObjectUtils(client);
+ }
+
+ @Test
+ public void whenVerifyIfObjectExistByDefaultMethod_thenCorrect() {
+ assertTrue(s3ObjectUtils.doesObjectExistByDefaultMethod(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
+
+ }
+
+ @Test
+ public void whenVerifyIfObjectExistByListObjects_thenCorrect() {
+ assertTrue(s3ObjectUtils.doesObjectExistByListObjects(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
+ }
+
+ @Test
+ public void whenVerifyIfObjectExistByMetaData_thenCorrect() {
+ assertTrue(s3ObjectUtils.doesObjectExistByMetaData(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
+ }
+}
diff --git a/aws-modules/pom.xml b/aws-modules/pom.xml
index 72c5017c32ad..02473815b5be 100644
--- a/aws-modules/pom.xml
+++ b/aws-modules/pom.xml
@@ -15,7 +15,7 @@
aws-app-sync
- aws-lambda
+ aws-lambda-modules
aws-miscellaneous
aws-reactive
aws-s3
diff --git a/axon/pom.xml b/axon/pom.xml
index 5c8f1d7a6c26..5eed742aab63 100644
--- a/axon/pom.xml
+++ b/axon/pom.xml
@@ -103,7 +103,8 @@
--add-opens java.base/java.util=ALL-UNNAMED
- --add-opens java.base/java.util.concurrent=ALL-UNNAMED
+ --add-opens
+ java.base/java.util.concurrent=ALL-UNNAMED
diff --git a/checker-plugin/README.md b/checker-framework/README.md
similarity index 100%
rename from checker-plugin/README.md
rename to checker-framework/README.md
diff --git a/checker-plugin/pom.xml b/checker-framework/pom.xml
similarity index 97%
rename from checker-plugin/pom.xml
rename to checker-framework/pom.xml
index 28958db89d52..a348745343c5 100644
--- a/checker-plugin/pom.xml
+++ b/checker-framework/pom.xml
@@ -3,11 +3,10 @@
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
- checker-plugin
+ checker-framework
1.0-SNAPSHOT
- checker-plugin
+ checker-framework
jar
- http://maven.apache.org
com.baeldung
diff --git a/checker-plugin/src/main/java/com/baeldung/typechecker/FakeNumExample.java b/checker-framework/src/main/java/com/baeldung/typechecker/FakeNumExample.java
similarity index 100%
rename from checker-plugin/src/main/java/com/baeldung/typechecker/FakeNumExample.java
rename to checker-framework/src/main/java/com/baeldung/typechecker/FakeNumExample.java
diff --git a/checker-plugin/src/main/java/com/baeldung/typechecker/FormatExample.java b/checker-framework/src/main/java/com/baeldung/typechecker/FormatExample.java
similarity index 100%
rename from checker-plugin/src/main/java/com/baeldung/typechecker/FormatExample.java
rename to checker-framework/src/main/java/com/baeldung/typechecker/FormatExample.java
diff --git a/checker-plugin/src/main/java/com/baeldung/typechecker/KeyForExample.java b/checker-framework/src/main/java/com/baeldung/typechecker/KeyForExample.java
similarity index 100%
rename from checker-plugin/src/main/java/com/baeldung/typechecker/KeyForExample.java
rename to checker-framework/src/main/java/com/baeldung/typechecker/KeyForExample.java
diff --git a/checker-plugin/src/main/java/com/baeldung/typechecker/MonotonicNotNullExample.java b/checker-framework/src/main/java/com/baeldung/typechecker/MonotonicNotNullExample.java
similarity index 100%
rename from checker-plugin/src/main/java/com/baeldung/typechecker/MonotonicNotNullExample.java
rename to checker-framework/src/main/java/com/baeldung/typechecker/MonotonicNotNullExample.java
diff --git a/checker-plugin/src/main/java/com/baeldung/typechecker/NonNullExample.java b/checker-framework/src/main/java/com/baeldung/typechecker/NonNullExample.java
similarity index 100%
rename from checker-plugin/src/main/java/com/baeldung/typechecker/NonNullExample.java
rename to checker-framework/src/main/java/com/baeldung/typechecker/NonNullExample.java
diff --git a/checker-plugin/src/main/java/com/baeldung/typechecker/RegexExample.java b/checker-framework/src/main/java/com/baeldung/typechecker/RegexExample.java
similarity index 100%
rename from checker-plugin/src/main/java/com/baeldung/typechecker/RegexExample.java
rename to checker-framework/src/main/java/com/baeldung/typechecker/RegexExample.java
diff --git a/checker-plugin/src/main/resources/logback.xml b/checker-framework/src/main/resources/logback.xml
similarity index 100%
rename from checker-plugin/src/main/resources/logback.xml
rename to checker-framework/src/main/resources/logback.xml
diff --git a/clojure/ring/.gitignore b/clojure-modules/clojure-ring/.gitignore
similarity index 100%
rename from clojure/ring/.gitignore
rename to clojure-modules/clojure-ring/.gitignore
diff --git a/clojure/ring/README.md b/clojure-modules/clojure-ring/README.md
similarity index 100%
rename from clojure/ring/README.md
rename to clojure-modules/clojure-ring/README.md
diff --git a/clojure/ring/project.clj b/clojure-modules/clojure-ring/project.clj
similarity index 100%
rename from clojure/ring/project.clj
rename to clojure-modules/clojure-ring/project.clj
diff --git a/clojure/ring/src/ring/core.clj b/clojure-modules/clojure-ring/src/ring/core.clj
similarity index 100%
rename from clojure/ring/src/ring/core.clj
rename to clojure-modules/clojure-ring/src/ring/core.clj
diff --git a/core-groovy-modules/core-groovy-2/pom.xml b/core-groovy-modules/core-groovy-2/pom.xml
index ca6a9a62c7c4..de750daf0fc4 100644
--- a/core-groovy-modules/core-groovy-2/pom.xml
+++ b/core-groovy-modules/core-groovy-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-groovy-2
- 1.0-SNAPSHOT
core-groovy-2
jar
@@ -153,14 +152,6 @@
-
-
- maven_central
- Maven Central
- https://repo.maven.apache.org/maven2/
-
-
-
1.1.3
3.4.2
diff --git a/core-groovy-modules/core-groovy-collections/pom.xml b/core-groovy-modules/core-groovy-collections/pom.xml
index 6d43ce7d18cf..08589f54e326 100644
--- a/core-groovy-modules/core-groovy-collections/pom.xml
+++ b/core-groovy-modules/core-groovy-collections/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-groovy-collections
- 1.0-SNAPSHOT
core-groovy-collections
jar
@@ -111,13 +110,4 @@
-
-
- maven_central
- Maven Central
- https://repo.maven.apache.org/maven2/
-
-
-
-
diff --git a/core-groovy-modules/core-groovy-strings/pom.xml b/core-groovy-modules/core-groovy-strings/pom.xml
index fac0f2521936..ac68849431a4 100644
--- a/core-groovy-modules/core-groovy-strings/pom.xml
+++ b/core-groovy-modules/core-groovy-strings/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-groovy-strings
- 1.0-SNAPSHOT
core-groovy-strings
jar
@@ -101,12 +100,4 @@
-
-
- maven_central
- Maven Central
- https://repo.maven.apache.org/maven2/
-
-
-
diff --git a/core-groovy-modules/core-groovy/pom.xml b/core-groovy-modules/core-groovy/pom.xml
index cf6cca9e1838..6668f6223561 100644
--- a/core-groovy-modules/core-groovy/pom.xml
+++ b/core-groovy-modules/core-groovy/pom.xml
@@ -3,9 +3,7 @@
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">
4.0.0
-
core-groovy
- 1.0-SNAPSHOT
core-groovy
jar
@@ -102,12 +100,4 @@
-
-
- maven_central
- Maven Central
- https://repo.maven.apache.org/maven2/
-
-
-
diff --git a/core-java-modules/core-java-10/pom.xml b/core-java-modules/core-java-10/pom.xml
index e2ac8db91922..7eccb098a0f8 100644
--- a/core-java-modules/core-java-10/pom.xml
+++ b/core-java-modules/core-java-10/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-10
- 0.1.0-SNAPSHOT
core-java-10
jar
diff --git a/core-java-modules/core-java-11-2/pom.xml b/core-java-modules/core-java-11-2/pom.xml
index 64a486b5c4da..464781404868 100644
--- a/core-java-modules/core-java-11-2/pom.xml
+++ b/core-java-modules/core-java-11-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-11-2
- 0.1.0-SNAPSHOT
core-java-11-2
jar
diff --git a/core-java-modules/core-java-11-3/pom.xml b/core-java-modules/core-java-11-3/pom.xml
index ccccae5ba11e..22db9e62ab1c 100644
--- a/core-java-modules/core-java-11-3/pom.xml
+++ b/core-java-modules/core-java-11-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-11-3
- 0.1.0-SNAPSHOT
core-java-11-3
jar
@@ -14,7 +13,7 @@
1.0.0-SNAPSHOT
../../pom.xml
-
+
com.google.code.gson
diff --git a/core-java-modules/core-java-11/pom.xml b/core-java-modules/core-java-11/pom.xml
index 28a218c4002a..d0c2c0acaa40 100644
--- a/core-java-modules/core-java-11/pom.xml
+++ b/core-java-modules/core-java-11/pom.xml
@@ -4,10 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-11
- 0.1.0-SNAPSHOT
core-java-11
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-12/pom.xml b/core-java-modules/core-java-12/pom.xml
index 9f95b1bc3f0e..ba6dfc62bc92 100644
--- a/core-java-modules/core-java-12/pom.xml
+++ b/core-java-modules/core-java-12/pom.xml
@@ -4,10 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-12
- 0.1.0-SNAPSHOT
core-java-12
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-13/pom.xml b/core-java-modules/core-java-13/pom.xml
index 9e4283897132..11d6ee7007f4 100644
--- a/core-java-modules/core-java-13/pom.xml
+++ b/core-java-modules/core-java-13/pom.xml
@@ -3,12 +3,9 @@
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">
4.0.0
- com.baeldung
core-java-13
- 0.1.0-SNAPSHOT
core-java-13
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-14/pom.xml b/core-java-modules/core-java-14/pom.xml
index f78edd622a7e..9f48c0b8b259 100644
--- a/core-java-modules/core-java-14/pom.xml
+++ b/core-java-modules/core-java-14/pom.xml
@@ -6,7 +6,6 @@
core-java-14
core-java-14
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-15/pom.xml b/core-java-modules/core-java-15/pom.xml
index a4923054acb2..059e2cc8f3be 100644
--- a/core-java-modules/core-java-15/pom.xml
+++ b/core-java-modules/core-java-15/pom.xml
@@ -6,7 +6,6 @@
core-java-15
core-java-15
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-16/pom.xml b/core-java-modules/core-java-16/pom.xml
index a2c0d4855b82..f8d287880a23 100644
--- a/core-java-modules/core-java-16/pom.xml
+++ b/core-java-modules/core-java-16/pom.xml
@@ -4,10 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-16
- 0.1.0-SNAPSHOT
core-java-16
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-17/pom.xml b/core-java-modules/core-java-17/pom.xml
index bc949d90504d..e2d854be44cb 100644
--- a/core-java-modules/core-java-17/pom.xml
+++ b/core-java-modules/core-java-17/pom.xml
@@ -4,10 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-17
- 0.1.0-SNAPSHOT
core-java-17
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-19/README.md b/core-java-modules/core-java-19/README.md
index 6a9c6c7fdd3c..68244d9f91e8 100644
--- a/core-java-modules/core-java-19/README.md
+++ b/core-java-modules/core-java-19/README.md
@@ -1,3 +1,4 @@
## Relevant Articles
- [Record Patterns in Java 19](https://www.baeldung.com/java-19-record-patterns)
- [Structured Concurrency in Java 19](https://www.baeldung.com/java-structured-concurrency)
+- [Possible Root Causes for High CPU Usage in Java](https://www.baeldung.com/java-high-cpu-usage-causes)
diff --git a/core-java-modules/core-java-19/pom.xml b/core-java-modules/core-java-19/pom.xml
index 096b13e67991..930b37391c6f 100644
--- a/core-java-modules/core-java-19/pom.xml
+++ b/core-java-modules/core-java-19/pom.xml
@@ -1,21 +1,17 @@
+ 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">
4.0.0
+ core-java-19
+ core-java-19
+
com.baeldung.core-java-modules
core-java-modules
0.0.1-SNAPSHOT
- core-java-19
-
-
- 19
- 19
- UTF-8
-
@@ -30,4 +26,10 @@
+
+ 19
+ 19
+ UTF-8
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-19/src/main/java/com/baeldung/highcpu/Application.java b/core-java-modules/core-java-19/src/main/java/com/baeldung/highcpu/Application.java
new file mode 100644
index 000000000000..82162406b345
--- /dev/null
+++ b/core-java-modules/core-java-19/src/main/java/com/baeldung/highcpu/Application.java
@@ -0,0 +1,20 @@
+package com.baeldung.highcpu;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.function.IntUnaryOperator;
+import java.util.stream.IntStream;
+
+public class Application {
+
+ static List generateList() {
+ return IntStream.range(0, 10000000).parallel().map(IntUnaryOperator.identity()).collect(LinkedList::new, List::add, List::addAll);
+ }
+
+ public static void main(String[] args) {
+ List list = generateList();
+ long start = System.nanoTime();
+ int value = list.get(9500000);
+ System.out.printf("Found value %d in %d nanos\n", value, (System.nanoTime() - start));
+ }
+}
diff --git a/core-java-modules/core-java-20/README.md b/core-java-modules/core-java-20/README.md
new file mode 100644
index 000000000000..aba4e9e240fa
--- /dev/null
+++ b/core-java-modules/core-java-20/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values)
diff --git a/core-java-modules/core-java-20/pom.xml b/core-java-modules/core-java-20/pom.xml
new file mode 100644
index 000000000000..9562a41b1c8a
--- /dev/null
+++ b/core-java-modules/core-java-20/pom.xml
@@ -0,0 +1,65 @@
+
+
+ 4.0.0
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+ core-java-20
+
+
+ 20
+ 20
+ UTF-8
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ 20
+
+ --enable-preview
+ --add-modules=jdk.incubator.concurrent
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+ --enable-preview --add-modules=jdk.incubator.concurrent
+
+
+
+
+
+
+
+ jakarta.servlet
+ jakarta.servlet-api
+ 6.0.0
+ provided
+
+
+ org.assertj
+ assertj-core
+ 3.24.2
+ test
+
+
+ org.mockito
+ mockito-junit-jupiter
+ 5.2.0
+ test
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Controller.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Controller.java
new file mode 100644
index 000000000000..92edc57e4881
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Controller.java
@@ -0,0 +1,33 @@
+package com.baeldung.scopedvalues.classic;
+
+import com.baeldung.scopedvalues.data.Data;
+import com.baeldung.scopedvalues.data.User;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Optional;
+
+public class Controller {
+
+ private final Service service = new Service();
+
+ public void processRequest(HttpServletRequest request, HttpServletResponse response, User loggedInUser) {
+ Optional data = service.getData(request, loggedInUser);
+ if (data.isPresent()) {
+ try {
+ PrintWriter out = response.getWriter();
+ response.setContentType("application/json");
+ out.print(data.get());
+ out.flush();
+ response.setStatus(200);
+ } catch (IOException e) {
+ response.setStatus(500);
+ }
+ } else {
+ response.setStatus(400);
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Repository.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Repository.java
new file mode 100644
index 000000000000..3085b3be580c
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Repository.java
@@ -0,0 +1,16 @@
+package com.baeldung.scopedvalues.classic;
+
+import com.baeldung.scopedvalues.data.Data;
+import com.baeldung.scopedvalues.data.User;
+
+import java.util.Optional;
+
+public class Repository {
+
+ public Optional getData(String id, User user) {
+ return user.isAdmin()
+ ? Optional.of(new Data(id, "Title 1", "Description 1"))
+ : Optional.empty();
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Server.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Server.java
new file mode 100644
index 000000000000..71afa9e675d6
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Server.java
@@ -0,0 +1,42 @@
+package com.baeldung.scopedvalues.classic;
+
+import com.baeldung.scopedvalues.data.User;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.*;
+
+public class Server {
+
+ private static final List AUTHENTICATED_USERS = List.of(
+ new User("1", "admin", "123456", true),
+ new User("2", "user", "123456", false)
+ );
+ private final Controller controller = new Controller();
+ private final ExecutorService executor = Executors.newFixedThreadPool(5);
+
+ public void serve(HttpServletRequest request, HttpServletResponse response) throws InterruptedException, ExecutionException {
+ Optional user = authenticateUser(request);
+ if (user.isPresent()) {
+ Future> future = executor.submit(() ->
+ controller.processRequest(request, response, user.get()));
+ future.get();
+ } else {
+ response.setStatus(401);
+ }
+ }
+
+ private Optional authenticateUser(HttpServletRequest request) {
+ return AUTHENTICATED_USERS.stream()
+ .filter(user -> checkUserPassword(user, request))
+ .findFirst();
+ }
+
+ private boolean checkUserPassword(User user, HttpServletRequest request) {
+ return user.name().equals(request.getParameter("user_name"))
+ && user.password().equals(request.getParameter("user_pw"));
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Service.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Service.java
new file mode 100644
index 000000000000..011f79300135
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Service.java
@@ -0,0 +1,18 @@
+package com.baeldung.scopedvalues.classic;
+
+import com.baeldung.scopedvalues.data.Data;
+import com.baeldung.scopedvalues.data.User;
+import jakarta.servlet.http.HttpServletRequest;
+
+import java.util.Optional;
+
+public class Service {
+
+ private final Repository repository = new Repository();
+
+ public Optional getData(HttpServletRequest request, User loggedInUser) {
+ String id = request.getParameter("data_id");
+ return repository.getData(id, loggedInUser);
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/data/Data.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/data/Data.java
new file mode 100644
index 000000000000..70be41c1ac4a
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/data/Data.java
@@ -0,0 +1,3 @@
+package com.baeldung.scopedvalues.data;
+
+public record Data(String id, String title, String description) {}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/data/User.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/data/User.java
new file mode 100644
index 000000000000..22e0a4243f12
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/data/User.java
@@ -0,0 +1,3 @@
+package com.baeldung.scopedvalues.data;
+
+public record User(String id, String name, String password, boolean isAdmin) {}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Controller.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Controller.java
new file mode 100644
index 000000000000..239ee88f1955
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Controller.java
@@ -0,0 +1,37 @@
+package com.baeldung.scopedvalues.scoped;
+
+import com.baeldung.scopedvalues.data.Data;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jdk.incubator.concurrent.ScopedValue;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Optional;
+
+public class Controller {
+
+ private final Service internalService = new Service();
+
+ public void processRequest(HttpServletRequest request, HttpServletResponse response) {
+ Optional data = internalService.getData(request);
+
+ ScopedValue.where(Server.LOGGED_IN_USER, null)
+ .run(internalService::extractData);
+
+ if (data.isPresent()) {
+ try {
+ PrintWriter out = response.getWriter();
+ response.setContentType("application/json");
+ out.print(data.get());
+ out.flush();
+ response.setStatus(200);
+ } catch (IOException e) {
+ response.setStatus(500);
+ }
+ } else {
+ response.setStatus(400);
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Repository.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Repository.java
new file mode 100644
index 000000000000..a40191eb3c3d
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Repository.java
@@ -0,0 +1,17 @@
+package com.baeldung.scopedvalues.scoped;
+
+import com.baeldung.scopedvalues.data.Data;
+import com.baeldung.scopedvalues.data.User;
+
+import java.util.Optional;
+
+public class Repository {
+
+ public Optional getData(String id) {
+ User loggedInUser = Server.LOGGED_IN_USER.get();
+ return loggedInUser.isAdmin()
+ ? Optional.of(new Data(id, "Title 1", "Description 1"))
+ : Optional.empty();
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Server.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Server.java
new file mode 100644
index 000000000000..559e4efd5618
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Server.java
@@ -0,0 +1,41 @@
+package com.baeldung.scopedvalues.scoped;
+
+import com.baeldung.scopedvalues.data.User;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jdk.incubator.concurrent.ScopedValue;
+
+import java.util.List;
+import java.util.Optional;
+
+public class Server {
+
+ private static final List AUTHENTICATED_USERS = List.of(
+ new User("1", "admin", "123456", true),
+ new User("2", "user", "123456", false)
+ );
+ public final static ScopedValue LOGGED_IN_USER = ScopedValue.newInstance();
+ private final Controller controller = new Controller();
+
+ public void serve(HttpServletRequest request, HttpServletResponse response) {
+ Optional user = authenticateUser(request);
+ if (user.isPresent()) {
+ ScopedValue.where(LOGGED_IN_USER, user.get())
+ .run(() -> controller.processRequest(request, response));
+ } else {
+ response.setStatus(401);
+ }
+ }
+
+ private Optional authenticateUser(HttpServletRequest request) {
+ return AUTHENTICATED_USERS.stream()
+ .filter(user -> checkUserPassword(user, request))
+ .findFirst();
+ }
+
+ private boolean checkUserPassword(User user, HttpServletRequest request) {
+ return user.name().equals(request.getParameter("user_name"))
+ && user.password().equals(request.getParameter("user_pw"));
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Service.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Service.java
new file mode 100644
index 000000000000..e35d98cae523
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Service.java
@@ -0,0 +1,23 @@
+package com.baeldung.scopedvalues.scoped;
+
+import com.baeldung.scopedvalues.data.Data;
+import com.baeldung.scopedvalues.data.User;
+import jakarta.servlet.http.HttpServletRequest;
+
+import java.util.Optional;
+
+public class Service {
+
+ private final Repository repository = new Repository();
+
+ public Optional getData(HttpServletRequest request) {
+ String id = request.getParameter("data_id");
+ return repository.getData(id);
+ }
+
+ public void extractData() {
+ User loggedInUser = Server.LOGGED_IN_USER.get();
+ assert loggedInUser == null;
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Controller.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Controller.java
new file mode 100644
index 000000000000..e4742c099872
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Controller.java
@@ -0,0 +1,44 @@
+package com.baeldung.scopedvalues.scoped.inheriting;
+
+import com.baeldung.scopedvalues.data.Data;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jdk.incubator.concurrent.StructuredTaskScope;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Optional;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+public class Controller {
+
+ private final InternalService internalService = new InternalService();
+ private final ExternalService externalService = new ExternalService();
+
+ public void processRequest(HttpServletRequest request, HttpServletResponse response) {
+ try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
+ Future> internalData = scope.fork(() -> internalService.getData(request));
+ Future externalData = scope.fork(externalService::getData);
+ try {
+ scope.join();
+ scope.throwIfFailed();
+
+ Optional data = internalData.resultNow();
+ if (data.isPresent()) {
+ PrintWriter out = response.getWriter();
+ response.setContentType("application/json");
+ out.println(data.get());
+ out.print(externalData.resultNow());
+ out.flush();
+ response.setStatus(200);
+ } else {
+ response.setStatus(400);
+ }
+ } catch (InterruptedException | ExecutionException | IOException e) {
+ response.setStatus(500);
+ }
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/ExternalService.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/ExternalService.java
new file mode 100644
index 000000000000..88fa4dfb7490
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/ExternalService.java
@@ -0,0 +1,9 @@
+package com.baeldung.scopedvalues.scoped.inheriting;
+
+public class ExternalService {
+
+ public String getData() {
+ return "External data";
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/InternalService.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/InternalService.java
new file mode 100644
index 000000000000..ace46b254c6f
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/InternalService.java
@@ -0,0 +1,17 @@
+package com.baeldung.scopedvalues.scoped.inheriting;
+
+import com.baeldung.scopedvalues.data.Data;
+import jakarta.servlet.http.HttpServletRequest;
+
+import java.util.Optional;
+
+public class InternalService {
+
+ private final Repository repository = new Repository();
+
+ public Optional getData(HttpServletRequest request) {
+ String id = request.getParameter("data_id");
+ return repository.getData(id);
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Repository.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Repository.java
new file mode 100644
index 000000000000..22d18b2facc0
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Repository.java
@@ -0,0 +1,17 @@
+package com.baeldung.scopedvalues.scoped.inheriting;
+
+import com.baeldung.scopedvalues.data.Data;
+import com.baeldung.scopedvalues.data.User;
+
+import java.util.Optional;
+
+public class Repository {
+
+ public Optional getData(String id) {
+ User loggedInUser = Server.LOGGED_IN_USER.get();
+ return loggedInUser.isAdmin()
+ ? Optional.of(new Data(id, "Title 1", "Description 1"))
+ : Optional.empty();
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Server.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Server.java
new file mode 100644
index 000000000000..5f04a1eedd22
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Server.java
@@ -0,0 +1,41 @@
+package com.baeldung.scopedvalues.scoped.inheriting;
+
+import com.baeldung.scopedvalues.data.User;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jdk.incubator.concurrent.ScopedValue;
+
+import java.util.List;
+import java.util.Optional;
+
+public class Server {
+
+ private static final List AUTHENTICATED_USERS = List.of(
+ new User("1", "admin", "123456", true),
+ new User("2", "user", "123456", false)
+ );
+ public final static ScopedValue LOGGED_IN_USER = ScopedValue.newInstance();
+ private final Controller controller = new Controller();
+
+ public void serve(HttpServletRequest request, HttpServletResponse response) {
+ Optional user = authenticateUser(request);
+ if (user.isPresent()) {
+ ScopedValue.where(LOGGED_IN_USER, user.get())
+ .run(() -> controller.processRequest(request, response));
+ } else {
+ response.setStatus(401);
+ }
+ }
+
+ private Optional authenticateUser(HttpServletRequest request) {
+ return AUTHENTICATED_USERS.stream()
+ .filter(user -> checkUserPassword(user, request))
+ .findFirst();
+ }
+
+ private boolean checkUserPassword(User user, HttpServletRequest request) {
+ return user.name().equals(request.getParameter("user_name"))
+ && user.password().equals(request.getParameter("user_pw"));
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/classic/ServerUnitTest.java b/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/classic/ServerUnitTest.java
new file mode 100644
index 000000000000..e0b9366c2224
--- /dev/null
+++ b/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/classic/ServerUnitTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.scopedvalues.classic;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.concurrent.ExecutionException;
+
+import static org.mockito.Mockito.*;
+import static org.assertj.core.api.Assertions.*;
+@ExtendWith(MockitoExtension.class)
+public class ServerUnitTest {
+
+ @Mock
+ private HttpServletRequest request;
+
+ @Mock
+ private HttpServletResponse response;
+
+ private final StringWriter writer = new StringWriter();
+
+ private final Server server = new Server();
+
+ @Test
+ void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws InterruptedException, IOException, ExecutionException {
+ when(request.getParameter("user_name")).thenReturn("admin");
+ when(request.getParameter("user_pw")).thenReturn("123456");
+ when(request.getParameter("data_id")).thenReturn("1");
+ when(response.getWriter()).thenReturn(new PrintWriter(writer));
+
+ server.serve(request, response);
+
+ assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]");
+ }
+
+ @Test
+ void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws InterruptedException, ExecutionException {
+ when(request.getParameter("user_name")).thenReturn("user");
+ when(request.getParameter("user_pw")).thenReturn("123456");
+
+ server.serve(request, response);
+
+ assertThat(writer.toString()).isEqualTo("");
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/scoped/ServerUnitTest.java b/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/scoped/ServerUnitTest.java
new file mode 100644
index 000000000000..034e6683e372
--- /dev/null
+++ b/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/scoped/ServerUnitTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.scopedvalues.scoped;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+public class ServerUnitTest {
+
+ @Mock
+ private HttpServletRequest request;
+
+ @Mock
+ private HttpServletResponse response;
+
+ private final StringWriter writer = new StringWriter();
+
+ private final Server server = new Server();
+
+ @Test
+ void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws IOException {
+ when(request.getParameter("user_name")).thenReturn("admin");
+ when(request.getParameter("user_pw")).thenReturn("123456");
+ when(request.getParameter("data_id")).thenReturn("1");
+ when(response.getWriter()).thenReturn(new PrintWriter(writer));
+
+ server.serve(request, response);
+
+ assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]");
+ }
+
+ @Test
+ void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws IOException {
+ when(request.getParameter("user_name")).thenReturn("user");
+ when(request.getParameter("user_pw")).thenReturn("123456");
+
+ server.serve(request, response);
+
+ assertThat(writer.toString()).isEqualTo("");
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/scoped/inheriting/ServerUnitTest.java b/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/scoped/inheriting/ServerUnitTest.java
new file mode 100644
index 000000000000..230b017c185c
--- /dev/null
+++ b/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/scoped/inheriting/ServerUnitTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.scopedvalues.scoped.inheriting;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+public class ServerUnitTest {
+
+ @Mock
+ private HttpServletRequest request;
+
+ @Mock
+ private HttpServletResponse response;
+
+ private final StringWriter writer = new StringWriter();
+
+ private final Server server = new Server();
+
+ @Test
+ void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws IOException {
+ when(request.getParameter("user_name")).thenReturn("admin");
+ when(request.getParameter("user_pw")).thenReturn("123456");
+ when(request.getParameter("data_id")).thenReturn("1");
+ when(response.getWriter()).thenReturn(new PrintWriter(writer));
+
+ server.serve(request, response);
+
+ assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]\nExternal data");
+ }
+
+ @Test
+ void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws IOException {
+ when(request.getParameter("user_name")).thenReturn("user");
+ when(request.getParameter("user_pw")).thenReturn("123456");
+
+ server.serve(request, response);
+
+ assertThat(writer.toString()).isEqualTo("");
+ }
+
+}
diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md
index cad4a4f1fa67..c723a827b162 100644
--- a/core-java-modules/core-java-8-2/README.md
+++ b/core-java-modules/core-java-8-2/README.md
@@ -11,4 +11,6 @@ This module contains articles about Java 8 core features
- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
- [Create a Simple “Rock-Paper-Scissors” Game in Java](https://www.baeldung.com/java-rock-paper-scissors)
- [VarArgs vs Array Input Parameters in Java](https://www.baeldung.com/varargs-vs-array)
+- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)
+- [Java Helper vs. Utility Classes](https://www.baeldung.com/java-helper-vs-utility-classes)
- [[<-- Prev]](/core-java-modules/core-java-8)
diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml
index 7db1e1ed4e58..589e38461319 100644
--- a/core-java-modules/core-java-8-2/pom.xml
+++ b/core-java-modules/core-java-8-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-8-2
- 0.1.0-SNAPSHOT
core-java-8-2
jar
diff --git a/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java
similarity index 100%
rename from core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java
rename to core-java-modules/core-java-8-2/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java
diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/helpervsutilityclasses/MyHelperClass.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/helpervsutilityclasses/MyHelperClass.java
new file mode 100644
index 000000000000..40b58bf20020
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/helpervsutilityclasses/MyHelperClass.java
@@ -0,0 +1,40 @@
+package com.baeldung.helpervsutilityclasses;
+
+class MyHelperClass {
+ public double discount;
+ public MyHelperClass(double discount) {
+ if (discount > 0 && discount < 1) {
+ this.discount = discount;
+ }
+ }
+ public double discountedPrice(double price) {
+ return price - (price * discount);
+ }
+
+ public static int getMaxNumber(int[] numbers) {
+ if (numbers.length == 0) {
+ throw new IllegalArgumentException("Ensure array is not empty");
+ }
+ int max = numbers[0];
+ for (int i = 1; i < numbers.length; i++) {
+ if (numbers[i] > max) {
+ max = numbers[i];
+ }
+ }
+ return max;
+ }
+
+ public static int getMinNumber(int[] numbers) {
+ if (numbers.length == 0) {
+ throw new IllegalArgumentException("Ensure array is not empty");
+ }
+ int min = numbers[0];
+ for (int i = 1; i < numbers.length; i++) {
+ if (numbers[i] < min) {
+ min = numbers[i];
+ }
+ }
+ return min;
+ }
+
+}
diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/helpervsutilityclasses/MyUtilityClass.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/helpervsutilityclasses/MyUtilityClass.java
new file mode 100644
index 000000000000..1f0075995ced
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/helpervsutilityclasses/MyUtilityClass.java
@@ -0,0 +1,19 @@
+package com.baeldung.helpervsutilityclasses;
+
+public final class MyUtilityClass {
+
+ private MyUtilityClass(){}
+
+ public static String returnUpperCase(String stringInput) {
+ return stringInput.toUpperCase();
+ }
+
+ public static String returnLowerCase(String stringInput) {
+ return stringInput.toLowerCase();
+ }
+
+ public static String[] splitStringInput(String stringInput, String delimiter) {
+ return stringInput.split(delimiter);
+ }
+
+}
diff --git a/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/lambdaexpression/LambdaExpressionExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/lambdaexpression/LambdaExpressionExample.java
similarity index 100%
rename from core-java-modules/core-java-lambdas/src/main/java/com/baeldung/lambdaexpression/LambdaExpressionExample.java
rename to core-java-modules/core-java-8-2/src/main/java/com/baeldung/lambdaexpression/LambdaExpressionExample.java
diff --git a/core-java-modules/core-java-8-2/src/test/java/com/baeldung/helpervsutilityclasses/MyHelperClassUnitTest.java b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/helpervsutilityclasses/MyHelperClassUnitTest.java
new file mode 100644
index 000000000000..a0c1afea52e3
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/helpervsutilityclasses/MyHelperClassUnitTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.helpervsutilityclasses;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class MyHelperClassUnitTest {
+
+ @Test
+ void whenCreatingHelperObject_thenHelperObjectShouldBeCreated() {
+ MyHelperClass myHelperClassObject = new MyHelperClass(0.10);
+ int[] numberArray = {15, 23, 66, 3, 51, 79};
+
+ assertNotNull(myHelperClassObject);
+
+ assertEquals(90, myHelperClassObject.discountedPrice(100.00));
+ assertEquals( 79, MyHelperClass.getMaxNumber(numberArray));
+ assertEquals(3, MyHelperClass.getMinNumber(numberArray));
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-8-2/src/test/java/com/baeldung/helpervsutilityclasses/MyUtilityClassUnitTest.java b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/helpervsutilityclasses/MyUtilityClassUnitTest.java
new file mode 100644
index 000000000000..8b29f51959e3
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/helpervsutilityclasses/MyUtilityClassUnitTest.java
@@ -0,0 +1,15 @@
+package com.baeldung.helpervsutilityclasses;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class MyUtilityClassUnitTest {
+
+ @Test
+ void whenUsingUtilityMethods_thenAccessMethodsViaClassName(){
+ assertEquals( "INIUBONG", MyUtilityClass.returnUpperCase("iniubong"));
+ assertEquals("accra", MyUtilityClass.returnLowerCase("AcCrA"));
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-8-datetime-2/README.md b/core-java-modules/core-java-8-datetime-2/README.md
index f16563aacc5a..56f66c10fbcf 100644
--- a/core-java-modules/core-java-8-datetime-2/README.md
+++ b/core-java-modules/core-java-8-datetime-2/README.md
@@ -2,4 +2,5 @@
- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates)
- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values)
-- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
\ No newline at end of file
+- [Parsing Date Strings with Varying Formats](https://www.baeldung.com/java-parsing-dates-many-formats)
+- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
diff --git a/core-java-modules/core-java-8-datetime-2/pom.xml b/core-java-modules/core-java-8-datetime-2/pom.xml
index 9e54b0ee1283..ce349d9dc3fb 100644
--- a/core-java-modules/core-java-8-datetime-2/pom.xml
+++ b/core-java-modules/core-java-8-datetime-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-8-datetime-2
- ${project.parent.version}
core-java-8-datetime-2
jar
diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateTimeFormat.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateTimeFormat.java
new file mode 100644
index 000000000000..a82f3bce2b68
--- /dev/null
+++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateTimeFormat.java
@@ -0,0 +1,20 @@
+package com.baeldung.parsingDates;
+
+import java.util.Arrays;
+import java.util.List;
+import org.joda.time.LocalDate;
+import org.joda.time.format.DateTimeFormat;
+
+public class SimpleDateTimeFormat {
+
+ public static LocalDate parseDate(String date) {
+ List patternList = Arrays.asList("MM/dd/yyyy", "dd.MM.yyyy", "yyyy-MM-dd");
+ for (String pattern : patternList) {
+ try {
+ return DateTimeFormat.forPattern(pattern).parseLocalDate(date);
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ return null;
+ }
+}
diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateTimeFormater.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateTimeFormater.java
new file mode 100644
index 000000000000..aa12038032d1
--- /dev/null
+++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateTimeFormater.java
@@ -0,0 +1,17 @@
+package com.baeldung.parsingDates;
+
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeFormatterBuilder;
+
+public class SimpleDateTimeFormater {
+
+ public static LocalDate parseDate(String date) {
+ DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
+ .append(DateTimeFormatter.ofPattern("[MM/dd/yyyy]" + "[dd-MM-yyyy]" + "[yyyy-MM-dd]"));
+
+ DateTimeFormatter dateTimeFormatter = dateTimeFormatterBuilder.toFormatter();
+
+ return LocalDate.parse(date, dateTimeFormatter);
+ }
+}
diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateUtils.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateUtils.java
new file mode 100644
index 000000000000..8a154d3cd821
--- /dev/null
+++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateUtils.java
@@ -0,0 +1,18 @@
+package com.baeldung.parsingDates;
+
+import java.text.ParseException;
+import java.util.Date;
+import org.apache.commons.lang3.time.DateUtils;
+
+public class SimpleDateUtils {
+
+ public static Date parseDate(String date) {
+ try {
+ return DateUtils.parseDateStrictly(date,
+ new String[]{"yyyy/MM/dd", "dd/MM/yyyy", "yyyy-MM-dd"});
+ } catch (ParseException ex) {
+ return null;
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleParseDate.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleParseDate.java
new file mode 100644
index 000000000000..cb024eea5369
--- /dev/null
+++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleParseDate.java
@@ -0,0 +1,19 @@
+package com.baeldung.parsingDates;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+
+public class SimpleParseDate {
+
+ public Date parseDate(String dateString, List formatStrings) {
+ for (String formatString : formatStrings) {
+ try {
+ return new SimpleDateFormat(formatString).parse(dateString);
+ } catch (ParseException e) {
+ }
+ }
+ return null;
+ }
+}
diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/parsingDates/SimpleParseDateUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/parsingDates/SimpleParseDateUnitTest.java
new file mode 100644
index 000000000000..d7cbb6a83486
--- /dev/null
+++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/parsingDates/SimpleParseDateUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.parsingDates;
+
+import com.baeldung.parsingDates.SimpleDateTimeFormat;
+import com.baeldung.parsingDates.SimpleDateTimeFormater;
+import com.baeldung.parsingDates.SimpleDateUtils;
+import com.baeldung.parsingDates.SimpleParseDate;
+import java.time.format.DateTimeParseException;
+import java.util.Arrays;
+import org.junit.*;
+import static org.junit.Assert.*;
+import org.joda.time.LocalDate;
+
+public class SimpleParseDateUnitTest {
+
+ @Test
+ public void whenInvalidInput_thenGettingUnexpectedResult() {
+ SimpleParseDate simpleParseDate = new SimpleParseDate();
+ String date = "2022-40-40";
+ assertEquals("Sat May 10 00:00:00 UTC 2025", simpleParseDate.parseDate(date, Arrays.asList("MM/dd/yyyy", "dd.MM.yyyy", "yyyy-MM-dd")).toString());
+ }
+
+ @Test
+ public void whenInvalidDate_thenAssertThrows() {
+ SimpleDateTimeFormater simpleDateTimeFormater = new SimpleDateTimeFormater();
+ assertEquals(java.time.LocalDate.parse("2022-12-04"), simpleDateTimeFormater.parseDate("2022-12-04"));
+ assertThrows(DateTimeParseException.class, () -> simpleDateTimeFormater.parseDate("2022-13-04"));
+ }
+
+ @Test
+ public void whenDateIsCorrect_thenParseCorrect() {
+ SimpleDateUtils simpleDateUtils = new SimpleDateUtils();
+ assertNull(simpleDateUtils.parseDate("53/10/2014"));
+ assertEquals("Wed Sep 10 00:00:00 UTC 2014", simpleDateUtils.parseDate("10/09/2014").toString());
+ }
+
+ @Test
+ public void whenDateIsCorrect_thenResultCorrect() {
+ SimpleDateTimeFormat simpleDateTimeFormat = new SimpleDateTimeFormat();
+ assertNull(simpleDateTimeFormat.parseDate("53/10/2014"));
+ assertEquals(LocalDate.parse("2014-10-10"), simpleDateTimeFormat.parseDate("2014-10-10"));
+ }
+
+}
diff --git a/core-java-modules/core-java-8-datetime/pom.xml b/core-java-modules/core-java-8-datetime/pom.xml
index 01ec6c0b7668..481b1a6a69ca 100644
--- a/core-java-modules/core-java-8-datetime/pom.xml
+++ b/core-java-modules/core-java-8-datetime/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-8-datetime
- ${project.parent.version}
core-java-8-datetime
jar
diff --git a/core-java-modules/core-java-8/pom.xml b/core-java-modules/core-java-8/pom.xml
index 89925bdbbbcc..fff7b7f2f996 100644
--- a/core-java-modules/core-java-8/pom.xml
+++ b/core-java-modules/core-java-8/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-8
- 0.1.0-SNAPSHOT
core-java-8
jar
diff --git a/core-java-modules/core-java-9-improvements/pom.xml b/core-java-modules/core-java-9-improvements/pom.xml
index 56d4ccff9fd5..f6f13ff4090b 100644
--- a/core-java-modules/core-java-9-improvements/pom.xml
+++ b/core-java-modules/core-java-9-improvements/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-9-improvements
- 0.2-SNAPSHOT
core-java-9-improvements
diff --git a/core-java-modules/core-java-9-jigsaw/README.md b/core-java-modules/core-java-9-jigsaw/README.md
index cfffb865886c..73905e6033e5 100644
--- a/core-java-modules/core-java-9-jigsaw/README.md
+++ b/core-java-modules/core-java-9-jigsaw/README.md
@@ -8,5 +8,5 @@ This module contains articles about Project Jigsaw and the Java Platform Module
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api)
- [Java 9 Illegal Reflective Access Warning](https://www.baeldung.com/java-illegal-reflective-access)
-
+- [Java Modularity and Unit Testing](https://www.baeldung.com/java-modularity-unit-testing)
diff --git a/core-java-modules/core-java-9-jigsaw/compile-library-core-module.sh b/core-java-modules/core-java-9-jigsaw/compile-library-core-module.sh
new file mode 100644
index 000000000000..fa0d4d5f1419
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/compile-library-core-module.sh
@@ -0,0 +1,2 @@
+#!/usr/bin/env bash
+javac -d mods/com.baeldung.library.core $(find library-core/src/main -name "*.java")
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/compile-library-core-tests.sh b/core-java-modules/core-java-9-jigsaw/compile-library-core-tests.sh
new file mode 100644
index 000000000000..751906103b05
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/compile-library-core-tests.sh
@@ -0,0 +1,10 @@
+#!/usr/bin/env bash
+javac --class-path outDir/library-core/:\
+libs/junit-jupiter-engine-5.9.2.jar:\
+libs/junit-platform-engine-1.9.2.jar:\
+libs/apiguardian-api-1.1.2.jar:\
+libs/junit-jupiter-params-5.9.2.jar:\
+libs/junit-jupiter-api-5.9.2.jar:\
+libs/opentest4j-1.2.0.jar:\
+libs/junit-platform-commons-1.9.2.jar \
+-d outDir/library-test library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/compile-library-core-with-tests.sh b/core-java-modules/core-java-9-jigsaw/compile-library-core-with-tests.sh
new file mode 100644
index 000000000000..c873a9003c30
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/compile-library-core-with-tests.sh
@@ -0,0 +1,13 @@
+#!/usr/bin/env bash
+javac --class-path libs/junit-jupiter-engine-5.9.2.jar:\
+libs/junit-platform-engine-1.9.2.jar:\
+libs/apiguardian-api-1.1.2.jar:\
+libs/junit-jupiter-params-5.9.2.jar:\
+libs/junit-jupiter-api-5.9.2.jar:\
+libs/opentest4j-1.2.0.jar:\
+libs/junit-platform-commons-1.9.2.jar \
+-d outDir/library-core \
+library-core/src/main/java/com/baeldung/library/core/Book.java \
+library-core/src/main/java/com/baeldung/library/core/Library.java \
+library-core/src/main/java/com/baeldung/library/core/Main.java \
+library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/compile-library-core.sh b/core-java-modules/core-java-9-jigsaw/compile-library-core.sh
new file mode 100644
index 000000000000..7531148d0fb3
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/compile-library-core.sh
@@ -0,0 +1,12 @@
+#!/usr/bin/env bash
+javac --class-path libs/junit-jupiter-engine-5.9.2.jar:\
+libs/junit-platform-engine-1.9.2.jar:\
+libs/apiguardian-api-1.1.2.jar:\
+libs/junit-jupiter-params-5.9.2.jar:\
+libs/junit-jupiter-api-5.9.2.jar:\
+libs/opentest4j-1.2.0.jar:\
+libs/junit-platform-commons-1.9.2.jar \
+-d outDir/library-core \
+library-core/src/main/java/com/baeldung/library/core/Book.java \
+library-core/src/main/java/com/baeldung/library/core/Library.java \
+library-core/src/main/java/com/baeldung/library/core/Main.java
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/compile-library-test-module.sh b/core-java-modules/core-java-9-jigsaw/compile-library-test-module.sh
new file mode 100644
index 000000000000..c6fd614fd05d
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/compile-library-test-module.sh
@@ -0,0 +1,2 @@
+#!/usr/bin/env bash
+javac --module-path mods:libs -d mods/com.baeldung.library.test $(find library-test/src/test -name "*.java")
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/download-junit-dependencies.sh b/core-java-modules/core-java-9-jigsaw/download-junit-dependencies.sh
new file mode 100644
index 000000000000..64c72a54298f
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/download-junit-dependencies.sh
@@ -0,0 +1,10 @@
+#!/usr/bin/env bash
+wget -P libs/ https://repo1.maven.org/maven2/org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-commons/1.9.2/junit-platform-commons-1.9.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-engine/1.9.2/junit-platform-engine-1.9.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-reporting/1.9.2/junit-platform-reporting-1.9.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-console/1.9.2/junit-platform-console-1.9.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/1.9.2/junit-platform-launcher-1.9.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/jupiter/junit-jupiter-engine/5.9.2/junit-jupiter-engine-5.9.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/jupiter/junit-jupiter-params/5.9.2/junit-jupiter-params-5.9.2.jar
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/library-core/pom.xml b/core-java-modules/core-java-9-jigsaw/library-core/pom.xml
new file mode 100644
index 000000000000..b860d899326d
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-core/pom.xml
@@ -0,0 +1,55 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ core-java-9-jigsaw
+ 0.2-SNAPSHOT
+
+
+ library-core
+
+
+ 19
+ 19
+ UTF-8
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter-api
+ 5.9.2
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ 5.9.2
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.8.1
+
+ 9
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 3.0.0-M5
+
+ false
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Book.java b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Book.java
new file mode 100644
index 000000000000..782de8fa1064
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Book.java
@@ -0,0 +1,52 @@
+package com.baeldung.library.core;
+
+import java.util.Objects;
+
+public class Book {
+
+ private String title;
+ private String author;
+
+ public Book(String title, String author) {
+ this.title = title;
+ this.author = author;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public String getAuthor() {
+ return author;
+ }
+
+
+ @Override
+ public String toString() {
+ return "Book [title=" + title + ", author=" + author + "]";
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ final Book book = (Book) o;
+
+ if (!Objects.equals(title, book.title)) {
+ return false;
+ }
+ return Objects.equals(author, book.author);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = title != null ? title.hashCode() : 0;
+ result = 31 * result + (author != null ? author.hashCode() : 0);
+ return result;
+ }
+}
diff --git a/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Library.java b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Library.java
new file mode 100644
index 000000000000..ee2225810de5
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Library.java
@@ -0,0 +1,25 @@
+package com.baeldung.library.core;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Library {
+
+ private List books = new ArrayList<>();
+
+ public void addBook(Book book) {
+ books.add(book);
+ }
+
+ public List getBooks() {
+ return books;
+ }
+
+ void removeBook(Book book) {
+ books.remove(book);
+ }
+
+ protected void removeBookByAuthor(String author) {
+ books.removeIf(book -> book.getAuthor().equals(author));
+ }
+}
diff --git a/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Main.java b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Main.java
new file mode 100644
index 000000000000..18839602c2b3
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Main.java
@@ -0,0 +1,16 @@
+package com.baeldung.library.core;
+
+public class Main {
+
+ public static void main(String[] args) {
+ Library library = new Library();
+ library.addBook(new Book("The Lord of the Rings", "J.R.R. Tolkien"));
+ library.addBook(new Book("The Hobbit", "J.R.R. Tolkien"));
+ library.addBook(new Book("The Silmarillion", "J.R.R. Tolkien"));
+ library.addBook(new Book("The Chronicles of Narnia", "C.S. Lewis"));
+ library.addBook(new Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis"));
+ System.out.println("Welcome to our library!");
+ System.out.println("We have the following books:");
+ library.getBooks().forEach(System.out::println);
+ }
+}
diff --git a/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/module-info.java b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/module-info.java
new file mode 100644
index 000000000000..bdf88d8bc986
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/module-info.java
@@ -0,0 +1,3 @@
+module com.baeldung.library.core {
+ exports com.baeldung.library.core;
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java b/core-java-modules/core-java-9-jigsaw/library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java
new file mode 100644
index 000000000000..20a4889e8cba
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java
@@ -0,0 +1,47 @@
+package com.baeldung.library.core;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class LibraryUnitTest {
+
+ @Test
+ void givenEmptyLibrary_whenAddABook_thenLibraryHasOneBook() {
+ Library library = new Library();
+ Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
+ library.addBook(theLordOfTheRings);
+ int expected = 1;
+ int actual = library.getBooks().size();
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ void givenTheLibraryWithABook_whenRemoveABook_thenLibraryIsEmpty() {
+ Library library = new Library();
+ Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
+ library.addBook(theLordOfTheRings);
+ library.removeBook(theLordOfTheRings);
+ int expected = 0;
+ int actual = library.getBooks().size();
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ void givenTheLibraryWithSeveralBook_whenRemoveABookByAuthor_thenLibraryHasNoBooksByTheAuthor() {
+ Library library = new Library();
+ Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
+ Book theHobbit = new Book("The Hobbit", "J.R.R. Tolkien");
+ Book theSilmarillion = new Book("The Silmarillion", "J.R.R. Tolkien");
+ Book theHungerGames = new Book("The Hunger Games", "Suzanne Collins");
+ library.addBook(theLordOfTheRings);
+ library.addBook(theHobbit);
+ library.addBook(theSilmarillion);
+ library.addBook(theHungerGames);
+ library.removeBookByAuthor("J.R.R. Tolkien");
+ int expected = 1;
+ int actual = library.getBooks().size();
+ assertEquals(expected, actual);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/com/baeldung/library/test/LibraryUnitTest.java b/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/com/baeldung/library/test/LibraryUnitTest.java
new file mode 100644
index 000000000000..31eae89bba1e
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/com/baeldung/library/test/LibraryUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.library.test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import com.baeldung.library.core.Book;
+import com.baeldung.library.core.Library;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import org.junit.jupiter.api.Test;
+
+class LibraryUnitTest {
+
+ @Test
+ void givenEmptyLibrary_whenAddABook_thenLibraryHasOneBook() {
+ Library library = new Library();
+ Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
+ library.addBook(theLordOfTheRings);
+ int expected = 1;
+ int actual = library.getBooks().size();
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ void givenTheLibraryWithABook_whenRemoveABook_thenLibraryIsEmpty()
+ throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
+ Library library = new Library();
+ Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
+ library.addBook(theLordOfTheRings);
+ Method removeBook = Library.class.getDeclaredMethod("removeBook", Book.class);
+ removeBook.setAccessible(true);
+ removeBook.invoke(library, theLordOfTheRings);
+ int expected = 0;
+ int actual = library.getBooks().size();
+ assertEquals(expected, actual);
+ }
+@Test
+void givenTheLibraryWithSeveralBook_whenRemoveABookByAuthor_thenLibraryHasNoBooksByTheAuthor() {
+ TestLibrary library = new TestLibrary();
+ Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
+ Book theHobbit = new Book("The Hobbit", "J.R.R. Tolkien");
+ Book theSilmarillion = new Book("The Silmarillion", "J.R.R. Tolkien");
+ Book theHungerGames = new Book("The Hunger Games", "Suzanne Collins");
+ library.addBook(theLordOfTheRings);
+ library.addBook(theHobbit);
+ library.addBook(theSilmarillion);
+ library.addBook(theHungerGames);
+ library.removeBookByAuthor("J.R.R. Tolkien");
+ int expected = 1;
+ int actual = library.getBooks().size();
+ assertEquals(expected, actual);
+}
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/com/baeldung/library/test/TestLibrary.java b/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/com/baeldung/library/test/TestLibrary.java
new file mode 100644
index 000000000000..8ee3b0e3fe53
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/com/baeldung/library/test/TestLibrary.java
@@ -0,0 +1,10 @@
+package com.baeldung.library.test;
+
+import com.baeldung.library.core.Library;
+
+public class TestLibrary extends Library {
+ @Override
+ public void removeBookByAuthor(final String author) {
+ super.removeBookByAuthor(author);
+ }
+}
diff --git a/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/module-info.java b/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/module-info.java
new file mode 100644
index 000000000000..8d60b574f246
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/module-info.java
@@ -0,0 +1,5 @@
+module com.baeldung.library.test {
+ requires com.baeldung.library.core;
+ requires org.junit.jupiter.api;
+ opens com.baeldung.library.test to org.junit.platform.commons;
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/pom.xml b/core-java-modules/core-java-9-jigsaw/pom.xml
index a26a88f4b084..288254b9cfef 100644
--- a/core-java-modules/core-java-9-jigsaw/pom.xml
+++ b/core-java-modules/core-java-9-jigsaw/pom.xml
@@ -4,8 +4,11 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-9-jigsaw
- 0.2-SNAPSHOT
core-java-9-jigsaw
+ pom
+
+ library-core
+
com.baeldung
diff --git a/core-java-modules/core-java-9-jigsaw/run-library-core-module-with-patch.sh b/core-java-modules/core-java-9-jigsaw/run-library-core-module-with-patch.sh
new file mode 100644
index 000000000000..70772a3589a5
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/run-library-core-module-with-patch.sh
@@ -0,0 +1,7 @@
+#!/usr/bin/env bash
+java --module-path mods:libs \
+--add-modules com.baeldung.library.core \
+--add-opens com.baeldung.library.core/com.baeldung.library.core=org.junit.platform.commons \
+--add-reads com.baeldung.library.core=org.junit.jupiter.api \
+--patch-module com.baeldung.library.core=outDir/library-test \
+--module org.junit.platform.console --select-class com.baeldung.library.core.LibraryUnitTest
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/run-library-core-module.sh b/core-java-modules/core-java-9-jigsaw/run-library-core-module.sh
new file mode 100644
index 000000000000..f2bb976512a0
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/run-library-core-module.sh
@@ -0,0 +1,2 @@
+#!/usr/bin/env bash
+java --module-path mods --module com.baeldung.library.core/com.baeldung.library.core.Main
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/run-library-test-class-path.sh b/core-java-modules/core-java-9-jigsaw/run-library-test-class-path.sh
new file mode 100644
index 000000000000..73e3d504bfa3
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/run-library-test-class-path.sh
@@ -0,0 +1,5 @@
+#!/usr/bin/env bash
+java --module-path libs \
+org.junit.platform.console.ConsoleLauncher \
+--classpath ./outDir/library-core \
+--select-class com.baeldung.library.core.LibraryUnitTest
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/run-library-test-module-path.sh b/core-java-modules/core-java-9-jigsaw/run-library-test-module-path.sh
new file mode 100644
index 000000000000..08d149dbd7fe
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/run-library-test-module-path.sh
@@ -0,0 +1,5 @@
+#!/usr/bin/env bash
+java --module-path mods:libs \
+--add-modules com.baeldung.library.test \
+--add-opens com.baeldung.library.core/com.baeldung.library.core=com.baeldung.library.test \
+org.junit.platform.console.ConsoleLauncher --select-class com.baeldung.library.test.LibraryUnitTest
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-new-features/pom.xml b/core-java-modules/core-java-9-new-features/pom.xml
index 78ffaff01036..6821c9c340c9 100644
--- a/core-java-modules/core-java-9-new-features/pom.xml
+++ b/core-java-modules/core-java-9-new-features/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-9-new-features
- 0.2-SNAPSHOT
core-java-9-new-features
diff --git a/core-java-modules/core-java-9-streams/pom.xml b/core-java-modules/core-java-9-streams/pom.xml
index d3f81780d1ca..903194b3b3d4 100644
--- a/core-java-modules/core-java-9-streams/pom.xml
+++ b/core-java-modules/core-java-9-streams/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-9-streams
- 0.1.0-SNAPSHOT
core-java-9-streams
jar
diff --git a/core-java-modules/core-java-9/README.md b/core-java-modules/core-java-9/README.md
index 38965d88f1be..bd7df0c8a618 100644
--- a/core-java-modules/core-java-9/README.md
+++ b/core-java-modules/core-java-9/README.md
@@ -5,7 +5,6 @@ This module contains articles about Java 9 core features
### Relevant Articles:
- [Method Handles in Java](https://www.baeldung.com/java-method-handles)
-- [Introduction to Chronicle Queue](https://www.baeldung.com/java-chronicle-queue)
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Immutable ArrayList in Java](https://www.baeldung.com/java-immutable-list)
diff --git a/core-java-modules/core-java-9/pom.xml b/core-java-modules/core-java-9/pom.xml
index 272af327cbea..bcfdacdf1d00 100644
--- a/core-java-modules/core-java-9/pom.xml
+++ b/core-java-modules/core-java-9/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-9
- 0.2-SNAPSHOT
core-java-9
diff --git a/core-java-modules/core-java-annotations/pom.xml b/core-java-modules/core-java-annotations/pom.xml
index 1acd3472329d..6b1b9d802fdb 100644
--- a/core-java-modules/core-java-annotations/pom.xml
+++ b/core-java-modules/core-java-annotations/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-annotations
- 0.1.0-SNAPSHOT
core-java-annotations
jar
diff --git a/core-java-modules/core-java-arrays-operations-basic/README.md b/core-java-modules/core-java-arrays-operations-basic/README.md
index 2e1268e00c2a..76f4044355e6 100644
--- a/core-java-modules/core-java-arrays-operations-basic/README.md
+++ b/core-java-modules/core-java-arrays-operations-basic/README.md
@@ -11,3 +11,5 @@ This module contains articles about Java array fundamentals. They assume no prev
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
- [Initializing a Boolean Array in Java](https://www.baeldung.com/java-initializing-boolean-array)
+- [Find the Index of an Element in a Java Array](https://www.baeldung.com/java-array-find-index)
+- [Comparing Two Byte Arrays in Java](https://www.baeldung.com/java-comparing-byte-arrays)
diff --git a/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/arrayindex/ArrayIndex.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/arrayindex/ArrayIndex.java
new file mode 100644
index 000000000000..596e0d424f6f
--- /dev/null
+++ b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/arrayindex/ArrayIndex.java
@@ -0,0 +1,28 @@
+package com.baeldung.arrayindex;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.IntStream;
+
+class ArrayIndex {
+ static int forLoop(int[] numbers, int target) {
+ for (int index = 0; index < numbers.length; index++) {
+ if (numbers[index] == target) {
+ return index;
+ }
+ }
+ return -1;
+ }
+
+ static int listIndexOf(Integer[] numbers, int target) {
+ List list = Arrays.asList(numbers);
+ return list.indexOf(target);
+ }
+
+ static int intStream(int[] numbers, int target) {
+ return IntStream.range(0, numbers.length)
+ .filter(i -> numbers[i] == target)
+ .findFirst()
+ .orElse(-1);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/compare/CompareByteArraysUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/compare/CompareByteArraysUnitTest.java
new file mode 100644
index 000000000000..4274acf83dd3
--- /dev/null
+++ b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/compare/CompareByteArraysUnitTest.java
@@ -0,0 +1,39 @@
+package com.baeldung.array.compare;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.Arrays;
+
+import org.junit.jupiter.api.Test;
+
+public class CompareByteArraysUnitTest {
+ private final static String INPUT = "I am a magic string.";
+ private final static byte[] ARRAY1 = INPUT.getBytes();
+ private final static byte[] ARRAY2 = INPUT.getBytes();
+
+ @Test
+ void whenUsingEqualsSign_thenTwoArraysAreNotEqual() {
+ assertFalse(ARRAY1 == ARRAY2);
+ }
+
+ @Test
+ void whenUsingEquals_thenTwoArraysAreNotEqual() {
+ assertFalse(ARRAY1.equals(ARRAY2));
+ }
+
+ @Test
+ void whenUsingArrayEquals_thenTwoArraysAreEqual() {
+ assertTrue(Arrays.equals(ARRAY1, ARRAY2));
+ }
+
+ @Test
+ void whenComparingStringArrays_thenGetExpectedResult() {
+ String[] strArray1 = new String[] { "Java", "is", "great" };
+ String[] strArray2 = new String[] { "Java", "is", "great" };
+
+ assertFalse(strArray1 == strArray2);
+ assertFalse(strArray1.equals(strArray2));
+ assertTrue(Arrays.equals(strArray1, strArray2));
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/arrayindex/ArrayIndexUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/arrayindex/ArrayIndexUnitTest.java
new file mode 100644
index 000000000000..84c868d5e084
--- /dev/null
+++ b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/arrayindex/ArrayIndexUnitTest.java
@@ -0,0 +1,106 @@
+package com.baeldung.arrayindex;
+
+import static com.baeldung.arrayindex.ArrayIndex.forLoop;
+import static com.baeldung.arrayindex.ArrayIndex.intStream;
+import static com.baeldung.arrayindex.ArrayIndex.listIndexOf;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Arrays;
+
+import org.apache.commons.lang3.ArrayUtils;
+import org.junit.jupiter.api.Test;
+
+import com.google.common.primitives.Ints;
+
+class ArrayIndexUnitTest {
+
+ @Test
+ void givenIntegerArray_whenUseForLoop_thenWillGetElementIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(2, forLoop(numbers, 30));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseForLoop_thenWillGetElementMinusOneIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, forLoop(numbers, 100));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseIndexOf_thenWillGetElementIndex() {
+ Integer[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(2, listIndexOf(numbers, 30));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseIndexOf_thenWillGetElementMinusOneIndex() {
+ Integer[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, listIndexOf(numbers, 100));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseIntStream_thenWillGetElementIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(2, intStream(numbers, 30));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseIntStream_thenWillGetElementMinusOneIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, intStream(numbers, 100));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseBinarySearch_thenWillGetElementIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(2, Arrays.binarySearch(numbers, 30));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseBinarySearch_thenWillGetUpperBoundMinusIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-6, Arrays.binarySearch(numbers, 100));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseBinarySearch_thenWillGetInArrayMinusIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-2, Arrays.binarySearch(numbers, 15));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseBinarySearch_thenWillGetLowerBoundMinusIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, Arrays.binarySearch(numbers, -15));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseApacheCommons_thenWillGetElementIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(2, ArrayUtils.indexOf(numbers, 30));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseApacheCommonsStartingFromIndex_thenWillGetNegativeIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, ArrayUtils.indexOf(numbers, 30, 3));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseApacheCommons_thenWillGetElementMinusOneIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, ArrayUtils.indexOf(numbers, 100));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseGuavaInts_thenWillGetElementIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(2, Ints.indexOf(numbers, 30));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseGuavaInts_thenWillGetElementMinusOneIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, Ints.indexOf(numbers, 100));
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-booleans/README.md b/core-java-modules/core-java-booleans/README.md
index 6a9be31958b8..fe7068c6f464 100644
--- a/core-java-modules/core-java-booleans/README.md
+++ b/core-java-modules/core-java-booleans/README.md
@@ -2,4 +2,5 @@
This module contains articles about Java Booleans.
-### Relevant Articles:
\ No newline at end of file
+### Relevant Articles:
+- [Convert Boolean to String in Java](https://www.baeldung.com/java-convert-boolean-to-string)
diff --git a/core-java-modules/core-java-booleans/pom.xml b/core-java-modules/core-java-booleans/pom.xml
index 18338fd88c11..3b0c28208fdc 100644
--- a/core-java-modules/core-java-booleans/pom.xml
+++ b/core-java-modules/core-java-booleans/pom.xml
@@ -1,16 +1,16 @@
- 4.0.0
- core-java-booleans
- 0.1.0-SNAPSHOT
- core-java-booleans
- jar
+ 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">
+ 4.0.0
+ core-java-booleans
+ core-java-booleans
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
-
- com.baeldung.core-java-modules
- core-java-modules
- 0.0.1-SNAPSHOT
-
\ No newline at end of file
diff --git a/core-java-modules/core-java-char/README.md b/core-java-modules/core-java-char/README.md
index 5f33aa69148e..e4af3121c5b8 100644
--- a/core-java-modules/core-java-char/README.md
+++ b/core-java-modules/core-java-char/README.md
@@ -4,3 +4,4 @@ This module contains articles about Java Character Class
### Relevant Articles:
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)
+- [Difference Between Java’s “char” and “String”](https://www.baeldung.com/java-char-vs-string)
diff --git a/core-java-modules/core-java-char/pom.xml b/core-java-modules/core-java-char/pom.xml
index 7dc0923fb50d..eb6cbee952a9 100644
--- a/core-java-modules/core-java-char/pom.xml
+++ b/core-java-modules/core-java-char/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-char
- 0.1.0-SNAPSHOT
core-java-char
jar
diff --git a/core-java-modules/core-java-char/src/test/java/com/baeldung/charandstring/DifferenceBetweenCharAndStringUnitTest.java b/core-java-modules/core-java-char/src/test/java/com/baeldung/charandstring/DifferenceBetweenCharAndStringUnitTest.java
new file mode 100644
index 000000000000..b4e1da6d713b
--- /dev/null
+++ b/core-java-modules/core-java-char/src/test/java/com/baeldung/charandstring/DifferenceBetweenCharAndStringUnitTest.java
@@ -0,0 +1,56 @@
+package com.baeldung.charandstring;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+
+import org.junit.jupiter.api.Test;
+
+public class DifferenceBetweenCharAndStringUnitTest {
+
+ @Test
+ void whenPlusTwoChars_thenGetSumAsInteger() {
+ char h = 'H'; // the value is 72
+ char i = 'i'; // the value is 105
+ assertEquals(177, h + i);
+ assertInstanceOf(Integer.class, h + i);
+ }
+
+ @Test
+ void whenPlusTwoStrings_thenConcatenateThem() {
+ String i = "i";
+ String h = "H";
+ assertEquals("Hi", h + i);
+ }
+
+ @Test
+ void whenPlusCharsAndStrings_thenGetExpectedValues() {
+ char c = 'C';
+ assertEquals("C", "" + c);
+
+ char h = 'H'; // the value is 72
+ char i = 'i'; // the value is 105
+ assertEquals("Hi", "" + h + i);
+ assertEquals("Hi", h + "" + i);
+ assertEquals("177", h + i + "");
+ }
+
+ @Test
+ void whenStringChars_thenGetCharArray() {
+ char h = 'h';
+ char e = 'e';
+ char l = 'l';
+ char o = 'o';
+
+ String hello = "hello";
+ assertEquals(h, hello.charAt(0));
+ assertEquals(e, hello.charAt(1));
+ assertEquals(l, hello.charAt(2));
+ assertEquals(l, hello.charAt(3));
+ assertEquals(o, hello.charAt(4));
+
+ char[] chars = new char[] { h, e, l, l, o };
+ char[] charsFromString = hello.toCharArray();
+ assertArrayEquals(chars, charsFromString);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-3/pom.xml b/core-java-modules/core-java-collections-3/pom.xml
index 6ef8e3c81afc..373dc9db14e4 100644
--- a/core-java-modules/core-java-collections-3/pom.xml
+++ b/core-java-modules/core-java-collections-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-3
- 0.1.0-SNAPSHOT
core-java-collections-3
jar
diff --git a/core-java-modules/core-java-collections-4/pom.xml b/core-java-modules/core-java-collections-4/pom.xml
index e88d5a6740e5..1a59411ecbe9 100644
--- a/core-java-modules/core-java-collections-4/pom.xml
+++ b/core-java-modules/core-java-collections-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-4
- 0.1.0-SNAPSHOT
core-java-collections-4
jar
diff --git a/core-java-modules/core-java-collections-5/pom.xml b/core-java-modules/core-java-collections-5/pom.xml
index 67c9f7120cce..84f62c696d07 100644
--- a/core-java-modules/core-java-collections-5/pom.xml
+++ b/core-java-modules/core-java-collections-5/pom.xml
@@ -1,11 +1,22 @@
-
4.0.0
core-java-collections-5
- 0.0.1-SNAPSHOT
core-java-collections-5
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ 9
+
+
+
+
jar
@@ -55,4 +66,5 @@
0.9.38
1.36
+
diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/arrayandlistperformance/ArrayAndArrayListPerformance.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/arrayandlistperformance/ArrayAndArrayListPerformance.java
new file mode 100644
index 000000000000..f8a113ff6997
--- /dev/null
+++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/arrayandlistperformance/ArrayAndArrayListPerformance.java
@@ -0,0 +1,77 @@
+package com.baeldung.arrayandlistperformance;
+
+import org.openjdk.jmh.annotations.*;
+import org.openjdk.jmh.infra.Blackhole;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.concurrent.TimeUnit;
+
+@State(Scope.Benchmark)
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+public class ArrayAndArrayListPerformance {
+
+ public static void main(String[] args) throws Exception {
+ org.openjdk.jmh.runner.Runner runner = new org.openjdk.jmh.runner.Runner(new OptionsBuilder().include(ArrayAndArrayListPerformance.class.getSimpleName()).forks(1).build());
+ runner.run();
+ }
+ public static Integer[] array = Collections.nCopies(1000000, 1).toArray(new Integer[0]);
+ public static ArrayList list = new ArrayList(
+ Arrays.asList(array));
+ @Benchmark
+ public Integer[] arrayCreation() {
+ return new Integer[1000000];
+ }
+
+ @Benchmark
+ public ArrayList arrayListCreation() {
+ return new ArrayList<>(1000000);
+ }
+
+ @Benchmark
+ public Integer[] arrayItemsSetting() {
+ for (int i = 0; i < 1000000; i++) {
+ array[i] = i;
+ }
+ return array;
+ }
+
+ @Benchmark
+ public ArrayList arrayListItemsSetting() {
+ for (int i = 0; i < 1000000; i++) {
+ list.add(i);
+ }
+ return list;
+ }
+
+ @Benchmark
+ public void arrayItemsRetrieval(Blackhole blackhole) {
+ for (int i = 0; i < 1000000; i++) {
+ int item = array[i];
+ blackhole.consume(item);
+ }
+ }
+
+ @Benchmark
+ public void arrayListItemsRetrieval(Blackhole blackhole) {
+ for (int i = 0; i < 1000000; i++) {
+ int item = list.get(i);
+ blackhole.consume(item);
+ }
+ }
+
+ @Benchmark
+ public void arrayCloning(Blackhole blackhole) {
+ Integer[] newArray = array.clone();
+ blackhole.consume(newArray);
+ }
+
+ @Benchmark
+ public void arrayListCloning(Blackhole blackhole) {
+ ArrayList newList = new ArrayList<>(list);
+ blackhole.consume(newList);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/CustomMovieIterator.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/CustomMovieIterator.java
new file mode 100644
index 000000000000..a1e34dd4c58b
--- /dev/null
+++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/CustomMovieIterator.java
@@ -0,0 +1,39 @@
+package com.baeldung.customiterators;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+public class CustomMovieIterator implements Iterator {
+ private int currentIndex;
+ private final List list;
+
+ public CustomMovieIterator(List list) {
+ this.list = list;
+ this.currentIndex = 0;
+ }
+
+ @Override
+ public boolean hasNext() {
+ while (currentIndex < list.size()) {
+ Movie currentMovie = list.get(currentIndex);
+ if (isMovieEligible(currentMovie)) {
+ return true;
+ }
+ currentIndex++;
+ }
+ return false;
+ }
+
+ @Override
+ public Movie next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+ return list.get(currentIndex++);
+ }
+
+ private boolean isMovieEligible(Movie movie) {
+ return movie.getRating() >= 8;
+ }
+}
diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/Movie.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/Movie.java
new file mode 100644
index 000000000000..e1188e69bfef
--- /dev/null
+++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/Movie.java
@@ -0,0 +1,37 @@
+package com.baeldung.customiterators;
+
+public class Movie {
+ private String name;
+ private String director;
+ private float rating;
+
+ public Movie(String name, String director, float rating) {
+ this.name = name;
+ this.director = director;
+ this.rating = rating;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDirector() {
+ return director;
+ }
+
+ public void setDirector(String director) {
+ this.director = director;
+ }
+
+ public float getRating() {
+ return rating;
+ }
+
+ public void setRating(float rating) {
+ this.rating = rating;
+ }
+}
diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/MyList.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/MyList.java
new file mode 100644
index 000000000000..a0b2f4a9435d
--- /dev/null
+++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/MyList.java
@@ -0,0 +1,139 @@
+package com.baeldung.customiterators;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+
+/**
+ * Please note that this class has been added for representation purposes of how a custom collection and its iterator would be.
+ * This does not have working code.
+ */
+public class MyList implements List {
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return false;
+ }
+
+ @Override
+ public boolean contains(Object o) {
+ return false;
+ }
+
+ @Override
+ public boolean add(E e) {
+ return false;
+ }
+
+ @Override
+ public boolean remove(Object o) {
+ return false;
+ }
+
+ @Override
+ public Iterator iterator() {
+ return new MyListIterator();
+ }
+
+ private class MyListIterator implements Iterator {
+ @Override
+ public boolean hasNext() {
+ return false;
+ }
+
+ @Override
+ public E next() {
+ return null;
+ }
+ }
+
+ @Override
+ public Object[] toArray() {
+ return new Object[0];
+ }
+
+ @Override
+ public T[] toArray(T[] a) {
+ return null;
+ }
+
+ @Override
+ public boolean containsAll(Collection> c) {
+ return false;
+ }
+
+ @Override
+ public boolean addAll(Collection extends E> c) {
+ return false;
+ }
+
+ @Override
+ public boolean addAll(int index, Collection extends E> c) {
+ return false;
+ }
+
+ @Override
+ public boolean removeAll(Collection> c) {
+ return false;
+ }
+
+ @Override
+ public boolean retainAll(Collection> c) {
+ return false;
+ }
+
+ @Override
+ public void clear() {
+
+ }
+
+ @Override
+ public E get(int index) {
+ return null;
+ }
+
+ @Override
+ public E set(int index, E element) {
+ return null;
+ }
+
+ @Override
+ public void add(int index, E element) {
+
+ }
+
+ @Override
+ public E remove(int index) {
+ return null;
+ }
+
+ @Override
+ public int indexOf(Object o) {
+ return 0;
+ }
+
+ @Override
+ public int lastIndexOf(Object o) {
+ return 0;
+ }
+
+ @Override
+ public ListIterator listIterator() {
+ return null;
+ }
+
+ @Override
+ public ListIterator listIterator(int index) {
+ return null;
+ }
+
+ @Override
+ public List subList(int fromIndex, int toIndex) {
+ return null;
+ }
+}
diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/PalindromIterator.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/PalindromIterator.java
new file mode 100644
index 000000000000..50263f52ecfc
--- /dev/null
+++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/customiterators/PalindromIterator.java
@@ -0,0 +1,44 @@
+package com.baeldung.customiterators;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+public class PalindromIterator implements Iterator {
+ private final List list;
+ private int currentIndex;
+
+ public PalindromIterator(List list) {
+ this.list = list;
+ this.currentIndex = 0;
+ }
+
+ @Override
+ public boolean hasNext() {
+ while (currentIndex < list.size()) {
+ String currString = list.get(currentIndex);
+ if (isPalindrome(currString)) {
+ return true;
+ }
+ currentIndex++;
+ }
+ return false;
+ }
+
+ @Override
+ public String next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+ return list.get(currentIndex++);
+ }
+
+ private boolean isPalindrome(String input) {
+ for (int i = 0; i < input.length() / 2; i++) {
+ if (input.charAt(i) != input.charAt(input.length() - i - 1)) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/customiterators/IteratorsUnitTest.java b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/customiterators/IteratorsUnitTest.java
new file mode 100644
index 000000000000..04389eb1d2b8
--- /dev/null
+++ b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/customiterators/IteratorsUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.customiterators;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Iterator;
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class IteratorsUnitTest {
+ @Test
+ public void givenListOfStrings_whenIteratedWithDefaultIterator() {
+ List listOfStrings = List.of("hello", "world", "this", "is", "a", "test");
+ Iterator iterator = listOfStrings.iterator();
+ Assert.assertTrue(iterator.hasNext());
+ assertEquals(iterator.next(), "hello");
+ }
+
+ @Test
+ public void givenListOfStrings_whenPalindromIterator_thenOnlyPalindromes() {
+ List listOfStrings = List.of("oslo", "madam", "car", "deed", "wow", "test");
+ PalindromIterator palindromIterator = new PalindromIterator(listOfStrings);
+ int count = 0;
+ while (palindromIterator.hasNext()) {
+ palindromIterator.next();
+ count++;
+ }
+ assertEquals(count, 3);
+ }
+
+ @Test
+ public void givenMovieList_whenMovieIteratorUsed_thenOnlyHighRatedMovies() {
+ List movies = getMovies();
+ CustomMovieIterator movieIterator = new CustomMovieIterator(movies);
+ int count = 0;
+ while (movieIterator.hasNext()) {
+ movieIterator.next();
+ count++;
+ }
+ assertEquals(4, movies.size());
+ assertEquals(2, count);
+ }
+
+ private List getMovies() {
+ Movie movie1 = new Movie("The Dark Knight", "Nolan", 10);
+ Movie movie2 = new Movie("Avatar", "Cameron", 9);
+ Movie movie3 = new Movie("Tenet", "Nolan", 7);
+ Movie movie4 = new Movie("Extraction", "Hargrave", 5);
+ return List.of(movie1, movie2, movie3, movie4);
+ }
+
+}
diff --git a/core-java-modules/core-java-collections-array-list/pom.xml b/core-java-modules/core-java-collections-array-list/pom.xml
index e3a115854cbd..ee0b102bb05a 100644
--- a/core-java-modules/core-java-collections-array-list/pom.xml
+++ b/core-java-modules/core-java-collections-array-list/pom.xml
@@ -4,7 +4,29 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-array-list
- 0.1.0-SNAPSHOT
+ core-java-collections-array-list
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ org.apache.commons
+ commons-collections4
+ ${commons-collections4.version}
+
+
+ com.google.guava
+ guava
+ 31.1-jre
+ test
+
+
+
@@ -27,32 +49,11 @@
+
16
16
3.0.0-M3
- core-java-collections-array-list
- jar
-
-
- com.baeldung.core-java-modules
- core-java-modules
- 0.0.1-SNAPSHOT
-
-
-
-
- org.apache.commons
- commons-collections4
- ${commons-collections4.version}
-
-
- com.google.guava
- guava
- 31.1-jre
- test
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-conversions-2/pom.xml b/core-java-modules/core-java-collections-conversions-2/pom.xml
index f6775a7a4226..8cd0a6932b56 100644
--- a/core-java-modules/core-java-collections-conversions-2/pom.xml
+++ b/core-java-modules/core-java-collections-conversions-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-conversions-2
- 0.1.0-SNAPSHOT
core-java-collections-conversions-2
jar
diff --git a/core-java-modules/core-java-collections-conversions/pom.xml b/core-java-modules/core-java-collections-conversions/pom.xml
index 08a452da510f..78e9847c0aba 100644
--- a/core-java-modules/core-java-collections-conversions/pom.xml
+++ b/core-java-modules/core-java-collections-conversions/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-conversions
- 0.1.0-SNAPSHOT
core-java-collections-conversions
jar
diff --git a/core-java-modules/core-java-collections-list-2/pom.xml b/core-java-modules/core-java-collections-list-2/pom.xml
index 59ab8c5f27eb..a305cdffc8cc 100644
--- a/core-java-modules/core-java-collections-list-2/pom.xml
+++ b/core-java-modules/core-java-collections-list-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-list-2
- 0.1.0-SNAPSHOT
core-java-collections-list-2
jar
diff --git a/core-java-modules/core-java-collections-list-3/pom.xml b/core-java-modules/core-java-collections-list-3/pom.xml
index 912204bcc67e..f01fe1f3b9ae 100644
--- a/core-java-modules/core-java-collections-list-3/pom.xml
+++ b/core-java-modules/core-java-collections-list-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-list-3
- 0.1.0-SNAPSHOT
core-java-collections-list-3
jar
diff --git a/core-java-modules/core-java-collections-list-4/pom.xml b/core-java-modules/core-java-collections-list-4/pom.xml
index 964ea4f5a16b..6d068298ec3e 100644
--- a/core-java-modules/core-java-collections-list-4/pom.xml
+++ b/core-java-modules/core-java-collections-list-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-list-4
- 0.1.0-SNAPSHOT
core-java-collections-list-4
jar
diff --git a/core-java-modules/core-java-collections-list-5/pom.xml b/core-java-modules/core-java-collections-list-5/pom.xml
index 0807f7612c27..2269cce9fd13 100644
--- a/core-java-modules/core-java-collections-list-5/pom.xml
+++ b/core-java-modules/core-java-collections-list-5/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-list-5
- 0.1.0-SNAPSHOT
core-java-collections-list-5
jar
@@ -15,6 +14,11 @@
+
+ org.openjdk.jmh
+ jmh-core
+ 1.36
+
commons-lang
commons-lang
@@ -25,11 +29,24 @@
commons-lang3
${commons-lang3.version}
+
+
+ org.apache.commons
+ commons-collections4
+ 4.4
+
+
+
+ org.projectlombok
+ lombok
+ 1.18.26
+ provided
+
+ 1.21
2.2
3.12.0
-
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/arrayandlistperformance/ArrayAndArrayListPerformance.java b/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/arrayandlistperformance/ArrayAndArrayListPerformance.java
new file mode 100644
index 000000000000..59540c69b928
--- /dev/null
+++ b/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/arrayandlistperformance/ArrayAndArrayListPerformance.java
@@ -0,0 +1,77 @@
+package com.baeldung.arrayandlistperformance;
+
+import org.openjdk.jmh.annotations.*;
+import org.openjdk.jmh.infra.Blackhole;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.concurrent.TimeUnit;
+
+@State(Scope.Benchmark)
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+public class ArrayAndArrayListPerformance {
+
+ public static void main(String[] args) throws Exception {
+ org.openjdk.jmh.runner.Runner runner = new org.openjdk.jmh.runner.Runner(new OptionsBuilder().include(ArrayAndArrayListPerformance.class.getSimpleName()).forks(1).build());
+ runner.run();
+ }
+ public static Integer[] array = Collections.nCopies(256, 1).toArray(new Integer[0]);
+ public static ArrayList list = new ArrayList(
+ Arrays.asList(array));
+ @Benchmark
+ public Integer[] arrayCreation() {
+ return new Integer[256];
+ }
+
+ @Benchmark
+ public ArrayList arrayListCreation() {
+ return new ArrayList<>(256);
+ }
+
+ @Benchmark
+ public Integer[] arrayItemsSetting() {
+ for (int i = 0; i < 256; i++) {
+ array[i] = i;
+ }
+ return array;
+ }
+
+ @Benchmark
+ public ArrayList arrayListItemsSetting() {
+ for (int i = 0; i < 256; i++) {
+ list.set(i,i);
+ }
+ return list;
+ }
+
+ @Benchmark
+ public void arrayItemsRetrieval(Blackhole blackhole) {
+ for (int i = 0; i < 256; i++) {
+ int item = array[i];
+ blackhole.consume(item);
+ }
+ }
+
+ @Benchmark
+ public void arrayListItemsRetrieval(Blackhole blackhole) {
+ for (int i = 0; i < 256; i++) {
+ int item = list.get(i);
+ blackhole.consume(item);
+ }
+ }
+
+ @Benchmark
+ public void arrayCloning(Blackhole blackhole) {
+ Integer[] newArray = array.clone();
+ blackhole.consume(newArray);
+ }
+
+ @Benchmark
+ public void arrayListCloning(Blackhole blackhole) {
+ ArrayList newList = new ArrayList<>(list);
+ blackhole.consume(newList);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/list/Country.java b/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/list/Country.java
new file mode 100644
index 000000000000..7ca7a4f185af
--- /dev/null
+++ b/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/list/Country.java
@@ -0,0 +1,11 @@
+package com.baeldung.list;
+
+import lombok.Data;
+
+@Data
+public class Country {
+
+ private final String name;
+ private final String language;
+
+}
diff --git a/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/ListContainsElementFromOtherListTest.java b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/ListContainsElementFromOtherListTest.java
new file mode 100644
index 000000000000..4ce7c4428217
--- /dev/null
+++ b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/ListContainsElementFromOtherListTest.java
@@ -0,0 +1,68 @@
+package com.baeldung.java.list;
+
+import static java.util.stream.Collectors.toSet;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.commons.collections4.CollectionUtils;
+import org.junit.Test;
+
+import com.baeldung.list.Country;
+
+public class ListContainsElementFromOtherListTest {
+
+ final private List listOfLetters = Arrays.asList("a", "b", "c", "d");
+ final private List listOfLettersWithOverlap = Arrays.asList("d", "e", "f", "g");
+ final private List listOfCities = Arrays.asList("London", "Berlin", "Paris", "Brussels");
+
+ @Test
+ public void givenValuesToCompare_whenUsingCollectionsDisjoint_thenDetectElementsInTwoLists() {
+ boolean shouldBeTrue = !Collections.disjoint(listOfLetters, listOfLettersWithOverlap);
+ assertTrue(shouldBeTrue);
+
+ boolean shouldBeFalse = !Collections.disjoint(listOfLetters, listOfCities);
+ assertFalse(shouldBeFalse);
+ }
+
+ @Test
+ public void givenValuesToCompare_whenUsingStreams_thenDetectElementsInTwoLists() {
+ boolean shouldBeTrue = listOfLetters.stream()
+ .anyMatch(listOfLettersWithOverlap::contains);
+ assertTrue(shouldBeTrue);
+
+ boolean shouldBeFalse = listOfLetters.stream()
+ .anyMatch(listOfCities::contains);
+ assertFalse(shouldBeFalse);
+ }
+
+ @Test
+ public void givenValuesToCompare_whenUsingApacheCollectionUtils_thenDetectElementsInTwoLists() {
+ boolean shouldBeTrue = CollectionUtils.containsAny(listOfLetters, listOfLettersWithOverlap);
+ assertTrue(shouldBeTrue);
+
+ boolean shouldBeFalse = CollectionUtils.containsAny(listOfLetters, listOfCities);
+ assertFalse(shouldBeFalse);
+ }
+
+ @Test
+ public void givenPropertiesInObjectsToCompare_whenUsingStreams_thenDetectElementsInTwoLists() {
+ Country france = new Country("France", "French");
+ Country mexico = new Country("Mexico", "Spanish");
+ Country spain = new Country("Spain", "Spanish");
+ List franceAndMexico = Arrays.asList(france, mexico);
+ List franceAndSpain = Arrays.asList(france, spain);
+
+ boolean shouldBeTrue = franceAndMexico.stream()
+ .map(Country::getLanguage)
+ .anyMatch(franceAndSpain.stream()
+ .map(Country::getLanguage)
+ .collect(toSet())::contains);
+
+ assertTrue(shouldBeTrue);
+ }
+
+}
diff --git a/core-java-modules/core-java-collections-list/pom.xml b/core-java-modules/core-java-collections-list/pom.xml
index 0cc8828a0d9a..94abb334e028 100644
--- a/core-java-modules/core-java-collections-list/pom.xml
+++ b/core-java-modules/core-java-collections-list/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-list
- 0.1.0-SNAPSHOT
core-java-collections-list
jar
diff --git a/core-java-modules/core-java-collections-maps-2/pom.xml b/core-java-modules/core-java-collections-maps-2/pom.xml
index 1e526ef8922d..15ca688ad24f 100644
--- a/core-java-modules/core-java-collections-maps-2/pom.xml
+++ b/core-java-modules/core-java-collections-maps-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-maps-2
- 0.1.0-SNAPSHOT
core-java-collections-maps-2
jar
diff --git a/core-java-modules/core-java-collections-maps-3/pom.xml b/core-java-modules/core-java-collections-maps-3/pom.xml
index a5bb6dc33837..98a0d18fe924 100644
--- a/core-java-modules/core-java-collections-maps-3/pom.xml
+++ b/core-java-modules/core-java-collections-maps-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-maps-3
- 0.1.0-SNAPSHOT
core-java-collections-maps-3
jar
diff --git a/core-java-modules/core-java-collections-maps-4/pom.xml b/core-java-modules/core-java-collections-maps-4/pom.xml
index a85e2cde2a60..f1734b737906 100644
--- a/core-java-modules/core-java-collections-maps-4/pom.xml
+++ b/core-java-modules/core-java-collections-maps-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-maps-4
- 0.1.0-SNAPSHOT
core-java-collections-maps-4
jar
diff --git a/core-java-modules/core-java-collections-maps-5/pom.xml b/core-java-modules/core-java-collections-maps-5/pom.xml
index f12e044b2305..593ec5a8f687 100644
--- a/core-java-modules/core-java-collections-maps-5/pom.xml
+++ b/core-java-modules/core-java-collections-maps-5/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-maps-5
- 0.1.0-SNAPSHOT
core-java-collections-maps-5
jar
diff --git a/core-java-modules/core-java-collections-maps-6/pom.xml b/core-java-modules/core-java-collections-maps-6/pom.xml
index 9910d086914d..8c35dcee6ee4 100644
--- a/core-java-modules/core-java-collections-maps-6/pom.xml
+++ b/core-java-modules/core-java-collections-maps-6/pom.xml
@@ -1,20 +1,54 @@
+ 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">
+ 4.0.0
core-java-collections-maps-6
- 0.1.0-SNAPSHOT
core-java-collections-maps-6
jar
+
core-java-modules
com.baeldung.core-java-modules
0.0.1-SNAPSHOT
- 4.0.0
5.2.5.RELEASE
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ 2.13.1
+
+
+ org.openjdk.jmh
+ jmh-core
+ 1.36
+
+
+ com.google.code.gson
+ gson
+ 2.8.9
+
+
+ org.json
+ json
+ 20230227
+
+
+ junit
+ junit
+ 4.13.1
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter
+ 5.8.1
+ test
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/maptojson/MapToJsonUnitTest.java b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/maptojson/MapToJsonUnitTest.java
new file mode 100644
index 000000000000..d9b13f4f4ac4
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/maptojson/MapToJsonUnitTest.java
@@ -0,0 +1,56 @@
+package com.baeldung.maptojson;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.reflect.TypeToken;
+import org.json.JSONObject;
+import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Map;
+
+public class MapToJsonUnitTest {
+String originalJsonData = "{\"CS\":\"Post1\",\"Linux\":\"Post1\",\"Kotlin\":\"Post1\"}";
+
+@Test
+public void given_HashMapData_whenUsingJackson_thenConvertToJson() throws JsonProcessingException {
+ Map data = new HashMap();
+ data.put("CS", "Post1");
+ data.put("Linux", "Post1");
+ data.put("Kotlin", "Post1");
+ ObjectMapper objectMapper = new ObjectMapper();
+ String jacksonData = objectMapper.writeValueAsString(data);
+ Assertions.assertEquals(jacksonData,originalJsonData);
+}
+
+@Test
+public void given_HashMapData_whenUsingGson_thenConvertToJson() {
+ Map data = new HashMap<>();
+ data.put("CS", "Post1");
+ data.put("Linux", "Post1");
+ data.put("Kotlin", "Post1");
+ Gson gson = new Gson();
+ Type typeObject = new TypeToken() {
+ }.getType();
+ String gsonData = gson.toJson(data, typeObject);
+ Assertions.assertEquals(gsonData,originalJsonData);
+}
+
+@Test
+public void given_HashMapData_whenOrgJson_thenConvertToJsonUsing() {
+ Map data = new HashMap<>();
+ data.put("CS", "Post1");
+ data.put("Linux", "Post1");
+ data.put("Kotlin", "Post1");
+ JSONObject jsonObject = new JSONObject(data);
+ String orgJsonData = jsonObject.toString();
+ Assertions.assertEquals(orgJsonData,originalJsonData);
+}
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml
index 3a1bf0d8a1a9..5e19117e0840 100644
--- a/core-java-modules/core-java-collections-maps/pom.xml
+++ b/core-java-modules/core-java-collections-maps/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-maps
- 0.1.0-SNAPSHOT
core-java-collections-maps
jar
diff --git a/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java
index d308aac7eb06..4ac562ef045f 100644
--- a/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java
+++ b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java
@@ -1,84 +1,126 @@
package com.baeldung.map;
-import com.google.common.collect.ImmutableMap;
-import org.junit.jupiter.api.Test;
+import static org.hamcrest.MatcherAssert.assertThat;
+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.util.AbstractMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.jupiter.api.Assertions.*;
-
-
-public class ImmutableMapUnitTest {
-
- @Test
- public void whenCollectionsUnModifiableMapMethod_thenOriginalCollectionChangesReflectInUnmodifiableMap() {
-
- Map mutableMap = new HashMap<>();
- mutableMap.put("USA", "North America");
-
- Map unmodifiableMap = Collections.unmodifiableMap(mutableMap);
- assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("Canada", "North America"));
-
- mutableMap.remove("USA");
- assertFalse(unmodifiableMap.containsKey("USA"));
-
- mutableMap.put("Mexico", "North America");
- assertTrue(unmodifiableMap.containsKey("Mexico"));
- }
-
- @Test
- @SuppressWarnings("deprecation")
- public void whenGuavaImmutableMapFromCopyOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
-
- Map mutableMap = new HashMap<>();
- mutableMap.put("USA", "North America");
-
- ImmutableMap immutableMap = ImmutableMap.copyOf(mutableMap);
- assertTrue(immutableMap.containsKey("USA"));
-
- assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
-
- mutableMap.remove("USA");
- assertTrue(immutableMap.containsKey("USA"));
-
- mutableMap.put("Mexico", "North America");
- assertFalse(immutableMap.containsKey("Mexico"));
- }
-
- @Test
- @SuppressWarnings("deprecation")
- public void whenGuavaImmutableMapFromBuilderMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
-
- Map mutableMap = new HashMap<>();
- mutableMap.put("USA", "North America");
-
- ImmutableMap immutableMap = ImmutableMap.builder()
- .putAll(mutableMap)
- .put("Costa Rica", "North America")
- .build();
- assertTrue(immutableMap.containsKey("USA"));
- assertTrue(immutableMap.containsKey("Costa Rica"));
-
- assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
-
- mutableMap.remove("USA");
- assertTrue(immutableMap.containsKey("USA"));
-
- mutableMap.put("Mexico", "North America");
- assertFalse(immutableMap.containsKey("Mexico"));
- }
-
- @Test
- @SuppressWarnings("deprecation")
- public void whenGuavaImmutableMapFromOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
-
- ImmutableMap immutableMap = ImmutableMap.of("USA", "North America", "Costa Rica", "North America");
- assertTrue(immutableMap.containsKey("USA"));
- assertTrue(immutableMap.containsKey("Costa Rica"));
-
- assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
- }
-
+import org.hamcrest.collection.IsMapContaining;
+import org.junit.jupiter.api.Test;
+
+import com.google.common.collect.ImmutableMap;
+
+class ImmutableMapUnitTest {
+
+ @Test
+ void whenCollectionsUnModifiableMapMethod_thenOriginalCollectionChangesReflectInUnmodifiableMap() {
+
+ Map mutableMap = new HashMap<>();
+ mutableMap.put("USA", "North America");
+
+ Map unmodifiableMap = Collections.unmodifiableMap(mutableMap);
+ assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("Canada", "North America"));
+
+ mutableMap.remove("USA");
+ assertFalse(unmodifiableMap.containsKey("USA"));
+
+ mutableMap.put("Mexico", "North America");
+ assertTrue(unmodifiableMap.containsKey("Mexico"));
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ void whenGuavaImmutableMapFromCopyOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
+
+ Map mutableMap = new HashMap<>();
+ mutableMap.put("USA", "North America");
+
+ ImmutableMap immutableMap = ImmutableMap.copyOf(mutableMap);
+ assertTrue(immutableMap.containsKey("USA"));
+
+ assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
+
+ mutableMap.remove("USA");
+ assertTrue(immutableMap.containsKey("USA"));
+
+ mutableMap.put("Mexico", "North America");
+ assertFalse(immutableMap.containsKey("Mexico"));
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ void whenGuavaImmutableMapFromBuilderMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
+
+ Map mutableMap = new HashMap<>();
+ mutableMap.put("USA", "North America");
+
+ ImmutableMap immutableMap = ImmutableMap.builder()
+ .putAll(mutableMap)
+ .put("Costa Rica", "North America")
+ .build();
+ assertTrue(immutableMap.containsKey("USA"));
+ assertTrue(immutableMap.containsKey("Costa Rica"));
+
+ assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
+
+ mutableMap.remove("USA");
+ assertTrue(immutableMap.containsKey("USA"));
+
+ mutableMap.put("Mexico", "North America");
+ assertFalse(immutableMap.containsKey("Mexico"));
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ void whenGuavaImmutableMapFromOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
+
+ ImmutableMap immutableMap = ImmutableMap.of("USA", "North America", "Costa Rica", "North America");
+ assertTrue(immutableMap.containsKey("USA"));
+ assertTrue(immutableMap.containsKey("Costa Rica"));
+
+ assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ void givenGuavaImmutableMapFromOfEntriesMethodwhenModifyEntry_thenThrowUnsupportedOperationException() {
+
+ ImmutableMap immutableMap = ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(1, "USA"), new AbstractMap.SimpleEntry<>(2, "Canada"));
+
+ assertThrows(UnsupportedOperationException.class, () -> immutableMap.put(2, "Mexico"));
+ }
+
+ @Test
+ void givenEntrieswhenCreatingGuavaImmutableMapFromOfEntriesMethod_thenCorrect() {
+
+ ImmutableMap immutableMap = ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(1, "USA"));
+
+ assertEquals(1, immutableMap.size());
+ assertThat(immutableMap, IsMapContaining.hasEntry(1, "USA"));
+ }
+
+ @Test
+ void givenGuavaImmutableMapFromOfEntriesMethodwhenEntryKeyExists_thenThrowIllegalArgumentException() {
+
+ assertThrows(IllegalArgumentException.class, () -> ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(1, "USA"), new AbstractMap.SimpleEntry<>(1, "Canada")));
+ }
+
+ @Test
+ void givenGuavaImmutableMapFromOfEntriesMethodwhenEntryKeyIsNull_thenThrowNullPointerException() {
+
+ assertThrows(NullPointerException.class, () -> ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(null, "USA")));
+ }
+
+ @Test
+ void givenGuavaImmutableMapFromOfEntriesMethodwhenEntryValueIsNull_thenThrowNullPointerException() {
+
+ assertThrows(NullPointerException.class, () -> ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(1, null)));
+ }
+
}
diff --git a/core-java-modules/core-java-collections-set-2/pom.xml b/core-java-modules/core-java-collections-set-2/pom.xml
index b1aadb0c22df..680c01d8cabd 100644
--- a/core-java-modules/core-java-collections-set-2/pom.xml
+++ b/core-java-modules/core-java-collections-set-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-set-2
- 0.0.1-SNAPSHOT
core-java-collections-set-2
jar
diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml
index 0b6e324c784e..e130837f1cbc 100644
--- a/core-java-modules/core-java-collections-set/pom.xml
+++ b/core-java-modules/core-java-collections-set/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-set
- 0.1.0-SNAPSHOT
core-java-collections-set
jar
diff --git a/core-java-modules/core-java-collections/pom.xml b/core-java-modules/core-java-collections/pom.xml
index eab7a35584a9..be91492d0645 100644
--- a/core-java-modules/core-java-collections/pom.xml
+++ b/core-java-modules/core-java-collections/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections
- 0.1.0-SNAPSHOT
core-java-collections
jar
diff --git a/core-java-modules/core-java-compiler/README.md b/core-java-modules/core-java-compiler/README.md
new file mode 100644
index 000000000000..2a1e60919461
--- /dev/null
+++ b/core-java-modules/core-java-compiler/README.md
@@ -0,0 +1,6 @@
+## Core Java Compiler
+
+### Relevant Articles:
+
+- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
+- [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error)
diff --git a/core-java-modules/core-java-compiler/pom.xml b/core-java-modules/core-java-compiler/pom.xml
new file mode 100644
index 000000000000..8f2be3f1421a
--- /dev/null
+++ b/core-java-modules/core-java-compiler/pom.xml
@@ -0,0 +1,29 @@
+
+
+ 4.0.0
+ core-java-compiler
+ 0.1.0-SNAPSHOT
+ core-java-compiler
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ com.google.gdata
+ core
+ ${gdata.version}
+
+
+
+
+ 1.47.1
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/javac/Data.java b/core-java-modules/core-java-compiler/src/main/java/com/baeldung/javac/Data.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/javac/Data.java
rename to core-java-modules/core-java-compiler/src/main/java/com/baeldung/javac/Data.java
diff --git a/core-java-modules/core-java/src/main/java/javac-args/arguments b/core-java-modules/core-java-compiler/src/main/java/javac-args/arguments
similarity index 100%
rename from core-java-modules/core-java/src/main/java/javac-args/arguments
rename to core-java-modules/core-java-compiler/src/main/java/javac-args/arguments
diff --git a/core-java-modules/core-java/src/main/java/javac-args/options b/core-java-modules/core-java-compiler/src/main/java/javac-args/options
similarity index 100%
rename from core-java-modules/core-java/src/main/java/javac-args/options
rename to core-java-modules/core-java-compiler/src/main/java/javac-args/options
diff --git a/core-java-modules/core-java/src/main/java/javac-args/types b/core-java-modules/core-java-compiler/src/main/java/javac-args/types
similarity index 100%
rename from core-java-modules/core-java/src/main/java/javac-args/types
rename to core-java-modules/core-java-compiler/src/main/java/javac-args/types
diff --git a/core-java-modules/core-java/src/main/java/javac-args/xlint-ops b/core-java-modules/core-java-compiler/src/main/java/javac-args/xlint-ops
similarity index 100%
rename from core-java-modules/core-java/src/main/java/javac-args/xlint-ops
rename to core-java-modules/core-java-compiler/src/main/java/javac-args/xlint-ops
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/illegalcharacter/IllegalCharacterUnitTest.java b/core-java-modules/core-java-compiler/src/test/java/com/baeldung/illegalcharacter/IllegalCharacterUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/illegalcharacter/IllegalCharacterUnitTest.java
rename to core-java-modules/core-java-compiler/src/test/java/com/baeldung/illegalcharacter/IllegalCharacterUnitTest.java
diff --git a/core-java-modules/core-java/src/test/resources/bom-file.txt b/core-java-modules/core-java-compiler/src/test/resources/bom-file.txt
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/bom-file.txt
rename to core-java-modules/core-java-compiler/src/test/resources/bom-file.txt
diff --git a/core-java-modules/core-java-concurrency-2/pom.xml b/core-java-modules/core-java-concurrency-2/pom.xml
index c61f28a6b3ae..e373c829cc82 100644
--- a/core-java-modules/core-java-concurrency-2/pom.xml
+++ b/core-java-modules/core-java-concurrency-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-2
- 0.1.0-SNAPSHOT
core-java-concurrency-2
jar
diff --git a/core-java-modules/core-java-concurrency-advanced-2/pom.xml b/core-java-modules/core-java-concurrency-advanced-2/pom.xml
index 1f19dc8cca0d..5c96684311e3 100644
--- a/core-java-modules/core-java-concurrency-advanced-2/pom.xml
+++ b/core-java-modules/core-java-concurrency-advanced-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-advanced-2
- 0.1.0-SNAPSHOT
core-java-concurrency-advanced-2
jar
diff --git a/core-java-modules/core-java-concurrency-advanced-3/pom.xml b/core-java-modules/core-java-concurrency-advanced-3/pom.xml
index 49a72112b4e7..7fa859c2d5d1 100644
--- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml
+++ b/core-java-modules/core-java-concurrency-advanced-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-advanced-3
- 0.1.0-SNAPSHOT
core-java-concurrency-advanced-3
jar
diff --git a/core-java-modules/core-java-concurrency-advanced-4/pom.xml b/core-java-modules/core-java-concurrency-advanced-4/pom.xml
index 5bd7ccfa0728..2ffe19b13c8a 100644
--- a/core-java-modules/core-java-concurrency-advanced-4/pom.xml
+++ b/core-java-modules/core-java-concurrency-advanced-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-advanced-4
- 0.1.0-SNAPSHOT
core-java-concurrency-advanced-4
jar
@@ -14,9 +13,6 @@
0.0.1-SNAPSHOT
-
-
-
core-java-concurrency-advanced-4
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Consumer.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Consumer.java
index 9bbcbb923ce6..933a1b5f52d1 100644
--- a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Consumer.java
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Consumer.java
@@ -1,6 +1,9 @@
package com.baeldung.producerconsumer;
+import java.util.logging.Logger;
+
public class Consumer implements Runnable {
+ private static final Logger log = Logger.getLogger(Consumer.class.getCanonicalName());
private final DataQueue dataQueue;
public Consumer(DataQueue dataQueue) {
@@ -14,7 +17,7 @@ public void run() {
public void consume() {
while (dataQueue.runFlag) {
- synchronized (this) {
+ synchronized (dataQueue) {
while (dataQueue.isEmpty() && dataQueue.runFlag) {
try {
dataQueue.waitOnEmpty();
@@ -31,12 +34,13 @@ public void consume() {
useMessage(message);
}
}
- System.out.println("Consumer Stopped");
+ log.info("Consumer Stopped");
}
private void useMessage(Message message) {
if (message != null) {
- System.out.printf("[%s] Consuming Message. Id: %d, Data: %f\n", Thread.currentThread().getName(), message.getId(), message.getData());
+ log.info(String.format("[%s] Consuming Message. Id: %d, Data: %f%n",
+ Thread.currentThread().getName(), message.getId(), message.getData()));
//Sleeping on random time to make it realistic
ThreadUtil.sleep((long) (message.getData() * 100));
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Producer.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Producer.java
index 04ad39f26e00..ca89d0c866f9 100644
--- a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Producer.java
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Producer.java
@@ -1,6 +1,9 @@
package com.baeldung.producerconsumer;
+import java.util.logging.Logger;
+
public class Producer implements Runnable {
+ private static final Logger log = Logger.getLogger(Producer.class.getCanonicalName());
private final DataQueue dataQueue;
private static int idSequence = 0;
@@ -16,7 +19,7 @@ public void run() {
public void produce() {
while (dataQueue.runFlag) {
- synchronized (this) {
+ synchronized (dataQueue) {
while (dataQueue.isFull() && dataQueue.runFlag) {
try {
dataQueue.waitOnFull();
@@ -33,12 +36,13 @@ public void produce() {
dataQueue.notifyAllForEmpty();
}
}
- System.out.println("Producer Stopped");
+ log.info("Producer Stopped");
}
private Message generateMessage() {
- Message message = new Message(++idSequence, Math.random());
- System.out.printf("[%s] Generated Message. Id: %d, Data: %f\n", Thread.currentThread().getName(), message.getId(), message.getData());
+ Message message = new Message(incrementAndGetId(), Math.random());
+ log.info(String.format("[%s] Generated Message. Id: %d, Data: %f%n",
+ Thread.currentThread().getName(), message.getId(), message.getData()));
//Sleeping on random time to make it realistic
ThreadUtil.sleep((long) (message.getData() * 100));
@@ -46,6 +50,10 @@ private Message generateMessage() {
return message;
}
+ private static int incrementAndGetId() {
+ return ++idSequence;
+ }
+
public void stop() {
dataQueue.runFlag = false;
dataQueue.notifyAllForFull();
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/SimpleProducerConsumerDemonstrator.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/SimpleProducerConsumerDemonstrator.java
index f1f6e1cc9cbb..500dc9ca073e 100644
--- a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/SimpleProducerConsumerDemonstrator.java
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/SimpleProducerConsumerDemonstrator.java
@@ -2,10 +2,12 @@
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
+import java.util.logging.Logger;
import static com.baeldung.producerconsumer.ThreadUtil.sleep;
public class SimpleProducerConsumerDemonstrator {
+ private static final Logger log = Logger.getLogger(SimpleProducerConsumerDemonstrator.class.getCanonicalName());
BlockingQueue blockingQueue = new LinkedBlockingDeque<>(5);
private void produce() {
@@ -17,7 +19,7 @@ private void produce() {
e.printStackTrace();
break;
}
- System.out.printf("[%s] Value produced: %f\n", Thread.currentThread().getName(), value);
+ log.info(String.format("[%s] Value produced: %f%n", Thread.currentThread().getName(), value));
}
}
@@ -31,7 +33,7 @@ private void consume() {
break;
}
// Consume value
- System.out.printf("[%s] Value consumed: %f\n", Thread.currentThread().getName(), value);
+ log.info(String.format("[%s] Value consumed: %f%n", Thread.currentThread().getName(), value));
}
}
diff --git a/core-java-modules/core-java-concurrency-advanced/pom.xml b/core-java-modules/core-java-concurrency-advanced/pom.xml
index 3c726e128406..18cfc5371ca9 100644
--- a/core-java-modules/core-java-concurrency-advanced/pom.xml
+++ b/core-java-modules/core-java-concurrency-advanced/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-advanced
- 0.1.0-SNAPSHOT
core-java-concurrency-advanced
jar
diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java
index 389e25719bdb..d23f1faa691d 100644
--- a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java
+++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java
@@ -1,9 +1,14 @@
package com.baeldung.concurrent.countdownlatch;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class Worker implements Runnable {
+
+ private static Logger log = LoggerFactory.getLogger(Worker.class);
private final List outputScraper;
private final CountDownLatch countDownLatch;
@@ -15,7 +20,7 @@ public class Worker implements Runnable {
@Override
public void run() {
// Do some work
- System.out.println("Doing some logic");
+ log.debug("Doing some logic");
outputScraper.add("Counted down");
countDownLatch.countDown();
}
diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java
index c022c0208579..44f84ad77c3c 100644
--- a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java
+++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java
@@ -1,8 +1,13 @@
package com.baeldung.concurrent.phaser;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.util.concurrent.Phaser;
class LongRunningAction implements Runnable {
+
+ private static Logger log = LoggerFactory.getLogger(LongRunningAction.class);
private String threadName;
private Phaser ph;
@@ -14,18 +19,18 @@ class LongRunningAction implements Runnable {
@Override
public void run() {
- System.out.println("This is phase " + ph.getPhase());
- System.out.println("Thread " + threadName + " before long running action");
+ log.info("This is phase {}", ph.getPhase());
+ log.info("Thread {} before long running action", threadName);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
-
- System.out.println("Thread " + threadName + " action completed and waiting for others");
+
+ log.debug("Thread {} action completed and waiting for others", threadName);
ph.arriveAndAwaitAdvance();
- System.out.println("Thread " + threadName + " proceeding in phase " + ph.getPhase());
+ log.debug("Thread {} proceeding in phase {}", threadName, ph.getPhase());
ph.arriveAndDeregister();
}
diff --git a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java
index 88c18b51490a..384a1837c133 100644
--- a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java
+++ b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java
@@ -4,6 +4,9 @@
import org.junit.Test;
import org.junit.runners.MethodSorters;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
@@ -13,6 +16,8 @@
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PhaserUnitTest {
+ private static Logger log = LoggerFactory.getLogger(PhaserUnitTest.class);
+
@Test
public void givenPhaser_whenCoordinateWorksBetweenThreads_thenShouldCoordinateBetweenMultiplePhases() {
//given
@@ -26,19 +31,19 @@ public void givenPhaser_whenCoordinateWorksBetweenThreads_thenShouldCoordinateBe
executorService.submit(new LongRunningAction("thread-3", ph));
//then
- System.out.println("Thread " + Thread.currentThread().getName() + " waiting for others");
+ log.debug("Thread {} waiting for others", Thread.currentThread().getName());
ph.arriveAndAwaitAdvance();
- System.out.println("Thread " + Thread.currentThread().getName() + " proceeding in phase " + ph.getPhase());
+ log.debug("Thread {} proceeding in phase {}", Thread.currentThread().getName(), ph.getPhase());
assertEquals(1, ph.getPhase());
//and
executorService.submit(new LongRunningAction("thread-4", ph));
executorService.submit(new LongRunningAction("thread-5", ph));
-
- System.out.println("Thread " + Thread.currentThread().getName() + " waiting for others");
+
+ log.debug("Thread {} waiting for others", Thread.currentThread().getName());
ph.arriveAndAwaitAdvance();
- System.out.println("Thread " + Thread.currentThread().getName() + " proceeding in phase " + ph.getPhase());
+ log.debug("Thread {} proceeding in phase {}", Thread.currentThread().getName(), ph.getPhase());
assertEquals(2, ph.getPhase());
diff --git a/core-java-modules/core-java/src/main/resources/logback.xml b/core-java-modules/core-java-concurrency-advanced/src/test/resources/logback-test.xml
similarity index 100%
rename from core-java-modules/core-java/src/main/resources/logback.xml
rename to core-java-modules/core-java-concurrency-advanced/src/test/resources/logback-test.xml
diff --git a/core-java-modules/core-java-concurrency-basic-2/pom.xml b/core-java-modules/core-java-concurrency-basic-2/pom.xml
index 9ca12da7fb9c..0cdfd68f03e8 100644
--- a/core-java-modules/core-java-concurrency-basic-2/pom.xml
+++ b/core-java-modules/core-java-concurrency-basic-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-basic-2
- 0.1.0-SNAPSHOT
core-java-concurrency-basic-2
jar
diff --git a/core-java-modules/core-java-concurrency-basic-3/README.md b/core-java-modules/core-java-concurrency-basic-3/README.md
index 46480c6b01e7..da148599b0c1 100644
--- a/core-java-modules/core-java-concurrency-basic-3/README.md
+++ b/core-java-modules/core-java-concurrency-basic-3/README.md
@@ -6,4 +6,5 @@ This module contains articles about basic Java concurrency.
- [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception)
- [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)
- [[<-- Prev]](../core-java-concurrency-basic-2)
diff --git a/core-java-modules/core-java-concurrency-basic-3/pom.xml b/core-java-modules/core-java-concurrency-basic-3/pom.xml
index 728987755064..1983d3c163ab 100644
--- a/core-java-modules/core-java-concurrency-basic-3/pom.xml
+++ b/core-java-modules/core-java-concurrency-basic-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-basic-3
- 0.1.0-SNAPSHOT
core-java-concurrency-basic-3
jar
@@ -14,6 +13,15 @@
0.0.1-SNAPSHOT
+
+
+ org.awaitility
+ awaitility
+ ${awaitility.version}
+ test
+
+
+
core-java-concurrency-basic-3
@@ -28,12 +36,4 @@
4.2.0
-
-
- org.awaitility
- awaitility
- ${awaitility.version}
- test
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/NonBlockingExample.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/NonBlockingExample.java
new file mode 100644
index 000000000000..b97f7d0dee90
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/NonBlockingExample.java
@@ -0,0 +1,17 @@
+package com.baeldung.concurrent.completablefuture;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.CompletableFuture;
+
+public class NonBlockingExample {
+
+ private static final Logger logger = LoggerFactory.getLogger(NonBlockingExample.class);
+
+ public static void main(String[] args) {
+ CompletableFuture.supplyAsync(() -> "Baeldung")
+ .thenApply(String::length)
+ .thenAccept(s -> logger.info(String.valueOf(s)));
+ }
+}
diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java
index c437b08b34af..4a400f7beb49 100644
--- a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java
+++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java
@@ -20,7 +20,8 @@ public class RequestProcessorUnitTest {
void whenWaitingWithThreadSleep_thenStatusIsDone() throws InterruptedException {
String requestId = requestProcessor.processRequest();
- Thread.sleep(2000);
+ //The sleep value should be greater than the maximum time the request takes to complete
+ Thread.sleep(2010);
assertEquals("DONE", requestProcessor.getStatus(requestId));
}
@@ -31,7 +32,8 @@ void whenWaitingWithAwaitility_thenStatusIsDone() {
String requestId = requestProcessor.processRequest();
Awaitility.await()
- .atMost(2, TimeUnit.SECONDS)
+ //The timeout value should exceed the maximum time the request takes to complete, for the time amount of a poll (500 ms)
+ .atMost(2501, TimeUnit.MILLISECONDS)
.pollDelay(500, TimeUnit.MILLISECONDS)
.until(() -> requestProcessor.getStatus(requestId), not(equalTo("PROCESSING")));
diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/BlockingUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/BlockingUnitTest.java
new file mode 100644
index 000000000000..75d8d73c2ff8
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/BlockingUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.concurrent.completablefuture;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class BlockingUnitTest {
+
+ @Test
+ void givenCompletableFuture_whenGet_thenReturnResult()
+ throws ExecutionException, InterruptedException {
+ CompletableFuture completableFuture = CompletableFuture
+ .supplyAsync(() -> "Baeldung")
+ .thenApply(String::toUpperCase);
+
+ assertEquals("BAELDUNG", completableFuture.get());
+ }
+
+ @Test
+ void givenCompletableFuture_whenJoin_thenReturnResult() {
+ CompletableFuture completableFuture = CompletableFuture
+ .supplyAsync(() -> "Blocking")
+ .thenApply(s -> s + " Operation")
+ .thenApply(String::toLowerCase);
+
+ assertEquals("blocking operation", completableFuture.join());
+ }
+}
diff --git a/core-java-modules/core-java-concurrency-basic/pom.xml b/core-java-modules/core-java-concurrency-basic/pom.xml
index 1e3157291a93..36d59f254ca1 100644
--- a/core-java-modules/core-java-concurrency-basic/pom.xml
+++ b/core-java-modules/core-java-concurrency-basic/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-basic
- 0.1.0-SNAPSHOT
core-java-concurrency-basic
jar
diff --git a/core-java-modules/core-java-concurrency-collections-2/README.md b/core-java-modules/core-java-concurrency-collections-2/README.md
index c812ed4284a6..2d65cf88e779 100644
--- a/core-java-modules/core-java-concurrency-collections-2/README.md
+++ b/core-java-modules/core-java-concurrency-collections-2/README.md
@@ -4,4 +4,5 @@
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
- [Java Concurrent HashSet Equivalent to ConcurrentHashMap](https://www.baeldung.com/java-concurrent-hashset-concurrenthashmap)
- [Reading and Writing With a ConcurrentHashMap](https://www.baeldung.com/concurrenthashmap-reading-and-writing)
+- [ArrayBlockingQueue vs. LinkedBlockingQueue](https://www.baeldung.com/java-arrayblockingqueue-vs-linkedblockingqueue)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-collections)
diff --git a/core-java-modules/core-java-concurrency-collections-2/pom.xml b/core-java-modules/core-java-concurrency-collections-2/pom.xml
index 9a95662faee7..a85721e47490 100644
--- a/core-java-modules/core-java-concurrency-collections-2/pom.xml
+++ b/core-java-modules/core-java-concurrency-collections-2/pom.xml
@@ -3,7 +3,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-collections-2
- 0.1.0-SNAPSHOT
core-java-concurrency-collections-2
jar
diff --git a/core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/BlockingQueueUnitTest.java b/core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/BlockingQueueUnitTest.java
new file mode 100644
index 000000000000..e913747f2da3
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/BlockingQueueUnitTest.java
@@ -0,0 +1,26 @@
+package com.baeldung.concurrent.queue;
+
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+
+import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+
+public class BlockingQueueUnitTest {
+
+ @Test
+ public void givenArrayBlockingQueue_whenAddedElements_thenReturnQueueRemainingCapacity() {
+ BlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(10);
+ arrayBlockingQueue.add("TestString1");
+ arrayBlockingQueue.add("TestString2");
+ assertEquals(8, arrayBlockingQueue.remainingCapacity());
+ }
+
+ @Test
+ public void givenLinkedBlockingQueue_whenAddedElements_thenReturnQueueRemainingCapacity() {
+ BlockingQueue linkedBlockingQueue = new LinkedBlockingQueue<>(10);
+ linkedBlockingQueue.add("TestString1");
+ assertEquals(9, linkedBlockingQueue.remainingCapacity());
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-concurrency-collections/pom.xml b/core-java-modules/core-java-concurrency-collections/pom.xml
index 8b8d2fe03b50..a35da4ce49ed 100644
--- a/core-java-modules/core-java-concurrency-collections/pom.xml
+++ b/core-java-modules/core-java-concurrency-collections/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-collections
- 0.1.0-SNAPSHOT
core-java-concurrency-collections
jar
diff --git a/core-java-modules/core-java-concurrency-simple/pom.xml b/core-java-modules/core-java-concurrency-simple/pom.xml
index 159a105035f7..a16df4fc9724 100644
--- a/core-java-modules/core-java-concurrency-simple/pom.xml
+++ b/core-java-modules/core-java-concurrency-simple/pom.xml
@@ -3,7 +3,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-simple
- 0.1.0-SNAPSHOT
core-java-concurrency-simple
jar
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/sandbox/SandboxJavaManualTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/sandbox/SandboxJavaManualTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/sandbox/SandboxJavaManualTest.java
rename to core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/sandbox/SandboxJavaManualTest.java
diff --git a/core-java-modules/core-java-console/pom.xml b/core-java-modules/core-java-console/pom.xml
index 200e2707dd7f..4debf9388be8 100644
--- a/core-java-modules/core-java-console/pom.xml
+++ b/core-java-modules/core-java-console/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-console
- 0.1.0-SNAPSHOT
core-java-console
jar
diff --git a/core-java-modules/core-java-date-operations-1/pom.xml b/core-java-modules/core-java-date-operations-1/pom.xml
index c5d46723d87f..5bfbb5bab0fe 100644
--- a/core-java-modules/core-java-date-operations-1/pom.xml
+++ b/core-java-modules/core-java-date-operations-1/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-date-operations-1
- ${project.parent.version}
core-java-date-operations-1
jar
diff --git a/core-java-modules/core-java-date-operations-2/pom.xml b/core-java-modules/core-java-date-operations-2/pom.xml
index 461ba70b6204..c6a22a4166d4 100644
--- a/core-java-modules/core-java-date-operations-2/pom.xml
+++ b/core-java-modules/core-java-date-operations-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-date-operations-2
- ${project.parent.version}
core-java-date-operations-2
jar
diff --git a/core-java-modules/core-java-date-operations-3/pom.xml b/core-java-modules/core-java-date-operations-3/pom.xml
index 8713139ba863..89c21a31c15e 100644
--- a/core-java-modules/core-java-date-operations-3/pom.xml
+++ b/core-java-modules/core-java-date-operations-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-date-operations-3
- ${project.parent.version}
core-java-date-operations-3
jar
@@ -14,10 +13,4 @@
0.0.1-SNAPSHOT
-
-
-
-
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java-datetime-string-2/pom.xml b/core-java-modules/core-java-datetime-string-2/pom.xml
index 3ec9ccaac41c..458fba25a27d 100644
--- a/core-java-modules/core-java-datetime-string-2/pom.xml
+++ b/core-java-modules/core-java-datetime-string-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-datetime-string-2
- ${project.parent.version}
core-java-datetime-string-2
jar
diff --git a/core-java-modules/core-java-datetime-string/pom.xml b/core-java-modules/core-java-datetime-string/pom.xml
index 2b3c2edb02f1..3efb2fe72855 100644
--- a/core-java-modules/core-java-datetime-string/pom.xml
+++ b/core-java-modules/core-java-datetime-string/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-datetime-string
- ${project.parent.version}
core-java-datetime-string
jar
@@ -20,7 +19,6 @@
commons-lang3
${commons-lang3.version}
-
commons-validator
commons-validator
diff --git a/core-java-modules/core-java-documentation/README.md b/core-java-modules/core-java-documentation/README.md
new file mode 100644
index 000000000000..b66b9e8c0562
--- /dev/null
+++ b/core-java-modules/core-java-documentation/README.md
@@ -0,0 +1,6 @@
+## Core Java Documentation
+
+### Relevant Articles:
+
+- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
+
diff --git a/core-java-modules/core-java-documentation/pom.xml b/core-java-modules/core-java-documentation/pom.xml
new file mode 100644
index 000000000000..be18af1b1001
--- /dev/null
+++ b/core-java-modules/core-java-documentation/pom.xml
@@ -0,0 +1,41 @@
+
+
+ 4.0.0
+ core-java-documentation
+ 0.1.0-SNAPSHOT
+ core-java-documentation
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ ${maven-javadoc-plugin.version}
+
+
+ ${target.version}
+
+
+
+
+
+
+
+ 3.0.0-M1
+ 1.8
+ 1.8
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/javadoc/CodeSnippetFormatting.java b/core-java-modules/core-java-documentation/src/main/java/com/baeldung/javadoc/CodeSnippetFormatting.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/javadoc/CodeSnippetFormatting.java
rename to core-java-modules/core-java-documentation/src/main/java/com/baeldung/javadoc/CodeSnippetFormatting.java
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/javadoc/Person.java b/core-java-modules/core-java-documentation/src/main/java/com/baeldung/javadoc/Person.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/javadoc/Person.java
rename to core-java-modules/core-java-documentation/src/main/java/com/baeldung/javadoc/Person.java
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java b/core-java-modules/core-java-documentation/src/main/java/com/baeldung/javadoc/SuperHero.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java
rename to core-java-modules/core-java-documentation/src/main/java/com/baeldung/javadoc/SuperHero.java
diff --git a/core-java-modules/core-java-exceptions-2/pom.xml b/core-java-modules/core-java-exceptions-2/pom.xml
index 9103672cd472..8bf5605f09fe 100644
--- a/core-java-modules/core-java-exceptions-2/pom.xml
+++ b/core-java-modules/core-java-exceptions-2/pom.xml
@@ -5,8 +5,6 @@
core-java-exceptions-2
core-java-exceptions-2
jar
-
- http://maven.apache.org
com.baeldung.core-java-modules
diff --git a/core-java-modules/core-java-exceptions-3/pom.xml b/core-java-modules/core-java-exceptions-3/pom.xml
index 7eaa57edf158..6ef979b54ae3 100644
--- a/core-java-modules/core-java-exceptions-3/pom.xml
+++ b/core-java-modules/core-java-exceptions-3/pom.xml
@@ -3,9 +3,7 @@
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">
4.0.0
- com.baeldung.exceptions
core-java-exceptions-3
- 0.1.0-SNAPSHOT
core-java-exceptions-3
jar
diff --git a/core-java-modules/core-java-exceptions-4/pom.xml b/core-java-modules/core-java-exceptions-4/pom.xml
index e9eb1bf37939..c41c782fcc92 100644
--- a/core-java-modules/core-java-exceptions-4/pom.xml
+++ b/core-java-modules/core-java-exceptions-4/pom.xml
@@ -3,9 +3,7 @@
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">
4.0.0
- com.baeldung.exceptions
core-java-exceptions-4
- 0.1.0-SNAPSHOT
core-java-exceptions-4
jar
diff --git a/core-java-modules/core-java-exceptions/pom.xml b/core-java-modules/core-java-exceptions/pom.xml
index 866248b41657..0bb6e86c7667 100644
--- a/core-java-modules/core-java-exceptions/pom.xml
+++ b/core-java-modules/core-java-exceptions/pom.xml
@@ -3,9 +3,7 @@
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">
4.0.0
- com.baeldung.exceptions
core-java-exceptions
- 0.1.0-SNAPSHOT
core-java-exceptions
jar
diff --git a/core-java-modules/core-java-function/pom.xml b/core-java-modules/core-java-function/pom.xml
index ebc34aaf4b91..e8b538ad2454 100644
--- a/core-java-modules/core-java-function/pom.xml
+++ b/core-java-modules/core-java-function/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-function
- 0.1.0-SNAPSHOT
core-java-function
jar
diff --git a/core-java-modules/core-java-functional/pom.xml b/core-java-modules/core-java-functional/pom.xml
index 9ad47f813382..4b0bf9f730e5 100644
--- a/core-java-modules/core-java-functional/pom.xml
+++ b/core-java-modules/core-java-functional/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-functional
- 0.1.0-SNAPSHOT
core-java-functional
jar
diff --git a/core-java-modules/core-java-hex/pom.xml b/core-java-modules/core-java-hex/pom.xml
index afac1c4d66a8..71e6b15b2e96 100644
--- a/core-java-modules/core-java-hex/pom.xml
+++ b/core-java-modules/core-java-hex/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-hex
- 0.1.0-SNAPSHOT
core-java-hex
jar
@@ -14,12 +13,4 @@
0.0.1-SNAPSHOT
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java-httpclient/pom.xml b/core-java-modules/core-java-httpclient/pom.xml
index 3df0447ff005..f3730d1b45bb 100644
--- a/core-java-modules/core-java-httpclient/pom.xml
+++ b/core-java-modules/core-java-httpclient/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-httpclient
- 0.1.0-SNAPSHOT
core-java-httpclient
jar
diff --git a/core-java-modules/core-java-io-2/pom.xml b/core-java-modules/core-java-io-2/pom.xml
index b5f43d5a94ef..8f4f2518fe33 100644
--- a/core-java-modules/core-java-io-2/pom.xml
+++ b/core-java-modules/core-java-io-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io-2
- 0.1.0-SNAPSHOT
core-java-io-2
jar
diff --git a/core-java-modules/core-java-io-3/pom.xml b/core-java-modules/core-java-io-3/pom.xml
index 49011338541a..26ea30183730 100644
--- a/core-java-modules/core-java-io-3/pom.xml
+++ b/core-java-modules/core-java-io-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io-3
- 0.1.0-SNAPSHOT
core-java-io-3
jar
diff --git a/core-java-modules/core-java-io-4/pom.xml b/core-java-modules/core-java-io-4/pom.xml
index 2cc05698fce7..30177e5c09ab 100644
--- a/core-java-modules/core-java-io-4/pom.xml
+++ b/core-java-modules/core-java-io-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io-4
- 0.1.0-SNAPSHOT
core-java-io-4
jar
diff --git a/core-java-modules/core-java-io-apis-2/README.md b/core-java-modules/core-java-io-apis-2/README.md
index f3d72fe8b5f8..a4ea869946d2 100644
--- a/core-java-modules/core-java-io-apis-2/README.md
+++ b/core-java-modules/core-java-io-apis-2/README.md
@@ -5,3 +5,8 @@ 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)
diff --git a/core-java-modules/core-java-io-apis-2/pom.xml b/core-java-modules/core-java-io-apis-2/pom.xml
index 70c3a87da296..e828b730d283 100644
--- a/core-java-modules/core-java-io-apis-2/pom.xml
+++ b/core-java-modules/core-java-io-apis-2/pom.xml
@@ -1,47 +1,114 @@
-
-
- 4.0.0
- core-java-io-apis-2
- 0.1.0-SNAPSHOT
- core-java-io-apis-2
- jar
-
-
- com.baeldung.core-java-modules
- core-java-modules
- 0.0.1-SNAPSHOT
-
-
-
-
-
- log4j
- log4j
- ${log4j.version}
-
-
- org.slf4j
- log4j-over-slf4j
- ${org.slf4j.version}
-
-
- org.projectlombok
- lombok
- ${lombok.version}
- provided
-
-
-
-
- core-java-io-apis-2
-
-
- src/main/resources
- true
-
-
-
-
+
+
+ 4.0.0
+ core-java-io-apis-2
+ core-java-io-apis-2
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+ log4j
+ log4j
+ ${log4j.version}
+
+
+ org.slf4j
+ log4j-over-slf4j
+ ${org.slf4j.version}
+
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+ provided
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ 5.7.2
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+
+ org.junit.jupiter
+ junit-jupiter-api
+ ${junit-jupiter-version}
+ test
+
+
+
+ org.junit.jupiter
+ junit-jupiter-params
+ ${junit-jupiter-version}
+ test
+
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ ${junit-jupiter-version}
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+ org.testng
+ testng
+ 7.1.0
+ test
+
+
+ org.testng
+ testng
+ 7.5
+ compile
+
+
+
+ core-java-io-apis-2
+
+
+ src/main/resources
+ true
+
+
+
+
+ 5.9.3
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/multinput/MultiInputs.java b/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/multinput/MultiInputs.java
new file mode 100644
index 000000000000..df799b25112b
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/multinput/MultiInputs.java
@@ -0,0 +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."); }
+
+ }
+}
+
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/absolutetorelative/AbsoluteToRelativeUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/absolutetorelative/AbsoluteToRelativeUnitTest.java
index 0830b0808a82..9b3f424a3040 100644
--- a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/absolutetorelative/AbsoluteToRelativeUnitTest.java
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/absolutetorelative/AbsoluteToRelativeUnitTest.java
@@ -1,93 +1,92 @@
-package com.baeldung.absolutetorelative;
-
-import org.assertj.core.api.Assertions;
-import org.junit.jupiter.api.Test;
-
-import java.net.URI;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-
-public class AbsoluteToRelativeUnitTest {
-
- // given - until using Paths, no need to create physical files
- private final Path pathOne = Paths.get("/baeldung/bar/one.txt");
- private final Path pathTwo = Paths.get("/baeldung/bar/two.txt");
- private final Path pathThree = Paths.get("/baeldung/foo/three.txt");
-
- private final URI uriOne = pathOne.toUri();
- private final URI uriTwo = pathTwo.toUri();
- private final URI uriThree = pathThree.toUri();
-
- @Test
- public void givenAbsolutePaths_whenRelativizePathOneToPathTwo_thenRelativeIsReturned() {
- Path result = pathOne.relativize(pathTwo);
-
- Assertions.assertThat(result)
- .isRelative()
- .isEqualTo(Paths.get("../two.txt"));
- }
-
- @Test
- public void givenAbsolutePaths_whenRelativizePathTwoToPathOne_thenRelativeIsReturned() {
- Path result = pathTwo.relativize(pathOne);
-
- Assertions.assertThat(result)
- .isRelative()
- .isEqualTo(Paths.get("../one.txt"));
- }
-
- @Test
- public void givenAbsolutePaths_whenRelativizePathOneParentToPathTwo_thenRelativeIsReturned() {
- Path result = pathOne.getParent().relativize(pathTwo);
-
- Assertions.assertThat(result)
- .isRelative()
- .isEqualTo(Paths.get("two.txt"));
- }
-
- @Test
- public void givenAbsolutePaths_whenRelativizePathOneToPathThree_thenRelativeIsReturned() {
- Path result = pathOne.relativize(pathThree);
-
- Assertions.assertThat(result)
- .isRelative()
- .isEqualTo(Paths.get("../../foo/three.txt"));
- }
-
- @Test
- public void givenAbsolutePaths_whenRelativizePathThreeToPathOne_thenRelativeIsReturned() {
- Path result = pathThree.relativize(pathOne);
-
- Assertions.assertThat(result)
- .isRelative()
- .isEqualTo(Paths.get("../../bar/one.txt"));
- }
-
- @Test
- public void givenAbsoluteURIs_whenRelativizeUriOneToUriTwo_thenAbsoluteIsReturned() {
- URI result = uriOne.relativize(uriTwo);
-
- Assertions.assertThat(result)
- .asString()
- .contains("/baeldung/bar/two.txt");
- }
-
- @Test
- public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriTwo_thenRelativeIsReturned() {
- URI result = pathOne.getParent().toUri().relativize(uriTwo);
-
- Assertions.assertThat(result)
- .asString()
- .contains("two.txt");
- }
-
- @Test
- public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriThree_thenAbsoluteIsReturned() {
- URI result = pathOne.getParent().toUri().relativize(uriThree);
-
- Assertions.assertThat(result)
- .asString()
- .contains("/baeldung/foo/three.txt");
- }
-
-}
+package com.baeldung.absolutetorelative;
+
+import java.net.URI;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class AbsoluteToRelativeUnitTest {
+
+ // given - until using Paths, no need to create physical files
+ private final Path pathOne = Paths.get("/baeldung/bar/one.txt");
+ private final Path pathTwo = Paths.get("/baeldung/bar/two.txt");
+ private final Path pathThree = Paths.get("/baeldung/foo/three.txt");
+
+ private final URI uriOne = pathOne.toUri();
+ private final URI uriTwo = pathTwo.toUri();
+ private final URI uriThree = pathThree.toUri();
+
+ @Test
+ public void givenAbsolutePaths_whenRelativizePathOneToPathTwo_thenRelativeIsReturned() {
+ Path result = pathOne.relativize(pathTwo);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .isRelative()
+ .isEqualTo(Paths.get("../two.txt"));
+ }
+
+ @Test
+ public void givenAbsolutePaths_whenRelativizePathTwoToPathOne_thenRelativeIsReturned() {
+ Path result = pathTwo.relativize(pathOne);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .isRelative()
+ .isEqualTo(Paths.get("../one.txt"));
+ }
+
+ @Test
+ public void givenAbsolutePaths_whenRelativizePathOneParentToPathTwo_thenRelativeIsReturned() {
+ Path result = pathOne.getParent().relativize(pathTwo);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .isRelative()
+ .isEqualTo(Paths.get("two.txt"));
+ }
+
+ @Test
+ public void givenAbsolutePaths_whenRelativizePathOneToPathThree_thenRelativeIsReturned() {
+ Path result = pathOne.relativize(pathThree);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .isRelative()
+ .isEqualTo(Paths.get("../../foo/three.txt"));
+ }
+
+ @Test
+ public void givenAbsolutePaths_whenRelativizePathThreeToPathOne_thenRelativeIsReturned() {
+ Path result = pathThree.relativize(pathOne);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .isRelative()
+ .isEqualTo(Paths.get("../../bar/one.txt"));
+ }
+
+ @Test
+ public void givenAbsoluteURIs_whenRelativizeUriOneToUriTwo_thenAbsoluteIsReturned() {
+ URI result = uriOne.relativize(uriTwo);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .asString()
+ .contains("/baeldung/bar/two.txt");
+ }
+
+ @Test
+ public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriTwo_thenRelativeIsReturned() {
+ URI result = pathOne.getParent().toUri().relativize(uriTwo);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .asString()
+ .contains("two.txt");
+ }
+
+ @Test
+ public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriThree_thenAbsoluteIsReturned() {
+ URI result = pathOne.getParent().toUri().relativize(uriThree);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .asString()
+ .contains("/baeldung/foo/three.txt");
+ }
+
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/BufferedReaderUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/BufferedReaderUnitTest.java
new file mode 100644
index 000000000000..06b7d3882157
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/BufferedReaderUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.bufferedreadervsfilereader;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+
+import org.junit.jupiter.api.Assertions;
+import org.testng.annotations.Test;
+public class BufferedReaderUnitTest {
+
+ @Test
+ public void whenReadingAFile_thenReadsLineByLine() {
+ StringBuilder result = new StringBuilder();
+
+ try (BufferedReader br = new BufferedReader(new FileReader("src/test/resources/sampleText1.txt"))) {
+ 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());
+ }
+
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/FileReaderUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/FileReaderUnitTest.java
new file mode 100644
index 000000000000..5df870e7b5e8
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/FileReaderUnitTest.java
@@ -0,0 +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;
+
+public class FileReaderUnitTest {
+
+ @Test
+ public 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());
+ }
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/multinput/TestMultipleInputsUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/multinput/TestMultipleInputsUnitTest.java
new file mode 100644
index 000000000000..317d9e817ed2
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/multinput/TestMultipleInputsUnitTest.java
@@ -0,0 +1,47 @@
+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);
+ }
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/outputtofile/ConsoleOutputToFileUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/outputtofile/ConsoleOutputToFileUnitTest.java
new file mode 100644
index 000000000000..c7f643b14841
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/outputtofile/ConsoleOutputToFileUnitTest.java
@@ -0,0 +1,94 @@
+package com.baeldung.outputtofile;
+
+import static org.junit.jupiter.api.Assertions.assertLinesMatch;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import com.google.common.collect.Lists;
+
+class DualPrintStream extends PrintStream {
+ private final PrintStream second;
+
+ public DualPrintStream(OutputStream main, PrintStream second) {
+ super(main);
+ this.second = second;
+ }
+
+ @Override
+ public void close() {
+ super.close();
+ second.close();
+ }
+
+ @Override
+ public void flush() {
+ super.flush();
+ second.flush();
+ }
+
+ @Override
+ public void write(byte[] buf, int off, int len) {
+ super.write(buf, off, len);
+ second.write(buf, off, len);
+ }
+
+ @Override
+ public void write(int b) {
+ super.write(b);
+ second.write(b);
+ }
+
+ @Override
+ public void write(byte[] b) throws IOException {
+ super.write(b);
+ second.write(b);
+ }
+}
+
+public class ConsoleOutputToFileUnitTest {
+
+ // @formatter:off
+ private final static List OUTPUT_LINES = Lists.newArrayList(
+ "I came",
+ "I saw",
+ "I conquered");
+ // @formatter:on
+
+ @Test
+ void whenReplacingSystemOutPrintStreamWithFileOutputStream_thenOutputsGoToFile(@TempDir Path tempDir) throws IOException {
+ PrintStream originalOut = System.out;
+ Path outputFilePath = tempDir.resolve("file-output.txt");
+ PrintStream out = new PrintStream(Files.newOutputStream(outputFilePath), true);
+ System.setOut(out);
+
+ OUTPUT_LINES.forEach(line -> System.out.println(line));
+ assertTrue(outputFilePath.toFile()
+ .exists(), "The file exists");
+ assertLinesMatch(OUTPUT_LINES, Files.readAllLines(outputFilePath));
+ System.setOut(originalOut);
+ }
+
+ @Test
+ void whenUsingDualPrintStream_thenOutputsGoToConsoleAndFile(@TempDir Path tempDir) throws IOException {
+ PrintStream originalOut = System.out;
+ Path outputFilePath = tempDir.resolve("dual-output.txt");
+ DualPrintStream dualOut = new DualPrintStream(Files.newOutputStream(outputFilePath), System.out);
+ System.setOut(dualOut);
+
+ OUTPUT_LINES.forEach(line -> System.out.println(line));
+ assertTrue(outputFilePath.toFile()
+ .exists(), "The file exists");
+ assertLinesMatch(OUTPUT_LINES, Files.readAllLines(outputFilePath));
+ System.setOut(originalOut);
+
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/path/DesktopPathUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/path/DesktopPathUnitTest.java
index fe21d0a72fac..1b71512c5c98 100644
--- a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/path/DesktopPathUnitTest.java
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/path/DesktopPathUnitTest.java
@@ -1,29 +1,27 @@
-package com.baeldung.path;
-
-import org.junit.jupiter.api.Test;
-
-import java.io.File;
-
-import static org.junit.Assert.assertEquals;
-
-import javax.swing.filechooser.FileSystemView;
-
-public class DesktopPathUnitTest {
- // Adapt DESKTOP_PATH variable to your own system path
- // private static final String DESKTOP_PATH = "C:\\Users\\HRAF\\Desktop";
-
- @Test
- public void whenUsingGetUserHomeProperty_thenShouldEqualDesktopPath() {
- String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
- // assertEquals(DESKTOP_PATH, desktopPath);
- }
-
- @Test
- public void whenUsingFileSystemViewGetHomeDirectory_thenShouldEqualDesktopPath() {
- FileSystemView view = FileSystemView.getFileSystemView();
- File file = view.getHomeDirectory();
- String path = file.getPath();
- // assertEquals(DESKTOP_PATH, path);
- }
-
-}
+package com.baeldung.path;
+
+import java.io.File;
+
+import javax.swing.filechooser.FileSystemView;
+
+import org.junit.jupiter.api.Test;
+
+public class DesktopPathUnitTest {
+ // Adapt DESKTOP_PATH variable to your own system path
+ // private static final String DESKTOP_PATH = "C:\\Users\\HRAF\\Desktop";
+
+ @Test
+ public void whenUsingGetUserHomeProperty_thenShouldEqualDesktopPath() {
+ String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
+ // assertEquals(DESKTOP_PATH, desktopPath);
+ }
+
+ @Test
+ public void whenUsingFileSystemViewGetHomeDirectory_thenShouldEqualDesktopPath() {
+ FileSystemView view = FileSystemView.getFileSystemView();
+ File file = view.getHomeDirectory();
+ String path = file.getPath();
+ // assertEquals(DESKTOP_PATH, path);
+ }
+
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/InputWithSpacesUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/InputWithSpacesUnitTest.java
new file mode 100644
index 000000000000..8a93c6ce650b
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/InputWithSpacesUnitTest.java
@@ -0,0 +1,97 @@
+package com.baeldung.scanner;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Scanner;
+
+import org.junit.jupiter.api.Test;
+
+import com.google.common.collect.Lists;
+
+public class InputWithSpacesUnitTest {
+ @Test
+ void whenValuesContainSpaces_thenNextBreaksTheValue() {
+ String input = new StringBuilder().append("Michael Jackson\n")
+ .append("He was the 'King of Pop'.\n")
+ .toString();
+
+ Scanner sc = new Scanner(input);
+ String name = sc.next();
+ String description = sc.next();
+ assertEquals("Michael", name);
+ assertEquals("Jackson", description);
+ }
+
+ @Test
+ void whenOneValuePerLineUsingNextLine_thenGetExpectedResult() {
+ String input = new StringBuilder().append("Michael Jackson\n")
+ .append("He was the 'King of Pop'.\n")
+ .toString();
+
+ Scanner sc = new Scanner(input);
+ String name = sc.nextLine();
+ String description = sc.nextLine();
+ assertEquals("Michael Jackson", name);
+ assertEquals("He was the 'King of Pop'.", description);
+ }
+
+ @Test
+ void whenOneValuePerLineUsingNewLineAsDelimiter_thenGetExpectedResult() {
+ String input = new StringBuilder().append("Michael Jackson\n")
+ .append("He was the 'King of Pop'.\n")
+ .toString();
+
+ Scanner sc = new Scanner(input);
+ sc.useDelimiter("\\n");
+ String name = sc.next();
+ String description = sc.next();
+ assertEquals("Michael Jackson", name);
+ assertEquals("He was the 'King of Pop'.", description);
+ }
+
+ @Test
+ void whenValuesAreSeparatedByCommaUsingSplit_thenGetExpectedResult() {
+ String input = "Michael Jackson, Whitney Houston, John Lennon\n";
+
+ Scanner sc = new Scanner(input);
+ String[] names = sc.nextLine()
+ .split(", ");
+ assertArrayEquals(new String[] { "Michael Jackson", "Whitney Houston", "John Lennon" }, names);
+ }
+
+ @Test
+ void whenValuesAreSeparatedByCommaSettingDelimiterWithoutNewline_thenGetExpectedResult() {
+ String input = new StringBuilder().append("Michael Jackson, Whitney Houston, John Lennon\n")
+ .append("Elvis Presley\n")
+ .toString();
+
+ Scanner sc = new Scanner(input);
+ sc.useDelimiter(", ");
+ List names = new ArrayList<>();
+ while (sc.hasNext()) {
+ names.add(sc.next());
+ }
+ //assertEquals(Lists.newArrayList("Michael Jackson", "Whitney Houston", "John Lennon", "Elvis Presley"), names); <-- Fail
+ assertEquals(3, names.size());
+ assertEquals("John Lennon\nElvis Presley\n", names.get(2));
+
+ }
+
+ @Test
+ void whenValuesAreSeparatedByCommaSettingDelimiter_thenGetExpectedResult() {
+ String input = new StringBuilder().append("Michael Jackson, Whitney Houston, John Lennon\n")
+ .append("Elvis Presley\n")
+ .toString();
+
+ Scanner sc = new Scanner(input);
+ sc.useDelimiter(", |\\n");
+ List names = new ArrayList<>();
+ while (sc.hasNext()) {
+ names.add(sc.next());
+ }
+ assertEquals(Lists.newArrayList("Michael Jackson", "Whitney Houston", "John Lennon", "Elvis Presley"), names);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextLineVsNextIntUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextLineVsNextIntUnitTest.java
new file mode 100644
index 000000000000..3aae0469d0a5
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextLineVsNextIntUnitTest.java
@@ -0,0 +1,85 @@
+package com.baeldung.scanner;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.InputMismatchException;
+import java.util.Scanner;
+
+import org.junit.jupiter.api.Test;
+
+public class NextLineVsNextIntUnitTest {
+
+ @Test
+ void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() {
+ String input = "42\n";
+
+ //nextLine()
+ Scanner sc1 = new Scanner(input);
+ int num1 = Integer.parseInt(sc1.nextLine());
+ assertEquals(42, num1);
+
+ //nextInt()
+ Scanner sc2 = new Scanner(input);
+ int num2 = sc2.nextInt();
+ assertEquals(42, num2);
+
+ }
+
+ @Test
+ void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() {
+ String input = "Nan\n";
+
+ //nextLine() -> NumberFormatException
+ Scanner sc1 = new Scanner(input);
+ assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine()));
+
+ //nextInt() -> InputMismatchException
+ Scanner sc2 = new Scanner(input);
+ assertThrows(InputMismatchException.class, sc2::nextInt);
+ }
+
+ @Test
+ void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() {
+ String input = "42 is a magic number\n";
+
+ //nextInt() to read '42'
+ Scanner sc2 = new Scanner(input);
+ int num2 = sc2.nextInt();
+ assertEquals(42, num2);
+
+ // call nextInt() again on "is"
+ assertThrows(InputMismatchException.class, sc2::nextInt);
+
+ String theNextToken = sc2.next();
+ assertEquals("is", theNextToken);
+
+ theNextToken = sc2.next();
+ assertEquals("a", theNextToken);
+ }
+
+ @Test
+ void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() {
+
+ String input = new StringBuilder().append("42\n")
+ .append("It is a magic number.\n")
+ .toString();
+
+ //nextLine()
+ Scanner sc1 = new Scanner(input);
+ int num1 = Integer.parseInt(sc1.nextLine());
+ String nextLineText1 = sc1.nextLine();
+ assertEquals(42, num1);
+ assertEquals("It is a magic number.", nextLineText1);
+
+ //nextInt()
+ Scanner sc2 = new Scanner(input);
+ int num2 = sc2.nextInt();
+ assertEquals(42, num2);
+
+ // nextInt() leaves the newline character (\n) behind
+ String nextLineText2 = sc2.nextLine();
+ assertEquals("", nextLineText2);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextVsNextLineUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextVsNextLineUnitTest.java
new file mode 100644
index 000000000000..08d2ebe28893
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextVsNextLineUnitTest.java
@@ -0,0 +1,51 @@
+package com.baeldung.scanner;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Scanner;
+
+import org.junit.jupiter.api.Test;
+
+class NextVsNextLineUnitTest {
+
+ @Test
+ void givenInput_whenUsingNextMethod_thenReturnToken() {
+ String input = "Hello world";
+ try (Scanner scanner = new Scanner(input)) {
+ assertEquals("Hello", scanner.next());
+ assertEquals("world", scanner.next());
+ }
+ }
+
+ @Test
+ void givenInput_whenUsingNextMethodWithCustomDelimiter_thenReturnToken() {
+ String input = "Hello :world";
+ try (Scanner scanner = new Scanner(input)) {
+ scanner.useDelimiter(":");
+
+ assertEquals("Hello ", scanner.next());
+ assertEquals("world", scanner.next());
+ }
+ }
+
+ @Test
+ void givenInput_whenUsingNextLineMethod_thenReturnEntireLine() {
+ String input = "Hello world\nWelcome to baeldung.com";
+ try (Scanner scanner = new Scanner(input)) {
+ assertEquals("Hello world", scanner.nextLine());
+ assertEquals("Welcome to baeldung.com", scanner.nextLine());
+ }
+ }
+
+ @Test
+ void givenInput_whenUsingNextLineWithCustomDelimiter_thenIgnoreDelimiter() {
+ String input = "Hello:world\nWelcome:to baeldung.com";
+ try (Scanner scanner = new Scanner(input)) {
+ scanner.useDelimiter(":");
+
+ assertEquals("Hello:world", scanner.nextLine());
+ assertEquals("Welcome:to baeldung.com", scanner.nextLine());
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScanACharacterUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScanACharacterUnitTest.java
index 1a70c6e3af0e..340b58bbf692 100644
--- a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScanACharacterUnitTest.java
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScanACharacterUnitTest.java
@@ -1,38 +1,38 @@
-package com.baeldung.scanner;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.util.Scanner;
-
-import org.junit.jupiter.api.Test;
-
-public class ScanACharacterUnitTest {
-
- // given - input scanner source, no need to scan from console
- String input = new StringBuilder().append("abc\n")
- .append("mno\n")
- .append("xyz\n")
- .toString();
-
- @Test
- public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
- Scanner sc = new Scanner(input);
- char c = sc.next().charAt(0);
- assertEquals('a', c);
- }
-
- @Test
- public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
- Scanner sc = new Scanner(input);
- char c = sc.findInLine(".").charAt(0);
- assertEquals('a', c);
- }
-
- @Test
- public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() {
- Scanner sc = new Scanner(input);
- char c = sc.useDelimiter("").next().charAt(0);
- assertEquals('a', c);
- }
-
-}
+package com.baeldung.scanner;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Scanner;
+
+import org.junit.jupiter.api.Test;
+
+public class ScanACharacterUnitTest {
+
+ // given - input scanner source, no need to scan from console
+ String input = new StringBuilder().append("abc\n")
+ .append("mno\n")
+ .append("xyz\n")
+ .toString();
+
+ @Test
+ public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
+ Scanner sc = new Scanner(input);
+ char c = sc.next().charAt(0);
+ assertEquals('a', c);
+ }
+
+ @Test
+ public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
+ Scanner sc = new Scanner(input);
+ char c = sc.findInLine(".").charAt(0);
+ assertEquals('a', c);
+ }
+
+ @Test
+ public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() {
+ Scanner sc = new Scanner(input);
+ char c = sc.useDelimiter("").next().charAt(0);
+ assertEquals('a', c);
+ }
+
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScannerToArrayUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScannerToArrayUnitTest.java
new file mode 100644
index 000000000000..f64bd7b1fc25
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScannerToArrayUnitTest.java
@@ -0,0 +1,107 @@
+package com.baeldung.scanner;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Scanner;
+
+import org.junit.jupiter.api.Test;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.ObjectArrays;
+
+public class ScannerToArrayUnitTest {
+
+ @Test
+ void whenMultipleElementsInOneLine_thenGetExpectedArray() {
+ String input = "Java Kotlin Ruby Python Go\n";
+ String[] expected = new String[] { "Java", "Kotlin", "Ruby", "Python", "Go" };
+
+ // scanner.next()
+ Scanner scanner1 = new Scanner(input);
+ String[] result1 = new String[5];
+ int i = 0;
+ while (i < result1.length) {
+ result1[i] = scanner1.next();
+ i++;
+ }
+ assertArrayEquals(expected, result1);
+
+ //split()
+ Scanner scanner2 = new Scanner(input);
+ String[] result2 = scanner2.nextLine()
+ .split("\\s+");
+ assertArrayEquals(expected, result2);
+ }
+
+ @Test
+ void whenOneElementPerLine_thenGetExpectedArray() {
+ String input = new StringBuilder().append("Baeldung Java\n")
+ .append("Baeldung Kotlin\n")
+ .append("Baeldung Linux\n")
+ .toString();
+
+ String[] expected = new String[] { "Baeldung Java", "Baeldung Kotlin", "Baeldung Linux" };
+
+ String[] result = new String[3];
+ Scanner scanner = new Scanner(input);
+ int i = 0;
+ while (i < result.length) {
+ result[i] = scanner.nextLine();
+ i++;
+ }
+ assertArrayEquals(expected, result);
+ }
+
+ @Test
+ void whenOneElementPerLine_thenGetExpectedList() {
+ String input = new StringBuilder().append("Baeldung Java\n")
+ .append("Baeldung Kotlin\n")
+ .append("Baeldung Linux\n")
+ .toString();
+
+ List expected = Lists.newArrayList("Baeldung Java", "Baeldung Kotlin", "Baeldung Linux");
+
+ List result = new ArrayList<>();
+ Scanner scanner = new Scanner(input);
+ while (scanner.hasNextLine()) {
+ result.add(scanner.nextLine());
+ }
+ assertEquals(expected, result);
+ }
+
+ @Test
+ void whenEveryTokenIsAnElement_thenGetExpectedList() {
+ String input = new StringBuilder().append("Linux Windows MacOS\n")
+ .append("Java Kotlin Python Go\n")
+ .toString();
+
+ List expected = Lists.newArrayList("Linux", "Windows", "MacOS", "Java", "Kotlin", "Python", "Go");
+ List result = new ArrayList<>();
+ Scanner scanner = new Scanner(input);
+ while (scanner.hasNext()) {
+ result.add(scanner.next());
+ }
+ assertEquals(expected, result);
+ }
+
+ @Test
+ void whenEveryTokenIsAnElement_thenGetExpectedArray() {
+ String input = new StringBuilder().append("Linux Windows MacOS\n")
+ .append("Java Kotlin Python Go\n")
+ .toString();
+
+ String[] expected = new String[] { "Linux", "Windows", "MacOS", "Java", "Kotlin", "Python", "Go" };
+ String[] result = new String[] {};
+
+ Scanner scanner = new Scanner(input);
+ while (scanner.hasNextLine()) {
+ String[] lineInArray = scanner.nextLine()
+ .split("\\s+");
+ result = ObjectArrays.concat(result, lineInArray, String.class);
+ }
+ assertArrayEquals(expected, result);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-apis-2/src/test/resources/sampleText1.txt b/core-java-modules/core-java-io-apis-2/src/test/resources/sampleText1.txt
new file mode 100644
index 000000000000..ea0584cfe09a
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/resources/sampleText1.txt
@@ -0,0 +1,3 @@
+first line
+second line
+third line
diff --git a/core-java-modules/core-java-io-apis-2/src/test/resources/sampleText2.txt b/core-java-modules/core-java-io-apis-2/src/test/resources/sampleText2.txt
new file mode 100644
index 000000000000..f2289097d4cb
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/resources/sampleText2.txt
@@ -0,0 +1 @@
+qwerty
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-apis/pom.xml b/core-java-modules/core-java-io-apis/pom.xml
index fab2bff9593b..f9d404cd5be1 100644
--- a/core-java-modules/core-java-io-apis/pom.xml
+++ b/core-java-modules/core-java-io-apis/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io-apis
- 0.1.0-SNAPSHOT
core-java-io-apis
jar
diff --git a/core-java-modules/core-java-io-apis/src/main/java/com/baeldung/scanner/NextLineAfterNextMethods.java b/core-java-modules/core-java-io-apis/src/main/java/com/baeldung/scanner/NextLineAfterNextMethods.java
new file mode 100644
index 000000000000..ce1b2832c992
--- /dev/null
+++ b/core-java-modules/core-java-io-apis/src/main/java/com/baeldung/scanner/NextLineAfterNextMethods.java
@@ -0,0 +1,56 @@
+package com.baeldung.scanner;
+
+import java.util.Scanner;
+
+public class NextLineAfterNextMethods {
+
+ private static void produceSkippingNextLineMethod() {
+ try (Scanner scanner = new Scanner(System.in)) {
+ System.out.print("Enter your age: ");
+ int age = scanner.nextInt();
+ System.out.print("Enter your first name: ");
+ String firstName = scanner.nextLine(); // Skipped because it reads the remaining newline character
+ System.out.println(age + ":" + firstName);
+ }
+ }
+
+ private static void fixSkippingNextLineMethodV1() {
+ try (Scanner scanner = new Scanner(System.in)) {
+ System.out.print("Enter your age: ");
+ int age = scanner.nextInt();
+ scanner.nextLine();
+ System.out.print("Enter your first name: ");
+ String firstName = scanner.nextLine();
+ System.out.println(age + ":" + firstName);
+ }
+ }
+
+ private static void fixSkippingNextLineMethodV2() {
+ try (Scanner scanner = new Scanner(System.in)) {
+ System.out.print("Enter your age: ");
+ int age = Integer.parseInt(scanner.nextLine());
+ System.out.print("Enter your first name: ");
+ String firstName = scanner.nextLine();
+ System.out.println(age + ":" + firstName);
+ }
+ }
+
+ private static void fixSkippingNextLineMethodV3() {
+ try (Scanner scanner = new Scanner(System.in)) {
+ System.out.print("Enter your age: ");
+ int age = scanner.nextInt();
+ scanner.skip("\r\n");
+ System.out.print("Enter your first name: ");
+ String firstName = scanner.nextLine();
+ System.out.println(age + ":" + firstName);
+ }
+ }
+
+ public static void main(String[] args) {
+ produceSkippingNextLineMethod();
+ fixSkippingNextLineMethodV1();
+ fixSkippingNextLineMethodV2();
+ fixSkippingNextLineMethodV3();
+ }
+
+}
diff --git a/core-java-modules/core-java-io-conversions-2/README.md b/core-java-modules/core-java-io-conversions-2/README.md
index c83a3fb1d72a..4e179a84d24e 100644
--- a/core-java-modules/core-java-io-conversions-2/README.md
+++ b/core-java-modules/core-java-io-conversions-2/README.md
@@ -10,4 +10,6 @@ This module contains articles about core Java input/output(IO) conversions.
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
- [How to Convert InputStream to Base64 String](https://www.baeldung.com/java-inputstream-to-base64-string)
+- [Convert an OutputStream to an InputStream](https://www.baeldung.com/java-convert-outputstream-to-inputstream)
+- [Java PrintStream to String](https://www.baeldung.com/java-printstream-to-string)
- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions)
diff --git a/core-java-modules/core-java-io-conversions-2/pom.xml b/core-java-modules/core-java-io-conversions-2/pom.xml
index 24708ad9678a..2c49bbfd81a8 100644
--- a/core-java-modules/core-java-io-conversions-2/pom.xml
+++ b/core-java-modules/core-java-io-conversions-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io-conversions-2
- 0.1.0-SNAPSHOT
core-java-io-conversions-2
jar
diff --git a/core-java-modules/core-java-io-conversions-2/src/main/java/com/baeldung/printstreamtostring/PrintStreamToStringUtil.java b/core-java-modules/core-java-io-conversions-2/src/main/java/com/baeldung/printstreamtostring/PrintStreamToStringUtil.java
new file mode 100644
index 000000000000..72bba78db0ec
--- /dev/null
+++ b/core-java-modules/core-java-io-conversions-2/src/main/java/com/baeldung/printstreamtostring/PrintStreamToStringUtil.java
@@ -0,0 +1,68 @@
+package com.baeldung.printstreamtostring;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+
+public class PrintStreamToStringUtil {
+
+ public static String usingByteArrayOutputStreamClass(String input) throws IOException {
+ if (input == null) {
+ return null;
+ }
+
+ String output;
+ try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream)) {
+ printStream.print(input);
+
+ output = outputStream.toString();
+ }
+
+ return output;
+ }
+
+ public static String usingApacheCommonsIO(String input) {
+ if (input == null) {
+ return null;
+ }
+
+ org.apache.commons.io.output.ByteArrayOutputStream outputStream = new org.apache.commons.io.output.ByteArrayOutputStream();
+ try (PrintStream printStream = new PrintStream(outputStream)) {
+ printStream.print(input);
+ }
+
+ return new String(outputStream.toByteArray());
+ }
+
+ public static String usingCustomOutputStream(String input) throws IOException {
+ if (input == null) {
+ return null;
+ }
+
+ String output;
+ try (CustomOutputStream outputStream = new CustomOutputStream(); PrintStream printStream = new PrintStream(outputStream)) {
+ printStream.print(input);
+
+ output = outputStream.toString();
+ }
+
+ return output;
+ }
+
+ private static class CustomOutputStream extends OutputStream {
+
+ private StringBuilder stringBuilder = new StringBuilder();
+
+ @Override
+ public void write(int b) throws IOException {
+ this.stringBuilder.append((char) b);
+ }
+
+ @Override
+ public String toString() {
+ return this.stringBuilder.toString();
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java
index 03f528766b89..341a820b015a 100644
--- a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java
+++ b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java
@@ -49,7 +49,7 @@ public final void givenUsingJava5_whenConvertingAnInputStreamToAString_thenCorre
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
final StringBuilder textBuilder = new StringBuilder();
- try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
+ try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
int c;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
@@ -63,7 +63,7 @@ public void givenUsingJava8_whenConvertingAnInputStreamToAString_thenCorrect() {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
- final String text = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))
+ final String text = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
diff --git a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/outputstreamtoinputstream/ConvertOutputStreamToInputStreamUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/outputstreamtoinputstream/ConvertOutputStreamToInputStreamUnitTest.java
new file mode 100644
index 000000000000..53e9da6dbb3b
--- /dev/null
+++ b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/outputstreamtoinputstream/ConvertOutputStreamToInputStreamUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.outputstreamtoinputstream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+
+import org.junit.jupiter.api.Test;
+
+public class ConvertOutputStreamToInputStreamUnitTest {
+
+ @Test
+ void whenUsingByteArray_thenGetExpectedInputStream() throws IOException {
+ String content = "I'm an important message.";
+ try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
+ out.write(content.getBytes());
+ try (ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray())) {
+ String inContent = new String(in.readAllBytes());
+
+ assertEquals(content, inContent);
+ }
+ }
+ }
+
+ @Test
+ void whenUsingPipeStream_thenGetExpectedInputStream() throws IOException {
+ String content = "I'm going through the pipe.";
+
+ ByteArrayOutputStream originOut = new ByteArrayOutputStream();
+ originOut.write(content.getBytes());
+
+ //connect the pipe
+ PipedInputStream in = new PipedInputStream();
+ PipedOutputStream out = new PipedOutputStream(in);
+
+ try (in) {
+ new Thread(() -> {
+ try (out) {
+ originOut.writeTo(out);
+ } catch (IOException iox) {
+ // handle IOExceptions
+ }
+ }).start();
+
+ String inContent = new String(in.readAllBytes());
+ assertEquals(content, inContent);
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/printstreamtostring/PrintStreamToStringUtilUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/printstreamtostring/PrintStreamToStringUtilUnitTest.java
new file mode 100644
index 000000000000..4db60b604e97
--- /dev/null
+++ b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/printstreamtostring/PrintStreamToStringUtilUnitTest.java
@@ -0,0 +1,32 @@
+package com.baeldung.printstreamtostring;
+
+import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.IOException;
+
+import org.junit.Test;
+
+public class PrintStreamToStringUtilUnitTest {
+
+ @Test
+ public void whenUsingByteArrayOutputStreamClass_thenConvert() throws IOException {
+ assertEquals("test", PrintStreamToStringUtil.usingByteArrayOutputStreamClass("test"));
+ assertEquals("", PrintStreamToStringUtil.usingByteArrayOutputStreamClass(""));
+ assertNull(PrintStreamToStringUtil.usingByteArrayOutputStreamClass(null));
+ }
+
+ @Test
+ public void whenCustomOutputStream_thenConvert() throws IOException {
+ assertEquals("world", PrintStreamToStringUtil.usingCustomOutputStream("world"));
+ assertEquals("", PrintStreamToStringUtil.usingCustomOutputStream(""));
+ assertNull(PrintStreamToStringUtil.usingCustomOutputStream(null));
+ }
+
+ @Test
+ public void whenUsingApacheCommonsIO_thenConvert() {
+ assertEquals("hello", PrintStreamToStringUtil.usingApacheCommonsIO("hello"));
+ assertEquals("", PrintStreamToStringUtil.usingApacheCommonsIO(""));
+ assertNull(PrintStreamToStringUtil.usingApacheCommonsIO(null));
+ }
+}
diff --git a/core-java-modules/core-java-io-conversions/pom.xml b/core-java-modules/core-java-io-conversions/pom.xml
index 8d5a47a1ac07..a44c352df285 100644
--- a/core-java-modules/core-java-io-conversions/pom.xml
+++ b/core-java-modules/core-java-io-conversions/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io-conversions
- 0.1.0-SNAPSHOT
core-java-io-conversions
jar
diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml
index e645534b46fa..ce072e687567 100644
--- a/core-java-modules/core-java-io/pom.xml
+++ b/core-java-modules/core-java-io/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io
- 0.1.0-SNAPSHOT
core-java-io
jar
diff --git a/core-java-modules/core-java-jar/pom.xml b/core-java-modules/core-java-jar/pom.xml
index 0ce2414f1e22..e4a43bdf1f35 100644
--- a/core-java-modules/core-java-jar/pom.xml
+++ b/core-java-modules/core-java-jar/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-jar
- 0.1.0-SNAPSHOT
core-java-jar
jar
diff --git a/core-java-modules/core-java-jndi/pom.xml b/core-java-modules/core-java-jndi/pom.xml
index 752700c39036..e48bec6622e3 100644
--- a/core-java-modules/core-java-jndi/pom.xml
+++ b/core-java-modules/core-java-jndi/pom.xml
@@ -3,9 +3,7 @@
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">
4.0.0
- com.baeldung.jndi
core-java-jndi
- 1.0-SNAPSHOT
core-java-jndi
diff --git a/core-java-modules/core-java-jpms/pom.xml b/core-java-modules/core-java-jpms/pom.xml
index 62aa49f29956..3cfa0e3f454e 100644
--- a/core-java-modules/core-java-jpms/pom.xml
+++ b/core-java-modules/core-java-jpms/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-jpms
- 0.0.1-SNAPSHOT
core-java-jpms
pom
@@ -15,8 +14,8 @@
- decoupling-pattern1
- decoupling-pattern2
+ service-provider-factory-pattern
+ service-loader-api-pattern
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/pom.xml b/core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/pom.xml
similarity index 92%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/pom.xml
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/pom.xml
index 13d0b2d201a7..f928912ffdfe 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/pom.xml
+++ b/core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/pom.xml
@@ -8,8 +8,8 @@
1.0
- com.baeldung.decoupling-pattern2
- decoupling-pattern2
+ com.baeldung.service-loader-api-pattern
+ service-loader-api-pattern
1.0-SNAPSHOT
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/src/main/java/com/baeldung/consumermodule/Application.java b/core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/src/main/java/com/baeldung/consumermodule/Application.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/src/main/java/com/baeldung/consumermodule/Application.java
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/src/main/java/com/baeldung/consumermodule/Application.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/src/main/java/module-info.java b/core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/src/main/java/module-info.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/src/main/java/module-info.java
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/src/main/java/module-info.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml b/core-java-modules/core-java-jpms/service-loader-api-pattern/pom.xml
similarity index 92%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/pom.xml
index 5b2e4cfc8289..13a443eab5cb 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml
+++ b/core-java-modules/core-java-jpms/service-loader-api-pattern/pom.xml
@@ -3,8 +3,8 @@
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">
4.0.0
- com.baeldung.decoupling-pattern2
- decoupling-pattern2
+ com.baeldung.service-loader-api-pattern
+ service-loader-api-pattern
1.0-SNAPSHOT
pom
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml b/core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/pom.xml
similarity index 91%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/pom.xml
index ddb8aeccd13b..bcee01f63194 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml
+++ b/core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/pom.xml
@@ -8,8 +8,8 @@
1.0
- com.baeldung.decoupling-pattern2
- decoupling-pattern2
+ com.baeldung.service-loader-api-pattern
+ service-loader-api-pattern
1.0-SNAPSHOT
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/src/main/java/com/baeldung/providermodule/LowercaseTextService.java b/core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/src/main/java/com/baeldung/providermodule/LowercaseTextService.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/src/main/java/com/baeldung/providermodule/LowercaseTextService.java
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/src/main/java/com/baeldung/providermodule/LowercaseTextService.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/src/main/java/module-info.java b/core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/src/main/java/module-info.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/src/main/java/module-info.java
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/src/main/java/module-info.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/pom.xml b/core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/pom.xml
similarity index 88%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/pom.xml
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/pom.xml
index 06ef9000926f..f40745541ba3 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/pom.xml
+++ b/core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/pom.xml
@@ -8,8 +8,8 @@
1.0
- com.baeldung.decoupling-pattern2
- decoupling-pattern2
+ com.baeldung.service-loader-api-pattern
+ service-loader-api-pattern
1.0-SNAPSHOT
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/src/main/java/com/baeldung/servicemodule/TextService.java b/core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/src/main/java/com/baeldung/servicemodule/TextService.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/src/main/java/com/baeldung/servicemodule/TextService.java
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/src/main/java/com/baeldung/servicemodule/TextService.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/src/main/java/module-info.java b/core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/src/main/java/module-info.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/src/main/java/module-info.java
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/src/main/java/module-info.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/pom.xml b/core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/pom.xml
similarity index 89%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/pom.xml
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/pom.xml
index f82e72b85dfa..ba92733f34fa 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/pom.xml
+++ b/core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/pom.xml
@@ -8,8 +8,8 @@
jar
- com.baeldung.decoupling-pattern1
- decoupling-pattern1
+ com.baeldung.service-provider-factory-pattern
+ service-provider-factory-pattern
1.0-SNAPSHOT
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/src/main/java/com/baeldung/consumermodule/Application.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/src/main/java/com/baeldung/consumermodule/Application.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/src/main/java/com/baeldung/consumermodule/Application.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/src/main/java/com/baeldung/consumermodule/Application.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/src/main/java/module-info.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/src/main/java/module-info.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/src/main/java/module-info.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/src/main/java/module-info.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml b/core-java-modules/core-java-jpms/service-provider-factory-pattern/pom.xml
similarity index 91%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/pom.xml
index 2121b46b82d5..35a99123120e 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml
+++ b/core-java-modules/core-java-jpms/service-provider-factory-pattern/pom.xml
@@ -3,8 +3,8 @@
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">
4.0.0
- com.baeldung.decoupling-pattern1
- decoupling-pattern1
+ com.baeldung.service-provider-factory-pattern
+ service-provider-factory-pattern
1.0-SNAPSHOT
pom
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/pom.xml b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/pom.xml
similarity index 86%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/pom.xml
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/pom.xml
index fc4b5854f993..d6e50ee9ff4f 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/pom.xml
+++ b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/pom.xml
@@ -9,8 +9,8 @@
jar
- com.baeldung.decoupling-pattern1
- decoupling-pattern1
+ com.baeldung.service-provider-factory-pattern
+ service-provider-factory-pattern
1.0-SNAPSHOT
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextService.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextService.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextService.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextService.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextServiceFactory.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextServiceFactory.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextServiceFactory.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextServiceFactory.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/LowercaseTextService.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/LowercaseTextService.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/LowercaseTextService.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/LowercaseTextService.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/UppercaseTextService.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/UppercaseTextService.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/UppercaseTextService.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/UppercaseTextService.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/module-info.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/module-info.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/module-info.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/module-info.java
diff --git a/core-java-modules/core-java-jvm-2/pom.xml b/core-java-modules/core-java-jvm-2/pom.xml
index 59d2842ffed4..2ccc847a6f19 100644
--- a/core-java-modules/core-java-jvm-2/pom.xml
+++ b/core-java-modules/core-java-jvm-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-jvm-2
- 0.1.0-SNAPSHOT
core-java-jvm-2
jar
@@ -47,10 +46,8 @@
0.10
0.10.2
-
11
11
-
\ No newline at end of file
diff --git a/core-java-modules/core-java-jvm-3/pom.xml b/core-java-modules/core-java-jvm-3/pom.xml
index cb2d8b0b85f5..78f4201c942d 100644
--- a/core-java-modules/core-java-jvm-3/pom.xml
+++ b/core-java-modules/core-java-jvm-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-jvm-3
- 0.1.0-SNAPSHOT
core-java-jvm-3
jar
@@ -14,7 +13,4 @@
0.0.1-SNAPSHOT
-
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml
index 856c6356a453..52bdf8bc5da0 100644
--- a/core-java-modules/core-java-jvm/pom.xml
+++ b/core-java-modules/core-java-jvm/pom.xml
@@ -1,10 +1,9 @@
+ 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">
4.0.0
core-java-jvm
- 0.1.0-SNAPSHOT
core-java-jvm
jar
diff --git a/core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/PrintClassLoader.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/PrintClassLoader.java
index b976ac99f28f..cd7000b41997 100644
--- a/core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/PrintClassLoader.java
+++ b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/PrintClassLoader.java
@@ -1,5 +1,7 @@
package com.baeldung.classloader;
+import java.sql.DriverManager;
+
import java.util.ArrayList;
public class PrintClassLoader {
@@ -7,6 +9,7 @@ public class PrintClassLoader {
public void printClassLoaders() throws ClassNotFoundException {
System.out.println("Classloader of this class:" + PrintClassLoader.class.getClassLoader());
+ System.out.println("Classloader of DriverManager:" + DriverManager.class.getClassLoader());
System.out.println("Classloader of ArrayList:" + ArrayList.class.getClassLoader());
}
diff --git a/core-java-modules/core-java-lambdas/README.md b/core-java-modules/core-java-lambdas/README.md
index 56b2a79e7e9d..cad209767387 100644
--- a/core-java-modules/core-java-lambdas/README.md
+++ b/core-java-modules/core-java-lambdas/README.md
@@ -10,4 +10,3 @@
- [Serialize a Lambda in Java](https://www.baeldung.com/java-serialize-lambda)
- [Convert Anonymous Class into Lambda in Java](https://www.baeldung.com/java-from-anonymous-class-to-lambda)
- [When to Use Callable and Supplier in Java](https://www.baeldung.com/java-callable-vs-supplier)
-- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)
diff --git a/core-java-modules/core-java-lambdas/pom.xml b/core-java-modules/core-java-lambdas/pom.xml
index f1e61ab8bfcd..a7fc5355d76f 100644
--- a/core-java-modules/core-java-lambdas/pom.xml
+++ b/core-java-modules/core-java-lambdas/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lambdas
- 0.1.0-SNAPSHOT
core-java-lambdas
jar
diff --git a/core-java-modules/core-java-lang-2/pom.xml b/core-java-modules/core-java-lang-2/pom.xml
index 4a89a2257725..22055cf252d0 100644
--- a/core-java-modules/core-java-lang-2/pom.xml
+++ b/core-java-modules/core-java-lang-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-2
- 0.1.0-SNAPSHOT
core-java-lang-2
jar
diff --git a/core-java-modules/core-java-lang-3/pom.xml b/core-java-modules/core-java-lang-3/pom.xml
index 331d91dff6f3..f29fa6494a56 100644
--- a/core-java-modules/core-java-lang-3/pom.xml
+++ b/core-java-modules/core-java-lang-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-3
- 0.1.0-SNAPSHOT
core-java-lang-3
jar
diff --git a/core-java-modules/core-java-lang-4/pom.xml b/core-java-modules/core-java-lang-4/pom.xml
index de67ddf55a8a..6977621a0ea8 100644
--- a/core-java-modules/core-java-lang-4/pom.xml
+++ b/core-java-modules/core-java-lang-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-4
- 0.1.0-SNAPSHOT
core-java-lang-4
jar
diff --git a/core-java-modules/core-java-lang-5/pom.xml b/core-java-modules/core-java-lang-5/pom.xml
index e3130632fbbd..8e95fc4405e0 100644
--- a/core-java-modules/core-java-lang-5/pom.xml
+++ b/core-java-modules/core-java-lang-5/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-5
- 0.1.0-SNAPSHOT
core-java-lang-5
jar
@@ -13,12 +12,6 @@
core-java-modules
0.0.1-SNAPSHOT
-
-
- 3.12.0
- 0.10.2
-
-
core-java-lang-5
@@ -29,4 +22,10 @@
+
+
+ 3.12.0
+ 0.10.2
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/rawtypes/RawTypesUnitTest.java b/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/rawtypes/RawTypesUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/rawtypes/RawTypesUnitTest.java
rename to core-java-modules/core-java-lang-5/src/test/java/com/baeldung/rawtypes/RawTypesUnitTest.java
diff --git a/core-java-modules/core-java-lang-math-2/pom.xml b/core-java-modules/core-java-lang-math-2/pom.xml
index e6ead5335015..223c791d354c 100644
--- a/core-java-modules/core-java-lang-math-2/pom.xml
+++ b/core-java-modules/core-java-lang-math-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-math-2
- 0.0.1-SNAPSHOT
core-java-lang-math-2
diff --git a/core-java-modules/core-java-lang-math-3/README.md b/core-java-modules/core-java-lang-math-3/README.md
index 89adc231000a..847bd314a7ee 100644
--- a/core-java-modules/core-java-lang-math-3/README.md
+++ b/core-java-modules/core-java-lang-math-3/README.md
@@ -10,4 +10,5 @@
- [Create a BMI Calculator in Java](https://www.baeldung.com/java-body-mass-index-calculator)
- [Java Program to Calculate the Standard Deviation](https://www.baeldung.com/java-calculate-standard-deviation)
- [Java Program to Print Pascal’s Triangle](https://www.baeldung.com/java-pascal-triangle)
+- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)
diff --git a/core-java-modules/core-java-lang-math-3/pom.xml b/core-java-modules/core-java-lang-math-3/pom.xml
index 38cb6dfa17f0..7860f57735c1 100644
--- a/core-java-modules/core-java-lang-math-3/pom.xml
+++ b/core-java-modules/core-java-lang-math-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-math-3
- 0.0.1-SNAPSHOT
core-java-lang-math-3
@@ -24,11 +23,17 @@
javaluator
${javaluator.version}
+
+ org.javamoney
+ moneta
+ ${javamoney.moneta.version}
+
0.4.8
3.0.3
+ 1.1
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/money/JavaMoney.java b/core-java-modules/core-java-lang-math-3/src/main/java/com/baeldung/money/JavaMoney.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/money/JavaMoney.java
rename to core-java-modules/core-java-lang-math-3/src/main/java/com/baeldung/money/JavaMoney.java
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
rename to core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
diff --git a/core-java-modules/core-java-lang-math/pom.xml b/core-java-modules/core-java-lang-math/pom.xml
index 37550b67d8e2..551e5db1d592 100644
--- a/core-java-modules/core-java-lang-math/pom.xml
+++ b/core-java-modules/core-java-lang-math/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-math
- 0.1.0-SNAPSHOT
core-java-lang-math
jar
diff --git a/core-java-modules/core-java-lang-oop-constructors-2/README.md b/core-java-modules/core-java-lang-oop-constructors-2/README.md
new file mode 100644
index 000000000000..d9b162c7a6ae
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors-2/README.md
@@ -0,0 +1,7 @@
+## Core Java Lang OOP - Constructors - Part 2
+
+This module contains article about constructors in Java
+
+### Relevant Articles:
+- [Different Ways to Create an Object in Java](https://www.baeldung.com/java-different-ways-to-create-objects)
+- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-oop-constructors)
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-constructors-2/pom.xml b/core-java-modules/core-java-lang-oop-constructors-2/pom.xml
new file mode 100644
index 000000000000..c6d9d847740a
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors-2/pom.xml
@@ -0,0 +1,16 @@
+
+
+ 4.0.0
+ core-java-lang-oop-constructors-2
+ core-java-lang-oop-constructors-2
+ jar
+
+
+ core-java-modules
+ com.baeldung.core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/ClonableRabbit.java b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/ClonableRabbit.java
similarity index 100%
rename from core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/ClonableRabbit.java
rename to core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/ClonableRabbit.java
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/Rabbit.java b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/Rabbit.java
similarity index 100%
rename from core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/Rabbit.java
rename to core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/Rabbit.java
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/RabbitType.java b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/RabbitType.java
similarity index 100%
rename from core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/RabbitType.java
rename to core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/RabbitType.java
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/SerializableRabbit.java b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/SerializableRabbit.java
similarity index 100%
rename from core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/SerializableRabbit.java
rename to core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/SerializableRabbit.java
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/utils/CreateRabbits.java b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/utils/CreateRabbits.java
similarity index 100%
rename from core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/utils/CreateRabbits.java
rename to core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/utils/CreateRabbits.java
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/objectcreation/CreateRabbitsUnitTest.java b/core-java-modules/core-java-lang-oop-constructors-2/src/test/java/com/baeldung/objectcreation/CreateRabbitsUnitTest.java
similarity index 100%
rename from core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/objectcreation/CreateRabbitsUnitTest.java
rename to core-java-modules/core-java-lang-oop-constructors-2/src/test/java/com/baeldung/objectcreation/CreateRabbitsUnitTest.java
diff --git a/core-java-modules/core-java-lang-oop-constructors/README.md b/core-java-modules/core-java-lang-oop-constructors/README.md
index 4ac9224bb119..c35cb836a5b0 100644
--- a/core-java-modules/core-java-lang-oop-constructors/README.md
+++ b/core-java-modules/core-java-lang-oop-constructors/README.md
@@ -13,4 +13,4 @@ This module contains article about constructors in Java
- [Constructor Specification in Java](https://www.baeldung.com/java-constructor-specification)
- [Static vs. Instance Initializer Block in Java](https://www.baeldung.com/java-static-instance-initializer-blocks)
- [Accessing Private Constructor in Java](https://www.baeldung.com/java-private-constructor-access)
-- [Different Ways to Create an Object in Java](https://www.baeldung.com/java-different-ways-to-create-objects)
+- More articles: [[next -->]](/core-java-modules/core-java-lang-oop-constructors-2)
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-methods/README.md b/core-java-modules/core-java-lang-oop-methods/README.md
index f34606f26a73..053cafac3ecf 100644
--- a/core-java-modules/core-java-lang-oop-methods/README.md
+++ b/core-java-modules/core-java-lang-oop-methods/README.md
@@ -11,3 +11,4 @@ This module contains articles about methods in Java
- [The Covariant Return Type in Java](https://www.baeldung.com/java-covariant-return-type)
- [Does a Method’s Signature Include the Return Type in Java?](https://www.baeldung.com/java-method-signature-return-type)
- [Solving the Hide Utility Class Public Constructor Sonar Warning](https://www.baeldung.com/java-sonar-hide-implicit-constructor)
+- [Best Practices for Passing Many Arguments to a Method in Java](https://www.baeldung.com/java-best-practices-many-parameters-method)
diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Car.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Car.java
new file mode 100644
index 000000000000..a72d7dd0f1be
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Car.java
@@ -0,0 +1,98 @@
+package com.baeldung.methods;
+
+public class Car {
+
+ private final String make;
+ private final String model;
+ private final int year;
+ private final String color;
+ private final boolean automatic;
+ private final int numDoors;
+ private final String features;
+
+ private Car(CarBuilder carBuilder) {
+ this.make = carBuilder.make;
+ this.model = carBuilder.model;
+ this.year = carBuilder.year;
+ this.color = carBuilder.color;
+ this.automatic = carBuilder.automatic;
+ this.numDoors = carBuilder.numDoors;
+ this.features = carBuilder.features;
+ }
+
+ public String getMake() {
+ return make;
+ }
+
+ public String getModel() {
+ return model;
+ }
+
+ public int getYear() {
+ return year;
+ }
+
+ public String getColor() {
+ return color;
+ }
+
+ public boolean isAutomatic() {
+ return automatic;
+ }
+
+ public int getNumDoors() {
+ return numDoors;
+ }
+
+ public String getFeatures() {
+ return features;
+ }
+
+ public static class CarBuilder {
+
+ private final String make;
+ private final String model;
+ private final int year;
+
+ private String color = "unknown";
+ private boolean automatic = false;
+ private int numDoors = 4;
+ private String features = "";
+
+ public CarBuilder(String make, String model, int year) {
+ this.make = make;
+ this.model = model;
+ this.year = year;
+ }
+
+ public CarBuilder color(String color) {
+ this.color = color;
+ return this;
+ }
+
+ public CarBuilder automatic(boolean automatic) {
+ this.automatic = automatic;
+ return this;
+ }
+
+ public CarBuilder numDoors(int numDoors) {
+ this.numDoors = numDoors;
+ return this;
+ }
+
+ public CarBuilder features(String features) {
+ this.features = features;
+ return this;
+ }
+
+ public Car build() {
+ return new Car(this);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "Car [make=" + make + ", model=" + model + ", year=" + year + ", color=" + color + ", automatic=" + automatic + ", numDoors=" + numDoors + ", features=" + features + "]";
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Motorcycle.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Motorcycle.java
new file mode 100644
index 000000000000..8a1fce4a5dfc
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Motorcycle.java
@@ -0,0 +1,52 @@
+package com.baeldung.methods;
+
+import java.io.Serializable;
+
+public class Motorcycle extends Vehicle implements Serializable {
+
+ private static final long serialVersionUID = 5973661295933599929L;
+
+ private int year;
+ private String features = "";
+
+ public Motorcycle() {
+ super();
+ }
+
+ public Motorcycle(String make, String model, String color, int weight, boolean statusNew, int year) {
+ super(make, model, color, weight, statusNew);
+ this.year = year;
+ }
+
+ public Motorcycle(Vehicle vehicle, int year) {
+ super(vehicle);
+ this.year = year;
+ }
+
+ public int getYear() {
+ return year;
+ }
+
+ public void setYear(int year) {
+ this.year = year;
+ }
+
+ public void setFeatures(String features) {
+ this.features = features;
+ }
+
+ public String getFeatures() {
+ return features;
+ }
+
+ public void addMotorcycleFeatures(String... features) {
+ StringBuilder str = new StringBuilder(this.getFeatures());
+ for (String feature : features) {
+ if (!str.toString().isEmpty())
+ str.append(", ");
+ str.append(feature);
+ }
+ this.setFeatures(str.toString());
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Vehicle.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Vehicle.java
new file mode 100644
index 000000000000..0c6964d255b7
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Vehicle.java
@@ -0,0 +1,33 @@
+package com.baeldung.methods;
+
+public class Vehicle {
+
+ static String defaultValue = "DEFAULT";
+ private String make = defaultValue;
+ private String model = defaultValue;
+ private String color = defaultValue;
+ private int weight = 0;
+ private boolean statusNew = true;
+
+ public Vehicle() {
+ super();
+ }
+
+ public Vehicle(String make, String model, String color, int weight, boolean statusNew) {
+ this.make = make;
+ this.model = model;
+ this.color = color;
+ this.weight = weight;
+ this.statusNew = statusNew;
+ }
+
+ public Vehicle(Vehicle vehicle) {
+ this(vehicle.make, vehicle.model, vehicle.color, vehicle.weight, vehicle.statusNew);
+ }
+
+ @Override
+ public String toString() {
+ return "Vehicle [make=" + make + ", model=" + model + ", color=" + color + ", weight=" + weight + ", statusNew=" + statusNew + "]";
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/VehicleProcessor.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/VehicleProcessor.java
new file mode 100644
index 000000000000..a7d597581335
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/VehicleProcessor.java
@@ -0,0 +1,20 @@
+package com.baeldung.methods;
+
+public class VehicleProcessor {
+
+ Vehicle processVehicle(String make, String model, String color, int weight, boolean status) {
+ return new Vehicle(make, model, color, weight, status);
+ }
+
+ Vehicle processVehicle(Vehicle vehicle) {
+ return new Vehicle(vehicle);
+ }
+
+ Car processCar(Car car) {
+ return new Car.CarBuilder(car.getMake(), car.getModel(), car.getYear()).color(car.getColor())
+ .automatic(car.isAutomatic())
+ .features(car.getFeatures())
+ .build();
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/methods/VehicleProcessorUnitTest.java b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/methods/VehicleProcessorUnitTest.java
new file mode 100644
index 000000000000..928fbcb4269a
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/methods/VehicleProcessorUnitTest.java
@@ -0,0 +1,58 @@
+package com.baeldung.methods;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+class VehicleProcessorUnitTest {
+
+ VehicleProcessor vehicleProcessor = new VehicleProcessor();
+ Vehicle vehicle = new Vehicle("Ford", "Focus", "red", 2200, true);
+
+ @Test
+ void givenAllArguments_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
+ Vehicle veh = vehicleProcessor.processVehicle("Ford", "Focus", "red", 2200, true);
+ assertThat(veh.toString()).hasToString(vehicle.toString());
+ }
+
+ @Test
+ void givenParameterObject_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
+ Vehicle veh = vehicleProcessor.processVehicle(vehicle);
+ assertThat(veh.toString()).hasToString(vehicle.toString());
+ }
+
+ @Test
+ void givenJavaBeanPattern_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
+ Motorcycle motorcycle = new Motorcycle("Ducati", "Monster", "yellow", 235, true, 2023);
+ motorcycle.setFeatures("GPS");
+
+ vehicleProcessor.processVehicle(motorcycle);
+ assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("GPS");
+ }
+
+ @Test
+ void givenJavaVarargs_whenMethodCall_thenAssertTheReturnedConcatenatedString() {
+ Motorcycle motorcycle = new Motorcycle("Ducati", "Monster", "red", 350, true, 2023);
+ motorcycle.addMotorcycleFeatures("abs");
+ assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs");
+
+ motorcycle.addMotorcycleFeatures("navi", "charger");
+ assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs, navi, charger");
+
+ motorcycle.addMotorcycleFeatures("wifi", "phone", "satellite");
+ assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs, navi, charger, wifi, phone, satellite");
+ }
+
+ @Test
+ void givenJavaBuilderPattern_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
+ Car car = new Car.CarBuilder("Ford", "Focus", 2023).color("blue")
+ .automatic(true)
+ .features("abs, navi, charger, wifi, phone, satellite")
+ .build();
+
+ Car result = vehicleProcessor.processCar(car);
+
+ assertThat(result.toString()).hasToString(car.toString());
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-modifiers/pom.xml b/core-java-modules/core-java-lang-oop-modifiers/pom.xml
index c193073a0ee6..459aa217211c 100644
--- a/core-java-modules/core-java-lang-oop-modifiers/pom.xml
+++ b/core-java-modules/core-java-lang-oop-modifiers/pom.xml
@@ -23,7 +23,7 @@
- 1.4.197
+ 2.1.214
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/staticclass/Pizza.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticclass/Pizza.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/staticclass/Pizza.java
rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticclass/Pizza.java
diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Car.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Car.java
index 950f008dcd9b..1158851fbdb0 100644
--- a/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Car.java
+++ b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Car.java
@@ -42,6 +42,10 @@ public void setEngine(String engine) {
this.engine = engine;
}
+ public static String getCarsInformation(Car car) {
+ return car.getName() + "-" + car.getEngine();
+ }
+
public static void setNumberOfCars(int numberOfCars) {
Car.numberOfCars = numberOfCars;
}
diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmethod/CallNonStaticMethodUnitTest.java b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmethod/CallNonStaticMethodUnitTest.java
new file mode 100644
index 000000000000..1171cb2e7a75
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmethod/CallNonStaticMethodUnitTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.staticmethod;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.AfterClass;
+import org.junit.Test;
+
+import com.baeldung.staticmodifier.Car;
+
+public class CallNonStaticMethodUnitTest {
+ @AfterClass
+ public static void setUpCarInstance() {
+ Car.setNumberOfCars(0);
+ }
+ @Test
+ public void whenCallingNonStaticMethodInStaticMethodWithInstanceClass_thenSuccess() {
+ Car car = new Car("Jaguar", "V8");
+ assertEquals("Jaguar-V8", Car.getCarsInformation(car));
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/CarUnitTest.java b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/CarUnitTest.java
index f55955caa8b2..68bbe8f0a240 100644
--- a/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/CarUnitTest.java
+++ b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/CarUnitTest.java
@@ -2,9 +2,16 @@
import static org.junit.Assert.*;
+import org.junit.AfterClass;
import org.junit.Test;
public class CarUnitTest {
+
+ @AfterClass
+ public static void setUpCarInstance() {
+ Car.setNumberOfCars(0);
+ }
+
@Test
public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() {
new Car("Jaguar", "V8");
diff --git a/core-java-modules/core-java-lang-oop-patterns/README.md b/core-java-modules/core-java-lang-oop-patterns/README.md
index df68a1413a2e..ea3309dc0adc 100644
--- a/core-java-modules/core-java-lang-oop-patterns/README.md
+++ b/core-java-modules/core-java-lang-oop-patterns/README.md
@@ -8,3 +8,4 @@ This module contains articles about Object-oriented programming (OOP) patterns i
- [Immutable Objects in Java](https://www.baeldung.com/java-immutable-object)
- [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)
diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Animal.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Animal.java
new file mode 100644
index 000000000000..b20c01cac990
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Animal.java
@@ -0,0 +1,5 @@
+package com.baeldung.interfacesingleimpl;
+
+public interface Animal {
+ String makeSound();
+}
diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/AnimalCare.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/AnimalCare.java
new file mode 100644
index 000000000000..0d7b73205640
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/AnimalCare.java
@@ -0,0 +1,13 @@
+package com.baeldung.interfacesingleimpl;
+
+public class AnimalCare {
+ private Animal animal;
+
+ public AnimalCare(Animal animal) {
+ this.animal = animal;
+ }
+
+ public String animalSound() {
+ return animal.makeSound();
+ }
+}
diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Cat.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Cat.java
new file mode 100644
index 000000000000..7540e0823bd6
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Cat.java
@@ -0,0 +1,21 @@
+package com.baeldung.interfacesingleimpl;
+
+public class Cat {
+ private String name;
+
+ public Cat(String name) {
+ this.name = name;
+ }
+
+ public String makeSound() {
+ return "Meow! My name is " + name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Dog.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Dog.java
new file mode 100644
index 000000000000..1dfd3bea0dce
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/interfacesingleimpl/Dog.java
@@ -0,0 +1,22 @@
+package com.baeldung.interfacesingleimpl;
+
+public class Dog implements Animal {
+ private String name;
+
+ public Dog(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String makeSound() {
+ return "Woof! My name is " + name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/InterfaceSingleImplUnitTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/InterfaceSingleImplUnitTest.java
new file mode 100644
index 000000000000..4044a554a304
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/InterfaceSingleImplUnitTest.java
@@ -0,0 +1,51 @@
+package com.baeldung.interfacesingleimpl;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.Test;
+
+public class InterfaceSingleImplUnitTest {
+ @Test
+ public void whenUsingMockAnimal_thenAnimalSoundIsCorrect() {
+ MockAnimal mockAnimal = new MockAnimal();
+ String expected = "Mock animal sound!";
+ AnimalCare animalCare = new AnimalCare(mockAnimal);
+ assertThat(animalCare.animalSound()).isEqualTo(expected);
+ }
+
+ @Test
+ public void whenCreatingDog_thenDogMakesWoofSound() {
+ Dog dog = new Dog("Buddy");
+ String expected = "Woof! My name is Buddy";
+ assertThat(dog.makeSound()).isEqualTo(expected);
+ }
+
+ @Test
+ public void whenCreatingCat_thenCatMakesMeowSound() {
+ Cat cat = new Cat("FuzzBall");
+ String expected = "Meow! My name is FuzzBall";
+ assertThat(cat.makeSound()).isEqualTo(expected);
+ }
+
+ @Test
+ public void whenCreatingAnimalCareWithDog_thenDogMakesWoofSound() {
+ Animal dog = new Dog("Ham");
+ AnimalCare animalCare = new AnimalCare(dog);
+ String expected = "Woof! My name is Ham";
+ assertThat(animalCare.animalSound()).isEqualTo(expected);
+ }
+
+ @Test
+ public void whenCreatingCatCareWithCat_thenCatMakesMeowSound() {
+ Cat cat = new Cat("Grumpy");
+ String expected = "Meow! My name is Grumpy";
+ assertThat(cat.makeSound()).isEqualTo(expected);
+ }
+
+ @Test
+ public void whenCreatingMockAnimal_thenMockAnimalMakesMockAnimalSound() {
+ MockAnimal mockAnimal = new MockAnimal();
+ String expected = "Mock animal sound!";
+ assertThat(mockAnimal.makeSound()).isEqualTo(expected);
+ }
+}
diff --git a/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/MockAnimal.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/MockAnimal.java
new file mode 100644
index 000000000000..1d3b264f45d4
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/interfacesingleimpl/MockAnimal.java
@@ -0,0 +1,8 @@
+package com.baeldung.interfacesingleimpl;
+
+public class MockAnimal implements Animal {
+ @Override
+ public String makeSound() {
+ return "Mock animal sound!";
+ }
+}
diff --git a/core-java-modules/core-java-lang-operators-2/pom.xml b/core-java-modules/core-java-lang-operators-2/pom.xml
index 9d925c553a94..4170f9f6a05a 100644
--- a/core-java-modules/core-java-lang-operators-2/pom.xml
+++ b/core-java-modules/core-java-lang-operators-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-operators-2
- 0.1.0-SNAPSHOT
core-java-lang-operators-2
jar
diff --git a/core-java-modules/core-java-lang-operators/pom.xml b/core-java-modules/core-java-lang-operators/pom.xml
index c61fb8135465..1815d01dcca9 100644
--- a/core-java-modules/core-java-lang-operators/pom.xml
+++ b/core-java-modules/core-java-lang-operators/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-operators
- 0.1.0-SNAPSHOT
core-java-lang-operators
jar
diff --git a/core-java-modules/core-java-lang-syntax-2/pom.xml b/core-java-modules/core-java-lang-syntax-2/pom.xml
index fdb050317437..bae5f0b6bd63 100644
--- a/core-java-modules/core-java-lang-syntax-2/pom.xml
+++ b/core-java-modules/core-java-lang-syntax-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-syntax-2
- 0.1.0-SNAPSHOT
core-java-lang-syntax-2
jar
diff --git a/core-java-modules/core-java-lang-syntax/pom.xml b/core-java-modules/core-java-lang-syntax/pom.xml
index 7cdbc40fbc4c..005bdc73cccb 100644
--- a/core-java-modules/core-java-lang-syntax/pom.xml
+++ b/core-java-modules/core-java-lang-syntax/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-syntax
- 0.1.0-SNAPSHOT
core-java-lang-syntax
jar
diff --git a/core-java-modules/core-java-lang/pom.xml b/core-java-modules/core-java-lang/pom.xml
index 4989c6a5a702..27cf0ac27644 100644
--- a/core-java-modules/core-java-lang/pom.xml
+++ b/core-java-modules/core-java-lang/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang
- 0.1.0-SNAPSHOT
core-java-lang
jar
diff --git a/core-java-modules/core-java-locale/README.md b/core-java-modules/core-java-locale/README.md
new file mode 100644
index 000000000000..744b5e760f3c
--- /dev/null
+++ b/core-java-modules/core-java-locale/README.md
@@ -0,0 +1,6 @@
+ Core Java Locale
+
+### Relevant Articles:
+
+- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
+
diff --git a/core-java-modules/core-java-locale/pom.xml b/core-java-modules/core-java-locale/pom.xml
new file mode 100644
index 000000000000..f493d572a131
--- /dev/null
+++ b/core-java-modules/core-java-locale/pom.xml
@@ -0,0 +1,20 @@
+
+
+ 4.0.0
+ core-java-locale
+ 0.1.0-SNAPSHOT
+ core-java-locale
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleControl.java b/core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleControl.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleControl.java
rename to core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleControl.java
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleResource.java b/core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleResource.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleResource.java
rename to core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleResource.java
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl.java b/core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl.java
rename to core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl.java
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl_PL.java b/core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl_PL.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl_PL.java
rename to core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl_PL.java
diff --git a/core-java-modules/core-java/src/main/resources/resourcebundle/resource.properties b/core-java-modules/core-java-locale/src/main/resources/resourcebundle/resource.properties
similarity index 100%
rename from core-java-modules/core-java/src/main/resources/resourcebundle/resource.properties
rename to core-java-modules/core-java-locale/src/main/resources/resourcebundle/resource.properties
diff --git a/core-java-modules/core-java/src/main/resources/resourcebundle/resource_en.properties b/core-java-modules/core-java-locale/src/main/resources/resourcebundle/resource_en.properties
similarity index 100%
rename from core-java-modules/core-java/src/main/resources/resourcebundle/resource_en.properties
rename to core-java-modules/core-java-locale/src/main/resources/resourcebundle/resource_en.properties
diff --git a/core-java-modules/core-java/src/main/resources/resourcebundle/resource_pl_PL.properties b/core-java-modules/core-java-locale/src/main/resources/resourcebundle/resource_pl_PL.properties
similarity index 100%
rename from core-java-modules/core-java/src/main/resources/resourcebundle/resource_pl_PL.properties
rename to core-java-modules/core-java-locale/src/main/resources/resourcebundle/resource_pl_PL.properties
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/resourcebundle/ExampleResourceUnitTest.java b/core-java-modules/core-java-locale/src/test/java/com/baeldung/resourcebundle/ExampleResourceUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/resourcebundle/ExampleResourceUnitTest.java
rename to core-java-modules/core-java-locale/src/test/java/com/baeldung/resourcebundle/ExampleResourceUnitTest.java
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/resourcebundle/PropertyResourceUnitTest.java b/core-java-modules/core-java-locale/src/test/java/com/baeldung/resourcebundle/PropertyResourceUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/resourcebundle/PropertyResourceUnitTest.java
rename to core-java-modules/core-java-locale/src/test/java/com/baeldung/resourcebundle/PropertyResourceUnitTest.java
diff --git a/core-java-modules/core-java-methods/README.md b/core-java-modules/core-java-methods/README.md
new file mode 100644
index 000000000000..b2208778e70e
--- /dev/null
+++ b/core-java-modules/core-java-methods/README.md
@@ -0,0 +1,6 @@
+=========
+
+## Core Java Methods
+
+### Relevant Articles:
+- [Execute a Method Only Once in Java](https://www.baeldung.com/execute-a-method-only-once-in-java)
\ No newline at end of file
diff --git a/core-java-modules/core-java-methods/pom.xml b/core-java-modules/core-java-methods/pom.xml
new file mode 100644
index 000000000000..5502cc67336f
--- /dev/null
+++ b/core-java-modules/core-java-methods/pom.xml
@@ -0,0 +1,40 @@
+
+
+ 4.0.0
+ core-java-methods
+ 0.1.0-SNAPSHOT
+ core-java-methods
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+
+
+ core-java-methods
+
+
+ src/main/resources
+ true
+
+
+
+
+
+ 3.22.0
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-methods/src/main/java/com/baeldung/executeonce/AtomicBooleanInitializer.java b/core-java-modules/core-java-methods/src/main/java/com/baeldung/executeonce/AtomicBooleanInitializer.java
new file mode 100644
index 000000000000..72ffc427115e
--- /dev/null
+++ b/core-java-modules/core-java-methods/src/main/java/com/baeldung/executeonce/AtomicBooleanInitializer.java
@@ -0,0 +1,19 @@
+package com.baeldung.executeonce;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+final class AtomicBooleanInitializer {
+
+ private final AtomicBoolean isInitialized = new AtomicBoolean(false);
+ int callCount = 0;
+
+ void initialize() {
+ if (isInitialized.compareAndSet(false, true)) {
+ initializationLogic();
+ }
+ }
+
+ private void initializationLogic() {
+ callCount++;
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-methods/src/main/java/com/baeldung/executeonce/StaticInitializer.java b/core-java-modules/core-java-methods/src/main/java/com/baeldung/executeonce/StaticInitializer.java
new file mode 100644
index 000000000000..2896578a8c69
--- /dev/null
+++ b/core-java-modules/core-java-methods/src/main/java/com/baeldung/executeonce/StaticInitializer.java
@@ -0,0 +1,14 @@
+package com.baeldung.executeonce;
+
+final class StaticInitializer {
+
+ static int CALL_COUNT = 0;
+
+ static {
+ initializationLogic();
+ }
+
+ private static void initializationLogic() {
+ CALL_COUNT++;
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-methods/src/main/java/com/baeldung/executeonce/SynchronizedInitializer.java b/core-java-modules/core-java-methods/src/main/java/com/baeldung/executeonce/SynchronizedInitializer.java
new file mode 100644
index 000000000000..79c5fb9c3c99
--- /dev/null
+++ b/core-java-modules/core-java-methods/src/main/java/com/baeldung/executeonce/SynchronizedInitializer.java
@@ -0,0 +1,18 @@
+package com.baeldung.executeonce;
+
+final class SynchronizedInitializer {
+
+ private static volatile boolean isInitialized = false;
+ int callCount = 0;
+
+ synchronized void initialize() {
+ if (!isInitialized) {
+ initializationLogic();
+ isInitialized = true;
+ }
+ }
+
+ private void initializationLogic() {
+ callCount++;
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-methods/src/test/java/com/baeldung/executeonce/AtomicBooleanInitializerUnitTest.java b/core-java-modules/core-java-methods/src/test/java/com/baeldung/executeonce/AtomicBooleanInitializerUnitTest.java
new file mode 100644
index 000000000000..8d72ded2cbd7
--- /dev/null
+++ b/core-java-modules/core-java-methods/src/test/java/com/baeldung/executeonce/AtomicBooleanInitializerUnitTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.executeonce;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+final class AtomicBooleanInitializerUnitTest {
+
+ @Test
+ void givenAtomicBooleanInitializer_whenRepeatedlyCallingInitialize_thenCallCountIsOne() {
+ AtomicBooleanInitializer atomicBooleanInitializer = new AtomicBooleanInitializer();
+ assertEquals(0, atomicBooleanInitializer.callCount);
+
+ atomicBooleanInitializer.initialize();
+ atomicBooleanInitializer.initialize();
+ atomicBooleanInitializer.initialize();
+
+ assertEquals(1, atomicBooleanInitializer.callCount);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-methods/src/test/java/com/baeldung/executeonce/StaticInitializerUnitTest.java b/core-java-modules/core-java-methods/src/test/java/com/baeldung/executeonce/StaticInitializerUnitTest.java
new file mode 100644
index 000000000000..a1620069ee94
--- /dev/null
+++ b/core-java-modules/core-java-methods/src/test/java/com/baeldung/executeonce/StaticInitializerUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.executeonce;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+final class StaticInitializerUnitTest {
+
+ @Test
+ void whenLoadingStaticInitializer_thenCallCountIsOne() {
+ assertEquals(1, StaticInitializer.CALL_COUNT);
+ }
+
+ @Test
+ void whenInitializingStaticInitializer_thenCallCountStaysOne() {
+ StaticInitializer staticInitializer = new StaticInitializer();
+ assertEquals(1, StaticInitializer.CALL_COUNT);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-methods/src/test/java/com/baeldung/executeonce/SynchronizedInitializerUnitTest.java b/core-java-modules/core-java-methods/src/test/java/com/baeldung/executeonce/SynchronizedInitializerUnitTest.java
new file mode 100644
index 000000000000..50eca7c5b7ea
--- /dev/null
+++ b/core-java-modules/core-java-methods/src/test/java/com/baeldung/executeonce/SynchronizedInitializerUnitTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.executeonce;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+final class SynchronizedInitializerUnitTest {
+
+ @Test
+ void givenSynchronizedInitializer_whenRepeatedlyCallingInitialize_thenCallCountIsOne() {
+ SynchronizedInitializer synchronizedInitializer = new SynchronizedInitializer();
+ assertEquals(0, synchronizedInitializer.callCount);
+
+ synchronizedInitializer.initialize();
+ synchronizedInitializer.initialize();
+ synchronizedInitializer.initialize();
+
+ assertEquals(1, synchronizedInitializer.callCount);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-networking-2/pom.xml b/core-java-modules/core-java-networking-2/pom.xml
index 982f4fa3463c..34f16a993875 100644
--- a/core-java-modules/core-java-networking-2/pom.xml
+++ b/core-java-modules/core-java-networking-2/pom.xml
@@ -15,9 +15,9 @@
- org.apache.httpcomponents
- httpclient
- ${httpclient.version}
+ commons-codec
+ commons-codec
+ ${commons-codec.version}
org.apache.commons
@@ -52,11 +52,11 @@
- 4.5.9
2.0.1
2.4.5
2.3.3
2.0.0-alpha-3
+ 1.15
\ No newline at end of file
diff --git a/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/auth/HttpClient.java b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/auth/HttpClient.java
index 779f8aa89859..f9d747a133a2 100644
--- a/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/auth/HttpClient.java
+++ b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/auth/HttpClient.java
@@ -21,7 +21,7 @@ public HttpClient(String user, String password) {
this.password = password;
}
- public int sendRquestWithAuthHeader(String url) throws IOException {
+ public int sendRequestWithAuthHeader(String url) throws IOException {
HttpURLConnection connection = null;
try {
connection = createConnection(url);
@@ -34,7 +34,7 @@ public int sendRquestWithAuthHeader(String url) throws IOException {
}
}
- public int sendRquestWithAuthenticator(String url) throws IOException {
+ public int sendRequestWithAuthenticator(String url) throws IOException {
setAuthenticator();
HttpURLConnection connection = null;
diff --git a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/auth/HttpClientLiveTest.java b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/auth/HttpClientLiveTest.java
index 01d580bc654e..387b22895344 100644
--- a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/auth/HttpClientLiveTest.java
+++ b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/auth/HttpClientLiveTest.java
@@ -7,28 +7,28 @@
public class HttpClientLiveTest {
@Test
- public void sendRquestWithAuthHeader() throws Exception {
+ public void sendRequestWithAuthHeader() throws Exception {
HttpClient httpClient = new HttpClient("user1", "pass1");
- int status = httpClient.sendRquestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
+ int status = httpClient.sendRequestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
assertTrue(isSuccess(status));
}
@Test
- public void sendRquestWithAuthHeader_whenIncorrectCredentials_thenNotSuccessful() throws Exception {
+ public void sendRequestWithAuthHeader_whenIncorrectCredentials_thenNotSuccessful() throws Exception {
HttpClient httpClient = new HttpClient("John", "Smith");
- int status = httpClient.sendRquestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
+ int status = httpClient.sendRequestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
assertTrue(isUnauthorized(status));
}
@Test
- public void sendRquestWithAuthenticator() throws Exception {
+ public void sendRequestWithAuthenticator() throws Exception {
HttpClient httpClient = new HttpClient("user2", "pass2");
- int status = httpClient.sendRquestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
+ int status = httpClient.sendRequestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
assertTrue(isSuccess(status));
}
@@ -37,7 +37,7 @@ public void sendRquestWithAuthenticator() throws Exception {
public void sendRquestWithAuthenticator_whenIncorrectCredentials_thenNotSuccessful() throws Exception {
HttpClient httpClient = new HttpClient("John", "Smith");
- int status = httpClient.sendRquestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
+ int status = httpClient.sendRequestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
assertTrue(isUnauthorized(status));
}
diff --git a/core-java-modules/core-java-networking-4/README.md b/core-java-modules/core-java-networking-4/README.md
index e614801468ff..10ca7caf4140 100644
--- a/core-java-modules/core-java-networking-4/README.md
+++ b/core-java-modules/core-java-networking-4/README.md
@@ -3,3 +3,4 @@
- [Validating URL in Java](https://www.baeldung.com/java-validate-url)
- [Validating IPv4 Address in Java](https://www.baeldung.com/java-validate-ipv4-address)
- [Download a Webpage in Java](https://www.baeldung.com/java-download-webpage)
+- [URL Query Manipulation in Java](https://www.baeldung.com/java-url-query-manipulation)
diff --git a/core-java-modules/core-java-networking-4/pom.xml b/core-java-modules/core-java-networking-4/pom.xml
index a3694cfea860..cbe6356d0fd6 100644
--- a/core-java-modules/core-java-networking-4/pom.xml
+++ b/core-java-modules/core-java-networking-4/pom.xml
@@ -14,7 +14,6 @@
-
commons-validator
commons-validator
@@ -25,7 +24,30 @@
jsoup
${jsoup.version}
-
+
+
+ org.apache.httpcomponents
+ httpclient
+ 4.5.2
+
+
+
+ javax.ws.rs
+ javax.ws.rs-api
+ 2.1.1
+
+
+ org.glassfish.jersey.core
+ jersey-common
+ 2.22.2
+ test
+
+
+
+ org.springframework
+ spring-web
+ 6.0.6
+
diff --git a/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/urlquerymanipulation/UrlQueryManipulationUnitTest.java b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/urlquerymanipulation/UrlQueryManipulationUnitTest.java
new file mode 100644
index 000000000000..cc53a3e3a899
--- /dev/null
+++ b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/urlquerymanipulation/UrlQueryManipulationUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.urlquerymanipulation;
+
+import static junit.framework.TestCase.assertEquals;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import javax.ws.rs.core.UriBuilder;
+
+import org.apache.http.client.utils.URIBuilder;
+
+import org.junit.Test;
+import org.springframework.web.util.UriComponentsBuilder;
+
+public class UrlQueryManipulationUnitTest {
+
+ @Test
+ public void whenUsingApacheUriBuilder_thenParametersAreCorrectlyAdded() throws URISyntaxException {
+ String url = "baeldung.com";
+ String key = "article";
+ String value = "alpha";
+ URI uri = new URIBuilder(url).addParameter(key, value)
+ .build();
+
+ assertEquals("baeldung.com?article=alpha", uri.toString());
+ }
+
+ @Test
+ public void whenUsingJavaUriBuilder_thenParametersAreCorrectlyAdded() {
+ String url = "baeldung.com";
+ String key = "article";
+ String value = "beta";
+ URI uri = UriBuilder.fromUri(url)
+ .queryParam(key, value)
+ .build();
+
+ assertEquals("baeldung.com?article=beta", uri.toString());
+ }
+
+ @Test
+ public void whenUsingSpringUriComponentsBuilder_thenParametersAreCorrectlyAdded() {
+ String url = "baeldung.com";
+ String key = "article";
+ String value = "charlie";
+ URI uri = UriComponentsBuilder.fromUriString(url)
+ .queryParam(key, value)
+ .build()
+ .toUri();
+
+ assertEquals("baeldung.com?article=charlie", uri.toString());
+ }
+
+}
diff --git a/core-java-modules/core-java-networking/pom.xml b/core-java-modules/core-java-networking/pom.xml
index 9974134eaea8..59aadbd1ed39 100644
--- a/core-java-modules/core-java-networking/pom.xml
+++ b/core-java-modules/core-java-networking/pom.xml
@@ -1,10 +1,9 @@
+ 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">
4.0.0
core-java-networking
- 0.1.0-SNAPSHOT
core-java-networking
jar
@@ -20,6 +19,11 @@
spring-web
${springframework.spring-web.version}
+
+ org.apache.httpcomponents
+ httpclient
+ ${apache.httpclient.version}
+
@@ -28,6 +32,7 @@
4.3.4.RELEASE
+ 4.5.14
\ No newline at end of file
diff --git a/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java b/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java
index 112f2cf53fb0..87d9d7a620ec 100644
--- a/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java
+++ b/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java
@@ -1,11 +1,19 @@
package com.baeldung.networking.url;
+import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import java.net.MalformedURLException;
+import java.net.URISyntaxException;
import java.net.URL;
+import java.util.Map;
+import org.apache.http.client.utils.URIBuilder;
+import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;
+import org.springframework.web.util.UriComponentsBuilder;
+
+import com.google.common.collect.ImmutableMap;
public class UrlUnitTest {
@@ -101,4 +109,44 @@ public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() t
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
}
-}
+ @Test
+ public void givenUrlParameters_whenBuildUrlWithURIBuilder_thenSuccess() throws URISyntaxException, MalformedURLException {
+ URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles");
+ uriBuilder.setPort(9090);
+ uriBuilder.addParameter("topic", "java");
+ uriBuilder.addParameter("version", "8");
+ URL url = uriBuilder.build().toURL();
+ assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
+ }
+
+ @Test
+ public void givenUrlParametersInMap_whenBuildUrlWithURIBuilder_thenSuccess() throws URISyntaxException, MalformedURLException {
+ Map paramMap = ImmutableMap.of("topic", "java", "version", "8");
+ URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles");
+ uriBuilder.setPort(9090);
+ uriBuilder.addParameters(paramMap.entrySet()
+ .stream()
+ .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
+ .collect(toList()));
+
+ URL url = uriBuilder.build().toURL();
+ assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
+ }
+
+ @Test
+ public void givenUrlParameters_whenBuildUrlWithSpringUriComponentsBuilder_thenSuccess() throws MalformedURLException {
+ URL url = UriComponentsBuilder.newInstance()
+ .scheme("http")
+ .host("baeldung.com")
+ .port(9090)
+ .path("articles")
+ .queryParam("topic", "java")
+ .queryParam("version", "8")
+ .build()
+ .toUri()
+ .toURL();
+
+ assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-nio-2/README.md b/core-java-modules/core-java-nio-2/README.md
index 308356cf8bfa..527600779a44 100644
--- a/core-java-modules/core-java-nio-2/README.md
+++ b/core-java-modules/core-java-nio-2/README.md
@@ -14,5 +14,4 @@ This module contains articles about core Java non-blocking input and output (IO)
- [What Is the Difference Between NIO and NIO.2?](https://www.baeldung.com/java-nio-vs-nio-2)
- [Guide to ByteBuffer](https://www.baeldung.com/java-bytebuffer)
- [Find Files that Match Wildcard Strings in Java](https://www.baeldung.com/java-files-match-wildcard-strings)
-- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
- [[<-- Prev]](/core-java-modules/core-java-nio)
diff --git a/core-java-modules/core-java-nio-2/pom.xml b/core-java-modules/core-java-nio-2/pom.xml
index eb56c2bf6835..e35b70cfc745 100644
--- a/core-java-modules/core-java-nio-2/pom.xml
+++ b/core-java-modules/core-java-nio-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-nio-2
- 0.1.0-SNAPSHOT
core-java-nio-2
jar
diff --git a/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoServer.java b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoServer.java
index 9e9edcd0baef..c8b638dc046c 100644
--- a/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoServer.java
+++ b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoServer.java
@@ -45,8 +45,9 @@ public static void main(String[] args) throws IOException {
private static void answerWithEcho(ByteBuffer buffer, SelectionKey key) throws IOException {
SocketChannel client = (SocketChannel) key.channel();
- client.read(buffer);
- if (new String(buffer.array()).trim().equals(POISON_PILL)) {
+ int r = client.read(buffer);
+ if (r == -1 || new String(buffer.array()).trim()
+ .equals(POISON_PILL)) {
client.close();
System.out.println("Not accepting client messages anymore");
} else {
diff --git a/core-java-modules/core-java-nio/pom.xml b/core-java-modules/core-java-nio/pom.xml
index 9e1c529a65f9..35fef82df59a 100644
--- a/core-java-modules/core-java-nio/pom.xml
+++ b/core-java-modules/core-java-nio/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-nio
- 0.1.0-SNAPSHOT
core-java-nio
jar
diff --git a/core-java-modules/core-java-numbers-2/pom.xml b/core-java-modules/core-java-numbers-2/pom.xml
index ac3843607e77..46e0fa47b416 100644
--- a/core-java-modules/core-java-numbers-2/pom.xml
+++ b/core-java-modules/core-java-numbers-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-numbers-2
- 0.1.0-SNAPSHOT
core-java-numbers-2
jar
diff --git a/core-java-modules/core-java-numbers-6/README.md b/core-java-modules/core-java-numbers-6/README.md
new file mode 100644
index 000000000000..97e4e2ca2803
--- /dev/null
+++ b/core-java-modules/core-java-numbers-6/README.md
@@ -0,0 +1,4 @@
+### Relevant Articles:
+- [Java Program to Calculate 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)
+- More articles: [[<-- prev]](../core-java-numbers-5)
diff --git a/core-java-modules/core-java-numbers-6/pom.xml b/core-java-modules/core-java-numbers-6/pom.xml
new file mode 100644
index 000000000000..531f1293d182
--- /dev/null
+++ b/core-java-modules/core-java-numbers-6/pom.xml
@@ -0,0 +1,43 @@
+
+ 4.0.0
+ core-java-numbers-6
+ core-java-numbers-6
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ ${junit-jupiter.version}
+ test
+
+
+ commons-codec
+ commons-codec
+ ${commons-codec}
+ test
+
+
+
+
+ core-java-numbers-6
+
+
+ src/main/resources
+ true
+
+
+
+
+
+ 1.15
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-numbers-6/src/main/java/com/baeldung/integertohex/IntegerToHex.java b/core-java-modules/core-java-numbers-6/src/main/java/com/baeldung/integertohex/IntegerToHex.java
new file mode 100644
index 000000000000..9f75b9a145dd
--- /dev/null
+++ b/core-java-modules/core-java-numbers-6/src/main/java/com/baeldung/integertohex/IntegerToHex.java
@@ -0,0 +1,16 @@
+package com.baeldung.integertohex;
+
+class IntegerToHex {
+ static final String digits = "0123456789ABCDEF";
+ static String integerToHex(int input) {
+ if (input <= 0)
+ return "0";
+ StringBuilder hex = new StringBuilder();
+ while (input > 0) {
+ int digit = input % 16;
+ hex.insert(0, digits.charAt(digit));
+ input = input / 16;
+ }
+ return hex.toString();
+ }
+}
diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integertohex/IntegerToHexUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integertohex/IntegerToHexUnitTest.java
new file mode 100644
index 000000000000..6073c2d3474f
--- /dev/null
+++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integertohex/IntegerToHexUnitTest.java
@@ -0,0 +1,75 @@
+package com.baeldung.integertohex;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.apache.commons.codec.binary.Hex;
+import org.junit.jupiter.api.Test;
+
+class IntegerToHexUnitTest {
+
+ @Test
+ void givenIntegerValue_whenUseRawMethod_thenWillGetHexValue() {
+ String result = IntegerToHex.integerToHex(1055);
+ assertEquals("41F", result);
+ }
+
+ @Test
+ void givenIntegerNegativeValue_whenUseRawMethod_thenZeroValue() {
+ String result = IntegerToHex.integerToHex(-1055);
+ assertEquals("0", result);
+ }
+
+ @Test
+ void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValue() {
+ String result = String.format("%02x", 255);
+ assertEquals("ff", result);
+ }
+
+ @Test
+ void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValueWithLeftZeros() {
+ String result = String.format("%04x", 255);
+ assertEquals("00ff", result);
+ }
+
+ @Test
+ void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValueWithLeftZerosAndUpperLetter() {
+ String result = String.format("%04X", 255);
+ assertEquals("00FF", result);
+ }
+
+ @Test
+ void givenIntegerValue_whenUseIntegerToHexString_thenWillGetHexValue() {
+ String result = Integer.toHexString(1000);
+ assertEquals("3e8", result);
+ }
+
+ @Test
+ void givenIntegerValue_whenUseLongToHexString_thenWillGetHexValue() {
+ String result = Long.toHexString(255L);
+ assertEquals("ff", result);
+ }
+
+ @Test
+ public void givenNegativeIntegerValue_whenUseIntegerToString_thenWillGetHexValue() {
+ String result = Integer.toString(-1458, 16);
+ assertEquals("-5b2", result);
+ }
+
+ @Test
+ public void givenIntegerValue_whenUseIntegerToString_thenWillGetHexValue() {
+ String result = Integer.toString(1458, 16);
+ assertEquals("5b2", result);
+ }
+
+ @Test
+ public void givenLongValue_whenUseLongToString_thenWillGetHexValue() {
+ String result = Long.toString(158, 16);
+ assertEquals("9e", result);
+ }
+
+ @Test
+ public void givenIntegerValue_whenUseApacheCommons_thenWillGetHexSignedValue() {
+ String result = Hex.encodeHexString(new byte[] { (byte) 254 });
+ assertEquals("fe", result);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/pi/PiProgramUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/pi/PiProgramUnitTest.java
new file mode 100644
index 000000000000..d47942a51756
--- /dev/null
+++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/pi/PiProgramUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.pi;
+
+import static org.junit.Assert.*;
+
+import java.util.Random;
+import org.junit.Test;
+
+public class PiProgramUnitTest {
+
+ @Test
+ public void givenPiCalculator_whenCalculatePiWithOneMillionPoints_thenEstimatedPiIsWithinTolerance() {
+ int totalPoints = 1000000;
+ int insideCircle = 0;
+
+ Random random = new Random();
+
+ for (long i = 0; i < totalPoints; i++) {
+ double x = random.nextDouble() * 2 - 1;
+ double y = random.nextDouble() * 2 - 1;
+
+ if (x * x + y * y <= 1) {
+ insideCircle++;
+ }
+
+ }
+ double pi = 4.0 * insideCircle / totalPoints;
+
+ assertEquals(Math.PI, pi, 0.01);
+ }
+
+}
diff --git a/core-java-modules/core-java-numbers-conversions/pom.xml b/core-java-modules/core-java-numbers-conversions/pom.xml
index 55df86d5c7ad..f745b83f8a83 100644
--- a/core-java-modules/core-java-numbers-conversions/pom.xml
+++ b/core-java-modules/core-java-numbers-conversions/pom.xml
@@ -12,6 +12,14 @@
0.0.1-SNAPSHOT
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+
core-java-numbers-conversions
diff --git a/core-java-modules/core-java-numbers-conversions/src/main/java/com/baeldung/stringtoint/StringToIntConverter.java b/core-java-modules/core-java-numbers-conversions/src/main/java/com/baeldung/stringtoint/StringToIntConverter.java
new file mode 100644
index 000000000000..151dcb3fdb68
--- /dev/null
+++ b/core-java-modules/core-java-numbers-conversions/src/main/java/com/baeldung/stringtoint/StringToIntConverter.java
@@ -0,0 +1,38 @@
+package com.baeldung.stringtoint;
+
+import java.util.Optional;
+import org.apache.commons.lang3.math.NumberUtils;
+
+public class StringToIntConverter {
+ Optional convertStringToIntUsingIntegerParseInt(String input){
+ try {
+ return Optional.of(Integer.parseInt(input));
+ } catch (NumberFormatException e) {
+ // log or handle the error
+ return Optional.empty();
+ }
+ }
+
+ Optional convertStringToIntUsingIntegerValueOf(String input){
+ try {
+ return Optional.of(Integer.valueOf(input));
+ } catch (NumberFormatException e) {
+ // log or handle the error
+ return Optional.empty();
+ }
+ }
+
+ Optional convertStringToIntUsingIntegerDecode(String input){
+ try {
+ return Optional.of(Integer.decode(input));
+ } catch (Exception e) {
+ // log or handle the error
+ return Optional.empty();
+ }
+ }
+
+ int convertStringToIntUsingNumberUtils(String input, Integer defaultValue){
+ return NumberUtils.toInt(input, defaultValue);
+ }
+}
+
diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/stringtoint/StringToIntConverterUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/stringtoint/StringToIntConverterUnitTest.java
new file mode 100644
index 000000000000..15cc04ed04e1
--- /dev/null
+++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/stringtoint/StringToIntConverterUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.stringtoint;
+
+import java.util.Arrays;
+import java.util.List;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class StringToIntConverterUnitTest {
+
+ private StringToIntConverter stringToIntConverter = new StringToIntConverter();
+
+ @Test
+ void whenConvertingIntToString_thenInvalidCasesReturnIntegerMinValue() {
+ List testData = Arrays.asList(
+ new TestData("", Integer.MIN_VALUE),
+ new TestData(null, Integer.MIN_VALUE),
+ new TestData("23,56", Integer.MIN_VALUE),
+ new TestData("2147483648", Integer.MIN_VALUE),
+ new TestData("-2147483649", Integer.MIN_VALUE),
+ new TestData("hello", Integer.MIN_VALUE)
+ );
+ testData.forEach(data -> {
+ Assertions.assertEquals(data.expectedOutput, stringToIntConverter.convertStringToIntUsingIntegerParseInt(data.input).orElse(Integer.MIN_VALUE));
+ Assertions.assertEquals(data.expectedOutput, stringToIntConverter.convertStringToIntUsingIntegerValueOf(data.input).orElse(Integer.MIN_VALUE));
+ Assertions.assertEquals(data.expectedOutput, stringToIntConverter.convertStringToIntUsingIntegerDecode(data.input).orElse(Integer.MIN_VALUE));
+ Assertions.assertEquals(data.expectedOutput, stringToIntConverter.convertStringToIntUsingNumberUtils(data.input,Integer.MIN_VALUE ));
+ });
+ }
+
+ @Test
+ void whenConvertingIntToString_thenValidCasesReturnUnboxedInt() {
+ List testData = Arrays.asList(
+ new TestData("23", 23),
+ new TestData("-23", -23)
+ );
+ testData.forEach(data -> {
+ Assertions.assertEquals(data.expectedOutput, stringToIntConverter.convertStringToIntUsingIntegerParseInt(data.input).orElse(Integer.MIN_VALUE));
+ Assertions.assertEquals(data.expectedOutput, stringToIntConverter.convertStringToIntUsingIntegerValueOf(data.input).orElse(Integer.MIN_VALUE));
+ Assertions.assertEquals(data.expectedOutput, stringToIntConverter.convertStringToIntUsingNumberUtils(data.input, Integer.MIN_VALUE));
+ Assertions.assertEquals(data.expectedOutput, stringToIntConverter.convertStringToIntUsingIntegerDecode(data.input).orElse(Integer.MIN_VALUE));
+ });
+ }
+
+ public static class TestData{
+ String input;
+ Integer expectedOutput;
+
+ TestData(String input, Integer expectedOutput){
+ this.input = input;
+ this.expectedOutput = expectedOutput;
+ }
+ }
+}
diff --git a/core-java-modules/core-java-numbers/pom.xml b/core-java-modules/core-java-numbers/pom.xml
index 4b2cae8ee955..38def238e88c 100644
--- a/core-java-modules/core-java-numbers/pom.xml
+++ b/core-java-modules/core-java-numbers/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-numbers
- 0.1.0-SNAPSHOT
core-java-numbers
jar
diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml
index 08441f6cee6a..eeefed867e93 100644
--- a/core-java-modules/core-java-optional/pom.xml
+++ b/core-java-modules/core-java-optional/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-optional
- 0.1.0-SNAPSHOT
core-java-optional
jar
diff --git a/core-java-modules/core-java-os/pom.xml b/core-java-modules/core-java-os/pom.xml
index ef29e435a5b9..d4ee34b8b7f9 100644
--- a/core-java-modules/core-java-os/pom.xml
+++ b/core-java-modules/core-java-os/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-os
- 0.1.0-SNAPSHOT
core-java-os
jar
diff --git a/core-java-modules/core-java-perf-2/README.md b/core-java-modules/core-java-perf-2/README.md
new file mode 100644
index 000000000000..8911c687a042
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/README.md
@@ -0,0 +1,8 @@
+## Core Java Performance
+
+This module contains articles about performance of Java applications
+
+### Relevant Articles:
+- [Possible Root Causes for High CPU Usage in Java](https://www.baeldung.com/java-high-cpu-usage-causes)
+- [External Debugging With JMXTerm](https://www.baeldung.com/java-jmxterm-external-debugging)
+- [Create and Detect Memory Leaks in Java](https://www.baeldung.com/java-create-detect-memory-leaks)
diff --git a/core-java-modules/core-java-perf-2/pom.xml b/core-java-modules/core-java-perf-2/pom.xml
new file mode 100644
index 000000000000..a44f6aa8c1b2
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/pom.xml
@@ -0,0 +1,23 @@
+
+
+ 4.0.0
+ core-java-perf-2
+ core-java-perf-2
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ net.datafaker
+ datafaker
+ 1.6.0
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/highcpu/Application.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/highcpu/Application.java
new file mode 100644
index 000000000000..82162406b345
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/highcpu/Application.java
@@ -0,0 +1,20 @@
+package com.baeldung.highcpu;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.function.IntUnaryOperator;
+import java.util.stream.IntStream;
+
+public class Application {
+
+ static List generateList() {
+ return IntStream.range(0, 10000000).parallel().map(IntUnaryOperator.identity()).collect(LinkedList::new, List::add, List::addAll);
+ }
+
+ public static void main(String[] args) {
+ List list = generateList();
+ long start = System.nanoTime();
+ int value = list.get(9500000);
+ System.out.printf("Found value %d in %d nanos\n", value, (System.nanoTime() - start));
+ }
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/AbstractPlayerMBean.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/AbstractPlayerMBean.java
new file mode 100644
index 000000000000..698d107c51ad
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/AbstractPlayerMBean.java
@@ -0,0 +1,16 @@
+package com.baeldung.jmxterm;
+
+import java.util.UUID;
+
+public abstract class AbstractPlayerMBean implements PlayerMBean{
+
+ private final UUID id;
+
+ protected AbstractPlayerMBean() {
+ this.id = UUID.randomUUID();
+ }
+
+ String getId() {
+ return getName() + id.toString();
+ }
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/BroadcastingGuessGame.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/BroadcastingGuessGame.java
new file mode 100644
index 000000000000..921d87c4d7b6
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/BroadcastingGuessGame.java
@@ -0,0 +1,42 @@
+package com.baeldung.jmxterm;
+
+import javax.management.ListenerNotFoundException;
+import javax.management.MBeanNotificationInfo;
+import javax.management.Notification;
+import javax.management.NotificationBroadcaster;
+import javax.management.NotificationBroadcasterSupport;
+import javax.management.NotificationFilter;
+import javax.management.NotificationListener;
+
+public abstract class BroadcastingGuessGame implements NotificationBroadcaster, GuessGameMBean {
+ private final NotificationBroadcasterSupport broadcaster =
+ new NotificationBroadcasterSupport();
+
+ private long notificationSequence = 0;
+
+ private final MBeanNotificationInfo[] notificationInfo;
+
+ protected BroadcastingGuessGame() {
+ this.notificationInfo = new MBeanNotificationInfo[]{
+ new MBeanNotificationInfo(new String[]{"game"}, Notification.class.getName(), "Game notification")
+ };
+ }
+
+ protected void notifyAboutWinner(Player winner) {
+ String message = "Winner is " + winner.getName() + " with score " + winner.getScore();
+ Notification notification = new Notification("game.winner", this, notificationSequence++, message);
+ broadcaster.sendNotification(notification);
+ }
+
+ public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) {
+ broadcaster.addNotificationListener(listener, filter, handback);
+ }
+
+ public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
+ broadcaster.removeNotificationListener(listener);
+ }
+
+ public MBeanNotificationInfo[] getNotificationInfo() {
+ return notificationInfo;
+ }
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/GameRunner.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/GameRunner.java
new file mode 100644
index 000000000000..3955d37504eb
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/GameRunner.java
@@ -0,0 +1,19 @@
+package com.baeldung.jmxterm;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class GameRunner {
+
+ public static void main(String[] args) {
+ MBeanGameServer mBeanGameServer = new MBeanGameServer();
+ Player bob = new Player("Bob");
+ Player alice = new Player("Alice");
+ Player john = new Player("John");
+ List players = Arrays.asList(bob, alice, john);
+ GuessGame guessGame = new GuessGame(players);
+ mBeanGameServer.registerGame(guessGame);
+ guessGame.start();
+ }
+
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/GuessGame.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/GuessGame.java
new file mode 100644
index 000000000000..c9d680880f3e
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/GuessGame.java
@@ -0,0 +1,80 @@
+package com.baeldung.jmxterm;
+
+import static com.baeldung.jmxterm.RandomNumbergenerator.generateRandomNumber;
+
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class GuessGame extends BroadcastingGuessGame {
+
+
+ public static final int SECOND = 1000;
+ private static final Logger log = Logger.getLogger(GuessGame.class.getCanonicalName());
+ private final List players;
+ private volatile boolean isFinished = false;
+ private volatile boolean isPaused = false;
+
+
+ public GuessGame(List players) {
+ this.players = players;
+ log.setLevel(Level.WARNING);
+ }
+
+ public void start() {
+ int randomNumber = generateRandomNumber();
+ while (!isFinished) {
+ waitASecond();
+ while (!isPaused && !isFinished) {
+ log.info("Current random number is " + randomNumber);
+ waitASecond();
+ for (Player player : players) {
+ int guess = player.guessNumber();
+ if (guess == randomNumber) {
+ log.info("Players " + player.getName() + " " + guess + " is correct");
+ player.incrementScore();
+ notifyAboutWinner(player);
+ randomNumber = generateRandomNumber();
+ break;
+ }
+ log.info("Player " + player.getName() + " guessed incorrectly with " + guess);
+ }
+ log.info("\n");
+ }
+ if (isPaused) {
+ log.info("Game is paused");
+ }
+ if (isFinished) {
+ log.info("Game is finished");
+ }
+ }
+ }
+
+ @Override
+ public void finishGame() {
+ isFinished = true;
+ }
+
+ @Override
+ public void pauseGame() {
+ isPaused = true;
+ }
+
+ @Override
+ public void unpauseGame() {
+ isPaused = false;
+ }
+
+ public List getPlayers() {
+ return players;
+ }
+
+ private void waitASecond() {
+ try {
+ Thread.sleep(SECOND);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/GuessGameMBean.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/GuessGameMBean.java
new file mode 100644
index 000000000000..fdf8149f713b
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/GuessGameMBean.java
@@ -0,0 +1,8 @@
+package com.baeldung.jmxterm;
+
+public interface GuessGameMBean {
+
+ void finishGame();
+ void pauseGame();
+ void unpauseGame();
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/MBeanGameServer.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/MBeanGameServer.java
new file mode 100644
index 000000000000..922a0baf76ab
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/MBeanGameServer.java
@@ -0,0 +1,37 @@
+package com.baeldung.jmxterm;
+
+import java.lang.management.ManagementFactory;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.MBeanRegistrationException;
+import javax.management.MBeanServer;
+import javax.management.MalformedObjectNameException;
+import javax.management.NotCompliantMBeanException;
+import javax.management.ObjectName;
+
+public class MBeanGameServer {
+
+ public static final String ID_FORMAT = "com.baeldung.jmxterm:type=%s,id=%s";
+ private final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
+
+ public void registerPlayer(AbstractPlayerMBean player) {
+ registerBean(player, "player", player.getId());
+ }
+
+ public void registerGame(GuessGame guessGame) {
+ registerBean(guessGame, "game", "singlegame");
+ guessGame.getPlayers().forEach(this::registerPlayer);
+ }
+
+ private void registerBean(Object bean, String type, String id) {
+ try {
+ ObjectName name = new ObjectName(String.format(ID_FORMAT, type, id));
+ server.registerMBean(bean, name);
+ } catch (InstanceAlreadyExistsException |
+ MBeanRegistrationException |
+ NotCompliantMBeanException |
+ MalformedObjectNameException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/Player.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/Player.java
new file mode 100644
index 000000000000..4961400f2f55
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/Player.java
@@ -0,0 +1,33 @@
+package com.baeldung.jmxterm;
+
+import static com.baeldung.jmxterm.RandomNumbergenerator.generateRandomNumber;
+
+public class Player extends AbstractPlayerMBean {
+ private final String name;
+ private int score = 0;
+
+ public Player(String name) {
+ super();
+ this.name = name;
+ }
+
+ @Override
+ public int guessNumber() {
+ return generateRandomNumber();
+ }
+
+ public void incrementScore() {
+ score++;
+ }
+
+ @Override
+ public int getScore() {
+ return score;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/PlayerMBean.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/PlayerMBean.java
new file mode 100644
index 000000000000..78b73ff578f2
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/PlayerMBean.java
@@ -0,0 +1,10 @@
+package com.baeldung.jmxterm;
+
+public interface PlayerMBean {
+
+ int guessNumber();
+
+ int getScore();
+
+ String getName();
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/RandomNumbergenerator.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/RandomNumbergenerator.java
new file mode 100644
index 000000000000..1418f502c628
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/jmxterm/RandomNumbergenerator.java
@@ -0,0 +1,18 @@
+package com.baeldung.jmxterm;
+
+import java.util.concurrent.ThreadLocalRandom;
+
+public class RandomNumbergenerator {
+
+ private static final int MIN = 0;
+ private static final int MAX = 10;
+
+ private static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();
+
+ private RandomNumbergenerator() {
+ }
+ public static int generateRandomNumber() {
+ return RANDOM.nextInt(MIN, MAX + 1);
+ }
+
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/LapsedListenerRunner.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/LapsedListenerRunner.java
new file mode 100644
index 000000000000..50da98e6c47f
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/LapsedListenerRunner.java
@@ -0,0 +1,35 @@
+package com.baeldung.lapsedlistener;
+
+import static com.baeldung.lapsedlistener.UserGenerator.generateUser;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class LapsedListenerRunner {
+
+ private static final Logger logger = LoggerFactory.getLogger(LapsedListenerRunner.class);
+ private static final MovieQuoteService movieQuoteService = new MovieQuoteService();
+
+ static {
+ movieQuoteService.start();
+ }
+
+public static void main(String[] args) {
+ while (true) {
+ User user = generateUser();
+ logger.debug("{} logged in", user.getName());
+ user.subscribe(movieQuoteService);
+ userUsingService();
+ logger.debug("{} logged out", user.getName());
+ }
+}
+
+ private static void userUsingService() {
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/MovieQuoteService.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/MovieQuoteService.java
new file mode 100644
index 000000000000..95240bbbd58a
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/MovieQuoteService.java
@@ -0,0 +1,47 @@
+package com.baeldung.lapsedlistener;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import net.datafaker.Faker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class MovieQuoteService implements Subject {
+
+ private static final Logger logger = LoggerFactory.getLogger(MovieQuoteService.class);
+ private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
+ private final List observers = new ArrayList<>();
+ private final Faker faker = new Faker();
+
+ @Override
+ public void attach(Observer observer) {
+ logger.debug("Current number of subscribed users: {}", observers.size());
+ observers.add(observer);
+ }
+
+ @Override
+ public void detach(Observer observer) {
+ observers.remove(observer);
+ }
+
+ @Override
+ public void notifyObservers() {
+ String quote = faker.movie().quote();
+ logger.debug("New quote: {}", quote);
+ for (Observer observer : observers) {
+ logger.debug("Notifying user: {}", observer);
+ observer.update(quote);
+ }
+ }
+
+ public void start() {
+ scheduler.scheduleAtFixedRate(this::notifyObservers, 0, 1, TimeUnit.SECONDS);
+ }
+
+ public int numberOfSubscribers() {
+ return observers.size();
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/Observer.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/Observer.java
new file mode 100644
index 000000000000..2c4ccf9e0603
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/Observer.java
@@ -0,0 +1,9 @@
+package com.baeldung.lapsedlistener;
+
+public interface Observer {
+ void update(String latestNews);
+
+ void subscribe(Subject subject);
+
+ void unsubscribe(Subject subject);
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/Subject.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/Subject.java
new file mode 100644
index 000000000000..141a7662a73d
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/Subject.java
@@ -0,0 +1,9 @@
+package com.baeldung.lapsedlistener;
+
+public interface Subject {
+ void attach(Observer observer);
+
+ void detach(Observer observer);
+
+ void notifyObservers();
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/User.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/User.java
new file mode 100644
index 000000000000..0ed0a32a0140
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/User.java
@@ -0,0 +1,70 @@
+package com.baeldung.lapsedlistener;
+
+public class User implements Observer {
+
+ private final String name;
+ private final String email;
+ private final String phone;
+ private final String street;
+ private final String city;
+ private final String state;
+ private final String zipCode;
+
+ public User(String name, String email, String phone, String street, String city, String state, String zipCode) {
+ this.name = name;
+ this.email = email;
+ this.phone = phone;
+ this.street = street;
+ this.city = city;
+ this.state = state;
+ this.zipCode = zipCode;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public String getPhone() {
+ return phone;
+ }
+
+ public String getStreet() {
+ return street;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public String getState() {
+ return state;
+ }
+
+ public String getZipCode() {
+ return zipCode;
+ }
+
+ @Override
+ public void update(final String quote) {
+ // user got updated with a new quote
+ }
+
+ @Override
+ public void subscribe(final Subject subject) {
+ subject.attach(this);
+ }
+
+ @Override
+ public void unsubscribe(final Subject subject) {
+ subject.detach(this);
+ }
+
+ @Override
+ public String toString() {
+ return "User [name=" + name + "]";
+ }
+}
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/UserGenerator.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/UserGenerator.java
new file mode 100644
index 000000000000..acdb7d7af74e
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/lapsedlistener/UserGenerator.java
@@ -0,0 +1,23 @@
+package com.baeldung.lapsedlistener;
+
+import net.datafaker.Faker;
+
+public class UserGenerator {
+
+ private UserGenerator() {
+ }
+
+ private static final Faker faker = new Faker();
+
+ public static User generateUser() {
+ String name = faker.name().fullName();
+ String email = faker.internet().emailAddress();
+ String phone = faker.phoneNumber().cellPhone();
+ String street = faker.address().streetAddress();
+ String city = faker.address().city();
+ String state = faker.address().state();
+ String zipCode = faker.address().zipCode();
+ return new User(name, email, phone, street, city, state, zipCode);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-perf-2/src/test/java/com/baeldung/jmxterm/PlayerUnitTest.java b/core-java-modules/core-java-perf-2/src/test/java/com/baeldung/jmxterm/PlayerUnitTest.java
new file mode 100644
index 000000000000..668c7195d788
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/test/java/com/baeldung/jmxterm/PlayerUnitTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.jmxterm;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+class PlayerUnitTest {
+
+ @Test
+ void givenNewPlayer_thenScoreIsZero() {
+ Player player = new Player("John");
+ assertEquals(0, player.getScore());
+ }
+
+ @Test
+ void givenNewPlayer_whenIncrementScore_thenScoreIsOne() {
+ Player player = new Player("John");
+ player.incrementScore();
+ assertEquals(1, player.getScore());
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-perf-2/src/test/java/com/baeldung/lapsedlistener/MovieQuoteServiceTest.java b/core-java-modules/core-java-perf-2/src/test/java/com/baeldung/lapsedlistener/MovieQuoteServiceTest.java
new file mode 100644
index 000000000000..90c96cba1b29
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/test/java/com/baeldung/lapsedlistener/MovieQuoteServiceTest.java
@@ -0,0 +1,24 @@
+package com.baeldung.lapsedlistener;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+class MovieQuoteServiceTest {
+
+ @Test
+ void whenSubscribeToService_thenServiceHasOneSubscriber() {
+ MovieQuoteService service = new MovieQuoteService();
+ service.attach(UserGenerator.generateUser());
+ assertEquals(1, service.numberOfSubscribers());
+ }
+
+ @Test
+ void whenUnsubscribeFromService_thenServiceHasNoSubscribers() {
+ MovieQuoteService service = new MovieQuoteService();
+ User user = UserGenerator.generateUser();
+ service.attach(user);
+ service.detach(user);
+ assertEquals(0, service.numberOfSubscribers());
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-perf/README.md b/core-java-modules/core-java-perf/README.md
index c018ec992750..c400f1d1968b 100644
--- a/core-java-modules/core-java-perf/README.md
+++ b/core-java-modules/core-java-perf/README.md
@@ -13,3 +13,5 @@ This module contains articles about performance of Java applications
- [Capturing a Java Thread Dump](https://www.baeldung.com/java-thread-dump)
- [JMX Ports](https://www.baeldung.com/jmx-ports)
- [Calling JMX MBean Method From a Shell Script](https://www.baeldung.com/jmx-mbean-shell-access)
+- [External Debugging With JMXTerm](https://www.baeldung.com/java-jmxterm-external-debugging)
+- [Create and Detect Memory Leaks in Java](https://www.baeldung.com/java-create-detect-memory-leaks)
diff --git a/core-java-modules/core-java-perf/pom.xml b/core-java-modules/core-java-perf/pom.xml
index f6f3ef795c15..c21fc94ec185 100644
--- a/core-java-modules/core-java-perf/pom.xml
+++ b/core-java-modules/core-java-perf/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-perf
- 0.1.0-SNAPSHOT
core-java-perf
jar
diff --git a/core-java-modules/core-java-properties/README.md b/core-java-modules/core-java-properties/README.md
new file mode 100644
index 000000000000..73991634df93
--- /dev/null
+++ b/core-java-modules/core-java-properties/README.md
@@ -0,0 +1,6 @@
+## Core Java Properties
+
+### Relevant Articles:
+
+- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
+- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
diff --git a/core-java-modules/core-java-properties/pom.xml b/core-java-modules/core-java-properties/pom.xml
new file mode 100644
index 000000000000..9beacabdd581
--- /dev/null
+++ b/core-java-modules/core-java-properties/pom.xml
@@ -0,0 +1,23 @@
+
+
+ 4.0.0
+ core-java-properties
+ 0.1.0-SNAPSHOT
+ core-java-properties
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/util/PropertiesLoader.java b/core-java-modules/core-java-properties/src/main/java/com/baeldung/util/PropertiesLoader.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/util/PropertiesLoader.java
rename to core-java-modules/core-java-properties/src/main/java/com/baeldung/util/PropertiesLoader.java
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java b/core-java-modules/core-java-properties/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java
rename to core-java-modules/core-java-properties/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/properties/MergePropertiesUnitTest.java b/core-java-modules/core-java-properties/src/test/java/com/baeldung/properties/MergePropertiesUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/properties/MergePropertiesUnitTest.java
rename to core-java-modules/core-java-properties/src/test/java/com/baeldung/properties/MergePropertiesUnitTest.java
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java b/core-java-modules/core-java-properties/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java
rename to core-java-modules/core-java-properties/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java
diff --git a/core-java-modules/core-java/src/test/resources/app.properties b/core-java-modules/core-java-properties/src/test/resources/app.properties
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/app.properties
rename to core-java-modules/core-java-properties/src/test/resources/app.properties
diff --git a/core-java-modules/core-java/src/test/resources/catalog b/core-java-modules/core-java-properties/src/test/resources/catalog
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/catalog
rename to core-java-modules/core-java-properties/src/test/resources/catalog
diff --git a/core-java-modules/core-java/src/test/resources/configuration.properties b/core-java-modules/core-java-properties/src/test/resources/configuration.properties
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/configuration.properties
rename to core-java-modules/core-java-properties/src/test/resources/configuration.properties
diff --git a/core-java-modules/core-java/src/test/resources/default.properties b/core-java-modules/core-java-properties/src/test/resources/default.properties
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/default.properties
rename to core-java-modules/core-java-properties/src/test/resources/default.properties
diff --git a/core-java-modules/core-java/src/test/resources/icons.xml b/core-java-modules/core-java-properties/src/test/resources/icons.xml
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/icons.xml
rename to core-java-modules/core-java-properties/src/test/resources/icons.xml
diff --git a/core-java-modules/core-java-records/README.md b/core-java-modules/core-java-records/README.md
new file mode 100644
index 000000000000..2e7ad00cd306
--- /dev/null
+++ b/core-java-modules/core-java-records/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Overridding hashCode() And equals() For Records](https://www.baeldung.com/java-override-hashcode-equals-records)
diff --git a/core-java-modules/core-java-records/pom.xml b/core-java-modules/core-java-records/pom.xml
new file mode 100644
index 000000000000..ed9a36fc1464
--- /dev/null
+++ b/core-java-modules/core-java-records/pom.xml
@@ -0,0 +1,32 @@
+
+
+
+ core-java-modules
+ com.baeldung.core-java-modules
+ 0.0.1-SNAPSHOT
+
+ 4.0.0
+
+ core-java-records
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ 16
+
+
+
+
+
+
+ 19
+ 19
+ UTF-8
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Movie.java b/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Movie.java
new file mode 100644
index 000000000000..e94638e8b5e2
--- /dev/null
+++ b/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Movie.java
@@ -0,0 +1,26 @@
+package com.baeldung.equalshashcoderecords;
+
+import java.util.Objects;
+
+record Movie(String name, Integer yearOfRelease, String distributor) {
+
+@Override
+public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (other == null) {
+ return false;
+ }
+ Movie movie = (Movie) other;
+ if (movie.name.equals(this.name) && movie.yearOfRelease.equals(this.yearOfRelease)) {
+ return true;
+ }
+ return false;
+}
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, yearOfRelease);
+ }
+}
diff --git a/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Person.java b/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Person.java
new file mode 100644
index 000000000000..7bfd8ae7415a
--- /dev/null
+++ b/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Person.java
@@ -0,0 +1,5 @@
+package com.baeldung.equalshashcoderecords;
+
+public record Person(String firstName, String lastName, String SSN, String dateOfBirth) {
+};
+
diff --git a/core-java-modules/core-java-records/src/test/java/com/baeldung/equalshashcoderecords/CustomRecordEqualsHashCode.java b/core-java-modules/core-java-records/src/test/java/com/baeldung/equalshashcoderecords/CustomRecordEqualsHashCode.java
new file mode 100644
index 000000000000..074886304fa2
--- /dev/null
+++ b/core-java-modules/core-java-records/src/test/java/com/baeldung/equalshashcoderecords/CustomRecordEqualsHashCode.java
@@ -0,0 +1,30 @@
+package com.baeldung.equalshashcoderecords;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+import org.junit.Test;
+
+public class CustomRecordEqualsHashCode {
+ @Test
+ public void givenTwoRecords_whenDefaultEquals_thenCompareEquality() {
+ Person robert = new Person("Robert", "Frost", "HDHDB223", "2000-01-02");
+ Person mike = new Person("Mike", "Adams", "ABJDJ2883", "2001-01-02");
+ assertNotEquals(robert, mike);
+ }
+
+ @Test
+ public void givenTwoRecords_hashCodesShouldBeSame() {
+ Person robert = new Person("Robert", "Frost", "HDHDB223", "2000-01-02");
+ Person robertCopy = new Person("Robert", "Frost", "HDHDB223", "2000-01-02");
+ assertEquals(robert.hashCode(), robertCopy.hashCode());
+ }
+
+ @Test
+ public void givenTwoRecords_whenCustomImplementation_thenCompareEquality() {
+ Movie movie1 = new Movie("The Batman", 2022, "WB");
+ Movie movie2 = new Movie("The Batman", 2022, "Dreamworks");
+ assertEquals(movie1, movie2);
+ assertEquals(movie1.hashCode(), movie2.hashCode());
+ }
+}
diff --git a/core-java-modules/core-java-reflection-2/pom.xml b/core-java-modules/core-java-reflection-2/pom.xml
index ee3eeee7345f..c7a4981533ce 100644
--- a/core-java-modules/core-java-reflection-2/pom.xml
+++ b/core-java-modules/core-java-reflection-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-reflection-2
- 0.1.0-SNAPSHOT
core-java-reflection-2
jar
diff --git a/core-java-modules/core-java-reflection-private-constructor/pom.xml b/core-java-modules/core-java-reflection-private-constructor/pom.xml
index b53aa2c61bd1..aee7815e2304 100644
--- a/core-java-modules/core-java-reflection-private-constructor/pom.xml
+++ b/core-java-modules/core-java-reflection-private-constructor/pom.xml
@@ -1,10 +1,9 @@
+ 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">
4.0.0
core-java-reflection-private-constructor
- 0.1.0-SNAPSHOT
core-java-reflection-private-constructor
jar
diff --git a/core-java-modules/core-java-reflection/pom.xml b/core-java-modules/core-java-reflection/pom.xml
index f6ee08dbda12..a836ee4a2281 100644
--- a/core-java-modules/core-java-reflection/pom.xml
+++ b/core-java-modules/core-java-reflection/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-reflection
- 0.1.0-SNAPSHOT
core-java-reflection
jar
diff --git a/core-java-modules/core-java-regex-2/README.md b/core-java-modules/core-java-regex-2/README.md
index 453e2cc419cd..ccf60f56d9ed 100644
--- a/core-java-modules/core-java-regex-2/README.md
+++ b/core-java-modules/core-java-regex-2/README.md
@@ -5,4 +5,6 @@
- [Converting Camel Case and Title Case to Words in Java](https://www.baeldung.com/java-camel-case-title-case-to-words)
- [How to Use Regular Expressions to Replace Tokens in Strings in Java](https://www.baeldung.com/java-regex-token-replacement)
- [Creating a Java Array from Regular Expression Matches](https://www.baeldung.com/java-array-regex-matches)
+- [Getting the Text That Follows After the Regex Match in Java](https://www.baeldung.com/java-regex-text-after-match)
+- [Regular Expression: \z vs \Z Anchors in Java](https://www.baeldung.com/java-regular-expression-z-vs-z-anchors)
- More articles: [[<-- prev]](/core-java-modules/core-java-regex)
diff --git a/core-java-modules/core-java-regex-2/pom.xml b/core-java-modules/core-java-regex-2/pom.xml
index ae9385e63c1e..ddfba35cb20b 100644
--- a/core-java-modules/core-java-regex-2/pom.xml
+++ b/core-java-modules/core-java-regex-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-regex-2
- 0.1.0-SNAPSHOT
core-java-regex-2
jar
diff --git a/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/aftermatch/GetTextAfterTheRegexMatchUnitTest.java b/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/aftermatch/GetTextAfterTheRegexMatchUnitTest.java
new file mode 100644
index 000000000000..04650a0c028d
--- /dev/null
+++ b/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/aftermatch/GetTextAfterTheRegexMatchUnitTest.java
@@ -0,0 +1,83 @@
+package com.baeldung.regex.aftermatch;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class GetTextAfterTheRegexMatchUnitTest {
+ private static final String INPUT1 = "Some text, targetValue=Regex is cool";
+ private static final String INPUT2 = "Some text. targetValue=Java is cool. some other text";
+
+ @Test
+ void whenUsingSplit_thenGetExpectedString() {
+ String result1 = INPUT1.split("targetValue=")[1];
+ assertEquals("Regex is cool", result1);
+
+ String afterFirstSplit = INPUT2.split("targetValue=")[1];
+ assertEquals("Java is cool. some other text", afterFirstSplit);
+ String result2 = afterFirstSplit.split("[.]")[0];
+ assertEquals("Java is cool", result2);
+
+ // if use the dot as the regex for splitting, the result array is empty
+ String[] splitByDot = INPUT2.split("targetValue=")[1].split(".");
+ assertEquals(0, splitByDot.length);
+ }
+
+ @Test
+ void whenUsingReplaceAll_thenGetExpectedString() {
+ String result1 = INPUT1.replaceAll(".*targetValue=", "");
+ assertEquals("Regex is cool", result1);
+
+ String afterFirstReplace = INPUT2.replaceAll(".*targetValue=", "");
+ assertEquals("Java is cool. some other text", afterFirstReplace);
+ String result2 = afterFirstReplace.replaceAll("[.].*", "");
+ assertEquals("Java is cool", result2);
+
+ }
+
+ @Test
+ void whenUsingRegexGrouping_thenGetExpectedString() {
+ Pattern p1 = Pattern.compile("targetValue=(.*)");
+ Matcher m1 = p1.matcher(INPUT1);
+ assertTrue(m1.find());
+ String result1 = m1.group(1);
+ assertEquals("Regex is cool", result1);
+
+ Pattern p2 = Pattern.compile("targetValue=([^.]*)");
+ Matcher m2 = p2.matcher(INPUT2);
+ assertTrue(m2.find());
+ String result2 = m2.group(1);
+ assertEquals("Java is cool", result2);
+
+ Pattern p3 = Pattern.compile("targetValue=(.*?)[.]");
+ Matcher m3 = p3.matcher(INPUT2);
+ assertTrue(m3.find());
+ String result3 = m3.group(1);
+ assertEquals("Java is cool", result3);
+ }
+
+ @Test
+ void whenUsingLookaround_thenGetExpectedString() {
+ Pattern p1 = Pattern.compile("(?<=targetValue=).*");
+ Matcher m1 = p1.matcher(INPUT1);
+ assertTrue(m1.find());
+ String result1 = m1.group();
+ assertEquals("Regex is cool", result1);
+
+ Pattern p2 = Pattern.compile("(?<=targetValue=)[^.]*");
+ Matcher m2 = p2.matcher(INPUT2);
+ assertTrue(m2.find());
+ String result2 = m2.group();
+ assertEquals("Java is cool", result2);
+
+ Pattern p3 = Pattern.compile("(?<=targetValue=).*(?=[.])");
+ Matcher m3 = p3.matcher(INPUT2);
+ assertTrue(m3.find());
+ String result3 = m3.group();
+ assertEquals("Java is cool", result3);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/z_regexp/ZRegularExpressionUnitTest.java b/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/z_regexp/ZRegularExpressionUnitTest.java
new file mode 100644
index 000000000000..90bbbb654081
--- /dev/null
+++ b/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/z_regexp/ZRegularExpressionUnitTest.java
@@ -0,0 +1,35 @@
+package com.baeldung.regex.z_regexp;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class ZRegularExpressionUnitTest {
+ @Test
+ public void givenCreditCardNumber_thenReturnIfMatched() {
+ String creditCardNumber = "1234567890123456";
+ String pattern = "\\d{16}\\z";
+ Assertions.assertTrue(creditCardNumber.matches(pattern));
+ }
+
+ @Test
+ public void givenLogOutput_thenReturnIfMatched() {
+ String logLine = "2022-05-01 14:30:00,123 INFO Some log message";
+ String pattern = ".*message\\z";
+ Assertions.assertTrue(logLine.matches(pattern));
+ }
+
+ @Test
+ public void givenEmailMessage_thenReturnIfMatched() {
+ String myMessage = "Hello HR, I hope i can write to Baeldung\n";
+ String pattern = ".*Baeldung\\s*\\Z";
+ Assertions.assertTrue(myMessage.matches(pattern));
+ }
+
+ @Test
+ public void givenFileExtension_thenReturnIfMatched() {
+ String fileName = "image.jpeg";
+ String pattern = ".*\\.jpeg\\Z";
+ Assertions.assertTrue(fileName.matches(pattern));
+ }
+
+}
diff --git a/core-java-modules/core-java-regex/pom.xml b/core-java-modules/core-java-regex/pom.xml
index 93f3ae3cdbaa..00b8107c573b 100644
--- a/core-java-modules/core-java-regex/pom.xml
+++ b/core-java-modules/core-java-regex/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-regex
- 0.1.0-SNAPSHOT
core-java-regex
jar
diff --git a/core-java-modules/core-java-security-2/pom.xml b/core-java-modules/core-java-security-2/pom.xml
index 7a354ee9e29c..0fc121c07050 100644
--- a/core-java-modules/core-java-security-2/pom.xml
+++ b/core-java-modules/core-java-security-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-security-2
- 0.1.0-SNAPSHOT
core-java-security-2
jar
diff --git a/core-java-modules/core-java-security-3/pom.xml b/core-java-modules/core-java-security-3/pom.xml
index 3cd546e6971e..a4f60b4db585 100644
--- a/core-java-modules/core-java-security-3/pom.xml
+++ b/core-java-modules/core-java-security-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-security-3
- 0.1.0-SNAPSHOT
core-java-security-3
jar
@@ -31,12 +30,18 @@
jaxb-api
${jaxb-api.version}
+
+ org.springframework.security
+ spring-security-crypto
+ ${spring-security-crypto.version}
+
- 1.60
+ 1.70
1.11
2.3.1
+ 6.0.3
\ No newline at end of file
diff --git a/core-java-modules/core-java-security-3/src/test/java/com/baeldung/hash/argon/HashPasswordUnitTest.java b/core-java-modules/core-java-security-3/src/test/java/com/baeldung/hash/argon/HashPasswordUnitTest.java
new file mode 100644
index 000000000000..6e0e326821a3
--- /dev/null
+++ b/core-java-modules/core-java-security-3/src/test/java/com/baeldung/hash/argon/HashPasswordUnitTest.java
@@ -0,0 +1,65 @@
+package com.baeldung.hash.argon;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.nio.charset.StandardCharsets;
+import java.security.SecureRandom;
+
+import org.bouncycastle.crypto.generators.Argon2BytesGenerator;
+import org.bouncycastle.crypto.params.Argon2Parameters;
+import org.bouncycastle.util.encoders.Hex;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
+
+import java.util.Arrays;
+import java.util.Base64;
+
+public class HashPasswordUnitTest {
+
+ @Test
+ public void givenRawPassword_whenEncodedWithArgon2_thenMatchesEncodedPassword() {
+ String rawPassword = "Baeldung";
+
+ Argon2PasswordEncoder arg2SpringSecurity = new Argon2PasswordEncoder(16, 32, 1, 60000, 10);
+ String hashPassword = arg2SpringSecurity.encode(rawPassword);
+
+ assertTrue(arg2SpringSecurity.matches(rawPassword, hashPassword));
+ }
+
+ @Test
+ public void givenRawPasswordAndSalt_whenArgon2AlgorithmIsUsed_thenHashIsCorrect() {
+ byte[] salt = generateSalt16Byte();
+ String password = "Baeldung";
+
+ int iterations = 2;
+ int memLimit = 66536;
+ int hashLength = 32;
+ int parallelism = 1;
+ Argon2Parameters.Builder builder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id).withVersion(Argon2Parameters.ARGON2_VERSION_13)
+ .withIterations(iterations)
+ .withMemoryAsKB(memLimit)
+ .withParallelism(parallelism)
+ .withSalt(salt);
+
+ Argon2BytesGenerator generate = new Argon2BytesGenerator();
+ generate.init(builder.build());
+ byte[] result = new byte[hashLength];
+ generate.generateBytes(password.getBytes(StandardCharsets.UTF_8), result, 0, result.length);
+
+ Argon2BytesGenerator verifier = new Argon2BytesGenerator();
+ verifier.init(builder.build());
+ byte[] testHash = new byte[hashLength];
+ verifier.generateBytes(password.getBytes(StandardCharsets.UTF_8), testHash, 0, testHash.length);
+
+ assertTrue(Arrays.equals(result, testHash));
+ }
+
+ private static byte[] generateSalt16Byte() {
+ SecureRandom secureRandom = new SecureRandom();
+ byte[] salt = new byte[16];
+ secureRandom.nextBytes(salt);
+ return salt;
+ }
+
+}
diff --git a/core-java-modules/core-java-security-algorithms/pom.xml b/core-java-modules/core-java-security-algorithms/pom.xml
index 967ddc103e86..0dde9f861a33 100644
--- a/core-java-modules/core-java-security-algorithms/pom.xml
+++ b/core-java-modules/core-java-security-algorithms/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-security-algorithms
- 0.1.0-SNAPSHOT
core-java-security-algorithms
jar
@@ -25,7 +24,6 @@
bcprov-jdk15on
${bouncycastle.version}
-
javax.xml.bind
jaxb-api
diff --git a/core-java-modules/core-java-security/pom.xml b/core-java-modules/core-java-security/pom.xml
index 66b56ada74d3..921017b08064 100644
--- a/core-java-modules/core-java-security/pom.xml
+++ b/core-java-modules/core-java-security/pom.xml
@@ -1,10 +1,9 @@
+ 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">
4.0.0
core-java-security
- 0.1.0-SNAPSHOT
core-java-security
jar
diff --git a/core-java-modules/core-java-serialization/pom.xml b/core-java-modules/core-java-serialization/pom.xml
index c82ae9d1d6fa..04144fb27f03 100644
--- a/core-java-modules/core-java-serialization/pom.xml
+++ b/core-java-modules/core-java-serialization/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-serialization
- 0.1.0-SNAPSHOT
core-java-serialization
jar
diff --git a/core-java-modules/core-java-streams-2/pom.xml b/core-java-modules/core-java-streams-2/pom.xml
index c8fa83c55a7b..9725497b04dc 100644
--- a/core-java-modules/core-java-streams-2/pom.xml
+++ b/core-java-modules/core-java-streams-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-streams-2
- 1.0
core-java-streams-2
jar
diff --git a/core-java-modules/core-java-streams-3/pom.xml b/core-java-modules/core-java-streams-3/pom.xml
index 3074a647ff36..9c657119b5f4 100644
--- a/core-java-modules/core-java-streams-3/pom.xml
+++ b/core-java-modules/core-java-streams-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-streams-3
- 0.1.0-SNAPSHOT
core-java-streams-3
jar
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/flatmap/map/Java8MapAndFlatMapUnitTest.java
similarity index 94%
rename from core-java-modules/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java
rename to core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/flatmap/map/Java8MapAndFlatMapUnitTest.java
index a0bd1cf09395..1b09ea25c61b 100644
--- a/core-java-modules/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java
+++ b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/flatmap/map/Java8MapAndFlatMapUnitTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.java8;
+package com.baeldung.streams.flatmap.map;
import org.junit.Test;
@@ -12,7 +12,7 @@
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
-public class Java8MapAndFlatMap {
+public class Java8MapAndFlatMapUnitTest {
@Test
public void givenStream_whenCalledMap_thenProduceList() {
diff --git a/core-java-modules/core-java-streams-4/README.md b/core-java-modules/core-java-streams-4/README.md
index 4175fb1f700e..c6717ec5feee 100644
--- a/core-java-modules/core-java-streams-4/README.md
+++ b/core-java-modules/core-java-streams-4/README.md
@@ -10,4 +10,3 @@
- [Understanding the Difference Between Stream.of() and IntStream.range()](https://www.baeldung.com/java-stream-of-and-intstream-range)
- [Check if Object Is an Array in Java](https://www.baeldung.com/java-check-if-object-is-an-array)
- [Mapping an Array of Integers to Strings Using Java Streams](https://www.baeldung.com/java-stream-integer-array-to-strings)
-- [Difference Between parallelStream() and stream().parallel() in Java](https://www.baeldung.com/java-parallelstream-vs-stream-parallel)
diff --git a/core-java-modules/core-java-streams-4/pom.xml b/core-java-modules/core-java-streams-4/pom.xml
index 46c0f3f7e124..fe791ebd42ee 100644
--- a/core-java-modules/core-java-streams-4/pom.xml
+++ b/core-java-modules/core-java-streams-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-streams-4
- 0.1.0-SNAPSHOT
core-java-streams-4
jar
diff --git a/core-java-modules/core-java-streams-5/README.md b/core-java-modules/core-java-streams-5/README.md
new file mode 100644
index 000000000000..4f367799f2dd
--- /dev/null
+++ b/core-java-modules/core-java-streams-5/README.md
@@ -0,0 +1 @@
+- [Difference Between parallelStream() and stream().parallel() in Java](https://www.baeldung.com/java-parallelstream-vs-stream-parallel)
diff --git a/core-java-modules/core-java-streams-5/pom.xml b/core-java-modules/core-java-streams-5/pom.xml
new file mode 100644
index 000000000000..d1f8af64618b
--- /dev/null
+++ b/core-java-modules/core-java-streams-5/pom.xml
@@ -0,0 +1,72 @@
+
+
+ 4.0.0
+ core-java-streams-5
+ core-java-streams-5
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ log4j
+ log4j
+ ${log4j.version}
+
+
+ org.junit
+ junit-bom
+ ${junit-jupiter.version}
+ pom
+ import
+
+
+ org.assertj
+ assertj-core
+ 3.23.1
+ test
+
+
+ org.apache.commons
+ commons-lang3
+ 3.12.0
+ test
+
+
+
+
+ core-java-streams-4
+
+
+ ../core-java-streams-4/src/main
+ true
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ ${maven.compiler.target}
+ -parameters
+
+
+
+
+
+
+
+ 3.1
+ 12
+ 12
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/emptystreams/EmptyStreams.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/emptystreams/EmptyStreams.java
new file mode 100644
index 000000000000..e561cfc8c190
--- /dev/null
+++ b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/emptystreams/EmptyStreams.java
@@ -0,0 +1,49 @@
+package com.baeldung.streams.emptystreams;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Optional;
+import java.util.function.Supplier;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+public class EmptyStreams {
+
+ public static void main(String[] args) {
+
+ createEmptyStreams();
+ checkForEmptyStreamUsingSupplier();
+ }
+
+ private static void createEmptyStreams() {
+
+ // Using Stream.empty()
+ Stream emptyStream = Stream.empty();
+ System.out.println(emptyStream.findAny().isEmpty());
+
+ // Using Stream.of()
+ emptyStream = Stream.of();
+ System.out.println(emptyStream.findAny().isEmpty());
+
+ // Empty Stream of primitive type
+ IntStream emptyIntStream = IntStream.of(new int[] {});
+ System.out.println(emptyIntStream.findAny().isEmpty());
+
+ // Using Arrays.stream()
+ emptyIntStream = Arrays.stream(new int[] {});
+ System.out.println(emptyIntStream.findAny().isEmpty());
+
+ // Using list.stream()
+ Stream collectionStream = new ArrayList().stream();
+ System.out.println(collectionStream.findAny().isEmpty());
+ }
+
+ private static void checkForEmptyStreamUsingSupplier() {
+ Supplier> streamSupplier = () -> Stream.of(1, 2, 3, 4, 5).filter(number -> number > 5);
+
+ Optional result1 = streamSupplier.get().findAny();
+ System.out.println(result1.isEmpty());
+ Optional result2 = streamSupplier.get().findFirst();
+ System.out.println(result2.isEmpty());
+ }
+}
diff --git a/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/parallelstream/Book.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/Book.java
similarity index 99%
rename from core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/parallelstream/Book.java
rename to core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/Book.java
index 165df551665e..d52a31aac955 100644
--- a/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/parallelstream/Book.java
+++ b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/Book.java
@@ -34,4 +34,4 @@ public int getYearPublished() {
public void setYearPublished(int yearPublished) {
this.yearPublished = yearPublished;
}
-}
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/parallelstream/BookSpliterator.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/BookSpliterator.java
similarity index 99%
rename from core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/parallelstream/BookSpliterator.java
rename to core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/BookSpliterator.java
index 14e87e0b07d5..7460e1372b6f 100644
--- a/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/parallelstream/BookSpliterator.java
+++ b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/BookSpliterator.java
@@ -37,4 +37,4 @@ public long estimateSize() {
public int characteristics() {
return CONCURRENT;
}
-}
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/parallelstream/MyBookContainer.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/MyBookContainer.java
similarity index 99%
rename from core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/parallelstream/MyBookContainer.java
rename to core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/MyBookContainer.java
index dc4b0e2623ee..d7e3adc5f180 100644
--- a/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/parallelstream/MyBookContainer.java
+++ b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/MyBookContainer.java
@@ -90,4 +90,4 @@ public boolean retainAll(Collection> c) {
public void clear() {
}
-}
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/parallelstream/ParallelStreamApplication.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/ParallelStreamApplication.java
similarity index 99%
rename from core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/parallelstream/ParallelStreamApplication.java
rename to core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/ParallelStreamApplication.java
index 9cdaf58bfb46..4297bdd3ed0d 100644
--- a/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/parallelstream/ParallelStreamApplication.java
+++ b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/ParallelStreamApplication.java
@@ -38,4 +38,4 @@ public long usingWithCustomSpliterator(MyBookContainer listOfBooks, int ye
});
return countOfBooks.get();
}
-}
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-streams-4/src/test/java/parallelstream/ParallelStreamUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/parallelstream/ParallelStreamUnitTest.java
similarity index 97%
rename from core-java-modules/core-java-streams-4/src/test/java/parallelstream/ParallelStreamUnitTest.java
rename to core-java-modules/core-java-streams-5/src/test/java/com/baeldung/parallelstream/ParallelStreamUnitTest.java
index 5542a21020d8..af8172a10dd1 100644
--- a/core-java-modules/core-java-streams-4/src/test/java/parallelstream/ParallelStreamUnitTest.java
+++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/parallelstream/ParallelStreamUnitTest.java
@@ -1,6 +1,5 @@
-package parallelstream;
+package com.baeldung.parallelstream;
-import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/emptystreams/EmptyStreamsUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/emptystreams/EmptyStreamsUnitTest.java
new file mode 100644
index 000000000000..a05eca1fcbb4
--- /dev/null
+++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/emptystreams/EmptyStreamsUnitTest.java
@@ -0,0 +1,44 @@
+package com.baeldung.streams.emptystreams;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Optional;
+import java.util.function.Supplier;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import org.junit.Test;
+
+public class EmptyStreamsUnitTest {
+
+ @Test
+ public void givenEmptyStreams_findAnyReturnsAnEmptyOptional() {
+
+ Stream emptyStream = Stream.empty();
+ assertTrue(emptyStream.findAny().isEmpty());
+
+ emptyStream = Stream.of();
+ assertTrue(emptyStream.findAny().isEmpty());
+
+ IntStream emptyIntStream = IntStream.of(new int[] {});
+ assertTrue(emptyIntStream.findAny().isEmpty());
+
+ emptyIntStream = Arrays.stream(new int[] {});
+ assertTrue(emptyIntStream.findAny().isEmpty());
+
+ Stream collectionStream = new ArrayList().stream();
+ assertTrue(collectionStream.findAny().isEmpty());
+ }
+
+ @Test
+ public void givenAStreamToSupplier_NewInstanceOfTheStreamIsReturnedForEveryGetCall() {
+ Supplier> streamSupplier = () -> Stream.of(1, 2, 3, 4, 5).filter(number -> number > 5);
+
+ Optional result1 = streamSupplier.get().findAny();
+ assertTrue(result1.isEmpty());
+ Optional result2 = streamSupplier.get().findFirst();
+ assertTrue(result2.isEmpty());
+ }
+}
diff --git a/core-java-modules/core-java-streams-collect/pom.xml b/core-java-modules/core-java-streams-collect/pom.xml
index c60cf2ab933d..e81598017cb3 100644
--- a/core-java-modules/core-java-streams-collect/pom.xml
+++ b/core-java-modules/core-java-streams-collect/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-streams-4
- 0.1.0-SNAPSHOT
core-java-streams-collect
jar
@@ -35,7 +34,6 @@
-
3.23.1
diff --git a/core-java-modules/core-java-streams-maps/pom.xml b/core-java-modules/core-java-streams-maps/pom.xml
index 06cc9ceef6b4..66e1fedd874c 100644
--- a/core-java-modules/core-java-streams-maps/pom.xml
+++ b/core-java-modules/core-java-streams-maps/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-streams-maps
- 0.1.0-SNAPSHOT
core-java-streams-maps
jar
diff --git a/core-java-modules/core-java-streams/pom.xml b/core-java-modules/core-java-streams/pom.xml
index a6bb827e77b7..b0794829c295 100644
--- a/core-java-modules/core-java-streams/pom.xml
+++ b/core-java-modules/core-java-streams/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-streams
- 0.1.0-SNAPSHOT
core-java-streams
jar
@@ -15,7 +14,6 @@
-
org.openjdk.jmh
jmh-core
diff --git a/core-java-modules/core-java-string-algorithms-2/pom.xml b/core-java-modules/core-java-string-algorithms-2/pom.xml
index 5af187abc205..3fdb022a4b46 100644
--- a/core-java-modules/core-java-string-algorithms-2/pom.xml
+++ b/core-java-modules/core-java-string-algorithms-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-algorithms-2
- 0.1.0-SNAPSHOT
core-java-string-algorithms-2
jar
diff --git a/core-java-modules/core-java-string-algorithms-3/README.md b/core-java-modules/core-java-string-algorithms-3/README.md
index d2863be8e5b3..c9e7e7d7d4d2 100644
--- a/core-java-modules/core-java-string-algorithms-3/README.md
+++ b/core-java-modules/core-java-string-algorithms-3/README.md
@@ -10,3 +10,4 @@ This module contains articles about string-related algorithms.
- [Check if the First Letter of a String is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase)
- [Find the First Non Repeating Character in a String in Java](https://www.baeldung.com/java-find-the-first-non-repeating-character)
- [Find the First Embedded Occurrence of an Integer in a Java String](https://www.baeldung.com/java-string-find-embedded-integer)
+- [Find the Most Frequent Characters in a String](https://www.baeldung.com/java-string-find-most-frequent-characters)
diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml
index 147ea22375da..7d4adeba92a5 100644
--- a/core-java-modules/core-java-string-algorithms-3/pom.xml
+++ b/core-java-modules/core-java-string-algorithms-3/pom.xml
@@ -3,7 +3,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-algorithms-3
- 0.1.0-SNAPSHOT
core-java-string-algorithms-3
jar
@@ -40,8 +39,8 @@
maven-compiler-plugin
${maven-compiler-plugin.version}
-
- ${java.version}
+
+ ${maven.compiler.target}
-parameters
diff --git a/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/charfreq/CharacterWithHighestFrequency.java b/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/charfreq/CharacterWithHighestFrequency.java
new file mode 100644
index 000000000000..938ad1edf319
--- /dev/null
+++ b/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/charfreq/CharacterWithHighestFrequency.java
@@ -0,0 +1,58 @@
+package com.baeldung.charfreq;
+
+import static java.util.Map.Entry.comparingByValue;
+import static java.util.stream.Collectors.counting;
+import static java.util.stream.Collectors.groupingBy;
+import static java.util.stream.Collectors.toSet;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+public class CharacterWithHighestFrequency {
+ public static Character byStream(String input) {
+ return input.chars()
+ .mapToObj(x -> (char) x)
+ .collect(groupingBy(x -> x, counting()))
+ .entrySet()
+ .stream()
+ .max(comparingByValue())
+ .get()
+ .getKey();
+ }
+
+ public static Set byMap(String input) {
+ Map map = new HashMap<>();
+ for (char c : input.toCharArray()) {
+ map.compute(c, (character, count) -> count == null ? 1 : ++count);
+ }
+ int maxCount = map.values()
+ .stream()
+ .mapToInt(Integer::intValue)
+ .max()
+ .getAsInt();
+
+ return map.keySet()
+ .stream()
+ .filter(c -> map.get(c) == maxCount)
+ .collect(toSet());
+ }
+
+ public static Set byBucket(String input) {
+ int[] buckets = new int[128];
+
+ int maxCount = 0;
+ for (char c : input.toCharArray()) {
+ buckets[c]++;
+ maxCount = Math.max(buckets[c], maxCount);
+ }
+
+ int finalMaxCount = maxCount;
+ return IntStream.range(0, 128)
+ .filter(c -> buckets[c] == finalMaxCount)
+ .mapToObj(i -> (char) i)
+ .collect(Collectors.toSet());
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/charfreq/CharacterWithHighestFrequencyUnitTest.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/charfreq/CharacterWithHighestFrequencyUnitTest.java
new file mode 100644
index 000000000000..978752f3d416
--- /dev/null
+++ b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/charfreq/CharacterWithHighestFrequencyUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.charfreq;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Collections;
+import java.util.Set;
+
+import org.junit.jupiter.api.Test;
+
+import com.google.common.collect.ImmutableSet;
+
+class CharacterWithHighestFrequencyUnitTest {
+ private static final String INPUT1 = "aaaaaaaaaa(10) bbbbbbb ccccc dddd eee ff";
+ private static final Set EXPECTED1 = Collections.singleton('a');
+
+ private static final String INPUT2 = "YYYYYYY(7) bbbbb -------(7) dddd eee kkkkkkk(7) ff";
+ private static final Set EXPECTED2 = ImmutableSet.of('Y', '-', 'k');
+
+ @Test
+ void whenGettingSingleCharWithHighestFrequencyByStream_shouldSuccess() {
+ char result1 = CharacterWithHighestFrequency.byStream(INPUT1);
+ assertEquals('a', result1);
+ }
+
+ @Test
+ void whenGettingCharWithHighestFrequencyByMap_shouldSuccess() {
+ Set result1 = CharacterWithHighestFrequency.byMap(INPUT1);
+ assertEquals(EXPECTED1, result1);
+
+ Set result2 = CharacterWithHighestFrequency.byMap(INPUT2);
+ assertEquals(EXPECTED2, result2);
+
+ }
+
+ @Test
+ void whenGettingCharWithHighestFrequencyByBucket_shouldSuccess() {
+ Set result1 = CharacterWithHighestFrequency.byBucket(INPUT1);
+ assertEquals(EXPECTED1, result1);
+
+ Set result2 = CharacterWithHighestFrequency.byBucket(INPUT2);
+ assertEquals(EXPECTED2, result2);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-algorithms/pom.xml b/core-java-modules/core-java-string-algorithms/pom.xml
index 84f3b61f8473..10d28feb2f4c 100644
--- a/core-java-modules/core-java-string-algorithms/pom.xml
+++ b/core-java-modules/core-java-string-algorithms/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-algorithms
- 0.1.0-SNAPSHOT
core-java-string-algorithms
jar
diff --git a/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java
index 5236f14ccdb8..07663ab7d1ec 100644
--- a/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java
+++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java
@@ -1,5 +1,9 @@
package com.baeldung.reverse;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
import org.apache.commons.lang3.StringUtils;
public class ReverseStringExamples {
@@ -46,11 +50,43 @@ public static String reverseTheOrderOfWords(String sentence) {
}
return output.toString()
- .trim();
+ .trim();
}
public static String reverseTheOrderOfWordsUsingApacheCommons(String sentence) {
return StringUtils.reverseDelimited(sentence, ' ');
}
+ public static String reverseUsingIntStreamRangeMethod(String str) {
+ if (str == null) {
+ return null;
+ }
+
+ char[] charArray = str.toCharArray();
+ return IntStream.range(0, str.length())
+ .mapToObj(i -> charArray[str.length() - i - 1])
+ .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
+ .toString();
+ }
+
+ public static String reverseUsingStreamOfMethod(String str) {
+ if (str == null) {
+ return null;
+ }
+
+ return Stream.of(str)
+ .map(string -> new StringBuilder(string).reverse())
+ .collect(Collectors.joining());
+ }
+
+ public static String reverseUsingCharsMethod(String str) {
+ if (str == null) {
+ return null;
+ }
+
+ return str.chars()
+ .mapToObj(c -> (char) c)
+ .reduce("", (a, b) -> b + a, (a2, b2) -> b2 + a2);
+ }
+
}
diff --git a/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/reverse/ReverseStringExamplesUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/reverse/ReverseStringExamplesUnitTest.java
index c12216317420..b3685a49da68 100644
--- a/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/reverse/ReverseStringExamplesUnitTest.java
+++ b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/reverse/ReverseStringExamplesUnitTest.java
@@ -1,10 +1,11 @@
package com.baeldung.reverse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-
public class ReverseStringExamplesUnitTest {
private static final String STRING_INPUT = "cat";
@@ -19,7 +20,7 @@ public void whenReverseIsCalled_ThenCorrectStringIsReturned() {
String reversedEmpty = ReverseStringExamples.reverse(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
- assertEquals(null, reversedNull);
+ assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@@ -30,7 +31,7 @@ public void whenReverseUsingStringBuilderIsCalled_ThenCorrectStringIsReturned()
String reversedEmpty = ReverseStringExamples.reverseUsingStringBuilder(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
- assertEquals(null, reversedNull);
+ assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@@ -41,7 +42,7 @@ public void whenReverseUsingApacheCommonsIsCalled_ThenCorrectStringIsReturned()
String reversedEmpty = ReverseStringExamples.reverseUsingApacheCommons(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
- assertEquals(null, reversedNull);
+ assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@@ -52,7 +53,7 @@ public void whenReverseTheOrderOfWordsIsCalled_ThenCorrectStringIsReturned() {
String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWords(StringUtils.EMPTY);
assertEquals(REVERSED_WORDS_SENTENCE, reversed);
- assertEquals(null, reversedNull);
+ assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@@ -63,7 +64,40 @@ public void whenReverseTheOrderOfWordsUsingApacheCommonsIsCalled_ThenCorrectStri
String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(StringUtils.EMPTY);
assertEquals(REVERSED_WORDS_SENTENCE, reversed);
- assertEquals(null, reversedNull);
+ assertNull(reversedNull);
+ assertEquals(StringUtils.EMPTY, reversedEmpty);
+ }
+
+ @Test
+ public void whenReverseStringUsingIntStreamRangeMethod_ThenCorrectStringIsReturned() {
+ String reversed = ReverseStringExamples.reverseUsingIntStreamRangeMethod(STRING_INPUT);
+ String reversedNull = ReverseStringExamples.reverseUsingIntStreamRangeMethod(null);
+ String reversedEmpty = ReverseStringExamples.reverseUsingIntStreamRangeMethod(StringUtils.EMPTY);
+
+ assertEquals(STRING_INPUT_REVERSED, reversed);
+ assertNull(reversedNull);
+ assertEquals(StringUtils.EMPTY, reversedEmpty);
+ }
+
+ @Test
+ public void whenReverseStringUsingCharsMethod_ThenCorrectStringIsReturned() {
+ String reversed = ReverseStringExamples.reverseUsingCharsMethod(STRING_INPUT);
+ String reversedNull = ReverseStringExamples.reverseUsingCharsMethod(null);
+ String reversedEmpty = ReverseStringExamples.reverseUsingCharsMethod(StringUtils.EMPTY);
+
+ assertEquals(STRING_INPUT_REVERSED, reversed);
+ assertNull(reversedNull);
+ assertEquals(StringUtils.EMPTY, reversedEmpty);
+ }
+
+ @Test
+ public void whenReverseStringUsingStreamOfMethod_ThenCorrectStringIsReturned() {
+ String reversed = ReverseStringExamples.reverseUsingStreamOfMethod(STRING_INPUT);
+ String reversedNull = ReverseStringExamples.reverseUsingStreamOfMethod(null);
+ String reversedEmpty = ReverseStringExamples.reverseUsingStreamOfMethod(StringUtils.EMPTY);
+
+ assertEquals(STRING_INPUT_REVERSED, reversed);
+ assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
diff --git a/core-java-modules/core-java-string-apis-2/README.md b/core-java-modules/core-java-string-apis-2/README.md
index 5476e9116967..d1ec0d8388e3 100644
--- a/core-java-modules/core-java-string-apis-2/README.md
+++ b/core-java-modules/core-java-string-apis-2/README.md
@@ -4,3 +4,4 @@ This module contains articles about string APIs.
### Relevant Articles:
- [Retain Only Digits and Decimal Separator in String](https://www.baeldung.com/java-string-retain-digits-decimal)
+- [Difference Between null and Empty String in Java](https://www.baeldung.com/java-string-null-vs-empty)
diff --git a/core-java-modules/core-java-string-apis-2/pom.xml b/core-java-modules/core-java-string-apis-2/pom.xml
index ba983d759392..db97b8574819 100644
--- a/core-java-modules/core-java-string-apis-2/pom.xml
+++ b/core-java-modules/core-java-string-apis-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-apis-2
- 0.0.1-SNAPSHOT
core-java-string-apis-2
jar
diff --git a/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/nullandempty/NullAndEmptyStringUnitTest.java b/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/nullandempty/NullAndEmptyStringUnitTest.java
new file mode 100644
index 000000000000..332a16fd8439
--- /dev/null
+++ b/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/nullandempty/NullAndEmptyStringUnitTest.java
@@ -0,0 +1,27 @@
+package com.baeldung.nullandempty;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+
+import org.junit.jupiter.api.Test;
+
+public class NullAndEmptyStringUnitTest {
+
+ @Test
+ void givenANullAndEmptyString_whenUsingStringMethods_thenShouldGetExpectedResult() {
+ String nullString = null;
+ String emptyString = "";
+ assertTrue(emptyString.equals(""));
+ assertThrows(NullPointerException.class, () -> nullString.length());
+ }
+
+ @Test
+ void givenANullAndEmptyString_whenCheckingEquality_thenShouldGetExpectedResult() {
+ String nullString = null;
+ String emptyString = "";
+ assertFalse(emptyString.equals(nullString));
+ assertFalse(emptyString == nullString);
+ }
+
+}
diff --git a/core-java-modules/core-java-string-apis/pom.xml b/core-java-modules/core-java-string-apis/pom.xml
index 6a382c3c57ae..5d7737228c38 100644
--- a/core-java-modules/core-java-string-apis/pom.xml
+++ b/core-java-modules/core-java-string-apis/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-apis
- 0.1.0-SNAPSHOT
core-java-string-apis
jar
diff --git a/core-java-modules/core-java-string-conversions-2/pom.xml b/core-java-modules/core-java-string-conversions-2/pom.xml
index e424ef3083be..90463271b8a0 100644
--- a/core-java-modules/core-java-string-conversions-2/pom.xml
+++ b/core-java-modules/core-java-string-conversions-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-conversions-2
- 0.1.0-SNAPSHOT
core-java-string-conversions-2
jar
diff --git a/core-java-modules/core-java-string-conversions-3/pom.xml b/core-java-modules/core-java-string-conversions-3/pom.xml
new file mode 100644
index 000000000000..1fdf79283f24
--- /dev/null
+++ b/core-java-modules/core-java-string-conversions-3/pom.xml
@@ -0,0 +1,27 @@
+
+
+ 4.0.0
+ core-java-string-conversions-3
+ core-java-string-conversions-3
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+ core-java-string-conversions-3
+
+
+ src/main/resources
+ true
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-conversions-3/src/main/java/com/baeldung/valueofcomparison/Student.java b/core-java-modules/core-java-string-conversions-3/src/main/java/com/baeldung/valueofcomparison/Student.java
new file mode 100644
index 000000000000..38bdea77fea2
--- /dev/null
+++ b/core-java-modules/core-java-string-conversions-3/src/main/java/com/baeldung/valueofcomparison/Student.java
@@ -0,0 +1,17 @@
+package com.baeldung.valueofcomparison;
+
+public class Student {
+
+ public String name;
+ public int age;
+
+ public Student(String name, int age) {
+ this.name = name;
+ this.age = age;
+ }
+
+ @Override
+ public String toString() {
+ return "Student(" + name + ", age " + age + ')';
+ }
+}
diff --git a/core-java-modules/core-java-string-conversions-3/src/test/java/com/baeldung/valueofcomparison/ValueOfUnitTest.java b/core-java-modules/core-java-string-conversions-3/src/test/java/com/baeldung/valueofcomparison/ValueOfUnitTest.java
new file mode 100644
index 000000000000..5f107b1a6878
--- /dev/null
+++ b/core-java-modules/core-java-string-conversions-3/src/test/java/com/baeldung/valueofcomparison/ValueOfUnitTest.java
@@ -0,0 +1,24 @@
+package com.baeldung.valueofcomparison;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+public class ValueOfUnitTest {
+
+ @Test
+ void whenCallingValueOf_thenMapToString() {
+ char[] exampleCharArray = {'a', 'b', 'c'};
+ Student alice = new Student("Alice", 5);
+
+ assertEquals("true", String.valueOf(true));
+ assertEquals("a", String.valueOf('a'));
+ assertEquals("abc", String.valueOf(exampleCharArray));
+ assertEquals("123.935", String.valueOf(123.935));
+ assertEquals("2222.3", String.valueOf(2222.3f));
+ assertEquals("2222", String.valueOf(2222));
+ assertEquals("123456789", String.valueOf(123456789L));
+ assertEquals("123456789", String.valueOf(123456789L));
+ assertEquals("Student(Alice, age 5)", String.valueOf(alice));
+ }
+}
diff --git a/core-java-modules/core-java-string-conversions/pom.xml b/core-java-modules/core-java-string-conversions/pom.xml
index c715e22ed4ff..b87431cd0bf0 100644
--- a/core-java-modules/core-java-string-conversions/pom.xml
+++ b/core-java-modules/core-java-string-conversions/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-conversions
- 0.1.0-SNAPSHOT
core-java-string-conversions
jar
diff --git a/core-java-modules/core-java-string-conversions/src/main/java/com/baeldung/stringtoint/StringToIntConverter.java b/core-java-modules/core-java-string-conversions/src/main/java/com/baeldung/stringtoint/StringToIntConverter.java
deleted file mode 100644
index 03d77c2aea1a..000000000000
--- a/core-java-modules/core-java-string-conversions/src/main/java/com/baeldung/stringtoint/StringToIntConverter.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package com.baeldung.stringtoint;
-
-import java.util.Optional;
-import org.apache.commons.lang3.math.NumberUtils;
-
-public class StringToIntConverter {
-
- private StringToIntConverter() {
- }
-
- public static Integer convertStringToIntUsingIntegerParseInt(String input){
- try {
- return Integer.parseInt(input);
- } catch (NumberFormatException e) {
- // log or handle the error
- return Integer.MIN_VALUE;
- }
- }
-
- public static Integer convertStringToIntUsingIntegerValueOf(String input){
- try {
- return Integer.valueOf(input);
- } catch (NumberFormatException e) {
- // log or handle the error
- return Integer.MIN_VALUE;
- }
- }
-
- public static Integer convertStringToIntUsingIntegerDecode(String input){
- try {
- return Integer.decode(input);
- } catch (Exception e) {
- // log or handle the error
- return Integer.MIN_VALUE;
- }
- }
-
- public static Integer convertStringToIntUsingOptional(String input){
- Optional parsedInt;
- try {
- parsedInt = Optional.of(Integer.parseInt(input));
- } catch (Exception e) {
- // log or handle the error
- parsedInt = Optional.empty();
- }
- return parsedInt.orElse(Integer.MIN_VALUE);
- }
-
- public static int convertStringToIntUsingNumberUtils(String input){
- return NumberUtils.toInt(input, Integer.MIN_VALUE);
- }
-}
diff --git a/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/stringtoint/StringToIntConverterUnitTest.java b/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/stringtoint/StringToIntConverterUnitTest.java
deleted file mode 100644
index 2bfb4db161ac..000000000000
--- a/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/stringtoint/StringToIntConverterUnitTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package com.baeldung.stringtoint;
-
-import java.util.Arrays;
-import java.util.List;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.Test;
-
-class StringToIntConverterUnitTest {
-
- @Test
- void whenConvertingIntToString_thenInvalidCasesReturnIntegerMinValue() {
- List testData = Arrays.asList(
- new TestData("", Integer.MIN_VALUE),
- new TestData(null, Integer.MIN_VALUE),
- new TestData("23,56", Integer.MIN_VALUE),
- new TestData("2147483648", Integer.MIN_VALUE),
- new TestData("-2147483649", Integer.MIN_VALUE),
- new TestData("hello", Integer.MIN_VALUE)
- );
- testData.forEach(data -> {
- Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingIntegerParseInt(data.input));
- Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingIntegerValueOf(data.input));
- Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingOptional(data.input));
- Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingIntegerDecode(data.input));
- Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingNumberUtils(data.input));
- });
- }
-
- @Test
- void whenConvertingIntToString_thenValidCasesReturnUnboxedInt() {
- List testData = Arrays.asList(
- new TestData("23", 23),
- new TestData("-23", -23)
- );
- testData.forEach(data -> {
- Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingIntegerParseInt(data.input));
- Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingIntegerValueOf(data.input));
- Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingOptional(data.input));
- Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingNumberUtils(data.input));
- Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingIntegerDecode(data.input));
- });
- }
-
- public static class TestData{
- String input;
- Integer expectedOutput;
-
- TestData(String input, Integer expectedOutput){
- this.input = input;
- this.expectedOutput = expectedOutput;
- }
- }
-}
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml
index 92bfa6b2d82c..c6debc4f71d8 100644
--- a/core-java-modules/core-java-string-operations-2/pom.xml
+++ b/core-java-modules/core-java-string-operations-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-operations-2
- 0.1.0-SNAPSHOT
core-java-string-operations-2
jar
diff --git a/core-java-modules/core-java-string-operations-3/pom.xml b/core-java-modules/core-java-string-operations-3/pom.xml
index 19b3d57ffdc5..39167271fa8f 100644
--- a/core-java-modules/core-java-string-operations-3/pom.xml
+++ b/core-java-modules/core-java-string-operations-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-operations-3
- 0.1.0-SNAPSHOT
core-java-string-operations-3
jar
diff --git a/core-java-modules/core-java-string-operations-4/pom.xml b/core-java-modules/core-java-string-operations-4/pom.xml
index 0f1e377d1865..cc755cf470dc 100644
--- a/core-java-modules/core-java-string-operations-4/pom.xml
+++ b/core-java-modules/core-java-string-operations-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-operations-4
- 0.1.0-SNAPSHOT
core-java-string-operations-4
jar
diff --git a/core-java-modules/core-java-string-operations-5/README.md b/core-java-modules/core-java-string-operations-5/README.md
index 94fb7e855ebc..3a09c8a585e3 100644
--- a/core-java-modules/core-java-string-operations-5/README.md
+++ b/core-java-modules/core-java-string-operations-5/README.md
@@ -8,3 +8,7 @@
- [Convert String to String Array](https://www.baeldung.com/java-convert-string-to-string-array)
- [String Interpolation in Java](https://www.baeldung.com/java-string-interpolation)
- [Guide to Splitting a String by Whitespace in Java](https://www.baeldung.com/java-splitting-a-string-by-whitespace)
+- [Check if the First Letter of a String Is a Number](https://www.baeldung.com/java-check-if-string-starts-with-number)
+- [Print “” Quotes Around a String in Java](https://www.baeldung.com/java-string-print-quotes)
+- [Remove Punctuation From a String in Java](https://www.baeldung.com/java-remove-punctuation-from-string)
+- [Find the Longest Word in a Given String in Java](https://www.baeldung.com/java-longest-word-string)
diff --git a/core-java-modules/core-java-string-operations-5/pom.xml b/core-java-modules/core-java-string-operations-5/pom.xml
index efb32c73b949..2a2a353984bd 100644
--- a/core-java-modules/core-java-string-operations-5/pom.xml
+++ b/core-java-modules/core-java-string-operations-5/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-operations-5
- 0.1.0-SNAPSHOT
core-java-string-operations-5
jar
diff --git a/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/firstchardigit/FirstCharDigit.java b/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/firstchardigit/FirstCharDigit.java
new file mode 100644
index 000000000000..a43127af1ae0
--- /dev/null
+++ b/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/firstchardigit/FirstCharDigit.java
@@ -0,0 +1,62 @@
+package com.baeldung.firstchardigit;
+
+import java.util.regex.Pattern;
+
+import com.google.common.base.CharMatcher;
+
+public class FirstCharDigit {
+
+ public static boolean checkUsingCharAtMethod(String str) {
+ if (str == null || str.length() == 0) {
+ return false;
+ }
+
+ char c = str.charAt(0);
+ return c >= '0' && c <= '9';
+ }
+
+ public static boolean checkUsingIsDigitMethod(String str) {
+ if (str == null || str.length() == 0) {
+ return false;
+ }
+
+ return Character.isDigit(str.charAt(0));
+ }
+
+ public static boolean checkUsingPatternClass(String str) {
+ if (str == null || str.length() == 0) {
+ return false;
+ }
+
+ return Pattern.compile("^[0-9].*")
+ .matcher(str)
+ .matches();
+ }
+
+ public static boolean checkUsingMatchesMethod(String str) {
+ if (str == null || str.length() == 0) {
+ return false;
+ }
+
+ return str.matches("^[0-9].*");
+ }
+
+ public static boolean checkUsingCharMatcherInRangeMethod(String str) {
+ if (str == null || str.length() == 0) {
+ return false;
+ }
+
+ return CharMatcher.inRange('0', '9')
+ .matches(str.charAt(0));
+ }
+
+ public static boolean checkUsingCharMatcherForPredicateMethod(String str) {
+ if (str == null || str.length() == 0) {
+ return false;
+ }
+
+ return CharMatcher.forPredicate(Character::isDigit)
+ .matches(str.charAt(0));
+ }
+
+}
diff --git a/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/longestword/LongestWordFinder.java b/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/longestword/LongestWordFinder.java
new file mode 100644
index 000000000000..770984ac2968
--- /dev/null
+++ b/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/longestword/LongestWordFinder.java
@@ -0,0 +1,36 @@
+package com.baeldung.longestword;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+public class LongestWordFinder {
+
+ public Optional findLongestWord(String sentence) {
+ return Optional.ofNullable(sentence)
+ .filter(string -> !string.trim()
+ .isEmpty())
+ .map(string -> string.split("\\s"))
+ .map(Arrays::asList)
+ .map(list -> Collections.max(list, Comparator.comparingInt(String::length)));
+ }
+
+ public List findLongestWords(String sentence) {
+ if (sentence == null || sentence.trim()
+ .isEmpty()) {
+ return Collections.emptyList();
+ }
+ String[] words = sentence.split("\\s");
+ int maxWordLength = Arrays.stream(words)
+ .mapToInt(String::length)
+ .max()
+ .orElseThrow();
+ return Arrays.stream(words)
+ .filter(word -> word.length() == maxWordLength)
+ .collect(Collectors.toList());
+ }
+
+}
diff --git a/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/delpunctuation/RemovePunctuationUnitTest.java b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/delpunctuation/RemovePunctuationUnitTest.java
new file mode 100644
index 000000000000..751ae0f4bcd9
--- /dev/null
+++ b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/delpunctuation/RemovePunctuationUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.delpunctuation;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+import org.junit.jupiter.api.Test;
+
+public class RemovePunctuationUnitTest {
+ private static final String INPUT = "Its 1 W o r d (!@#$%^&*{}[];':\")<>,.";
+ private static final String EXPECTED = "Its 1 W o r d ";
+
+ private static final String UNICODE_INPUT = "3 March März 三月 březen маршировать (!@#$%^&*{}[];':\")<>,.";
+ private static final String UNICODE_EXPECTED = "3 March März 三月 březen маршировать ";
+
+ @Test
+ void whenUsingCharClassRange_thenGetExceptedResult() {
+ String result = INPUT.replaceAll("[^\\sa-zA-Z0-9]", "");
+ assertEquals(EXPECTED, result);
+ }
+
+ @Test
+ void whenUsingPunctuationCharClass_thenGetExceptedResult() {
+ String result = INPUT.replaceAll("\\p{Punct}", "");
+ assertEquals(EXPECTED, result);
+ }
+
+ @Test
+ void whenInputContainsUnicodeChars_thenGetExceptedResult() {
+ String result1 = UNICODE_INPUT.replaceAll("[^\\sa-zA-Z0-9]", "");
+ assertNotEquals(UNICODE_EXPECTED, result1);
+
+ String actualResult1 = "3 March Mrz bezen ";
+ assertEquals(actualResult1, result1);
+
+
+ String result2 = UNICODE_INPUT.replaceAll("\\p{Punct}", "");
+ assertEquals(UNICODE_EXPECTED, result2);
+
+ String result3 = UNICODE_INPUT.replaceAll("[^\\s\\p{L}0-9]", "");
+ assertEquals(UNICODE_EXPECTED, result3);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/firstchardigit/FirstCharDigitUnitTest.java b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/firstchardigit/FirstCharDigitUnitTest.java
new file mode 100644
index 000000000000..0095ebcaf382
--- /dev/null
+++ b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/firstchardigit/FirstCharDigitUnitTest.java
@@ -0,0 +1,58 @@
+package com.baeldung.firstchardigit;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+
+class FirstCharDigitUnitTest {
+
+ @Test
+ void givenString_whenUsingCharAtMethod_thenSuccess() {
+ assertTrue(FirstCharDigit.checkUsingCharAtMethod("12 years"));
+ assertFalse(FirstCharDigit.checkUsingCharAtMethod("years"));
+ assertFalse(FirstCharDigit.checkUsingCharAtMethod(""));
+ assertFalse(FirstCharDigit.checkUsingCharAtMethod(null));
+ }
+
+ @Test
+ void givenString_whenUsingIsDigitMethod_thenSuccess() {
+ assertTrue(FirstCharDigit.checkUsingIsDigitMethod("10 cm"));
+ assertFalse(FirstCharDigit.checkUsingIsDigitMethod("cm"));
+ assertFalse(FirstCharDigit.checkUsingIsDigitMethod(""));
+ assertFalse(FirstCharDigit.checkUsingIsDigitMethod(null));
+ }
+
+ @Test
+ void givenString_whenUsingPatternClass_thenSuccess() {
+ assertTrue(FirstCharDigit.checkUsingPatternClass("1 kg"));
+ assertFalse(FirstCharDigit.checkUsingPatternClass("kg"));
+ assertFalse(FirstCharDigit.checkUsingPatternClass(""));
+ assertFalse(FirstCharDigit.checkUsingPatternClass(null));
+ }
+
+ @Test
+ void givenString_whenUsingMatchesMethod_thenSuccess() {
+ assertTrue(FirstCharDigit.checkUsingMatchesMethod("123"));
+ assertFalse(FirstCharDigit.checkUsingMatchesMethod("ABC"));
+ assertFalse(FirstCharDigit.checkUsingMatchesMethod(""));
+ assertFalse(FirstCharDigit.checkUsingMatchesMethod(null));
+ }
+
+ @Test
+ void givenString_whenUsingCharMatcherInRangeMethod_thenSuccess() {
+ assertTrue(FirstCharDigit.checkUsingCharMatcherInRangeMethod("2023"));
+ assertFalse(FirstCharDigit.checkUsingCharMatcherInRangeMethod("abc"));
+ assertFalse(FirstCharDigit.checkUsingCharMatcherInRangeMethod(""));
+ assertFalse(FirstCharDigit.checkUsingCharMatcherInRangeMethod(null));
+ }
+
+ @Test
+ void givenString_whenUsingCharMatcherForPredicateMethod_thenSuccess() {
+ assertTrue(FirstCharDigit.checkUsingCharMatcherForPredicateMethod("100"));
+ assertFalse(FirstCharDigit.checkUsingCharMatcherForPredicateMethod("abdo"));
+ assertFalse(FirstCharDigit.checkUsingCharMatcherForPredicateMethod(""));
+ assertFalse(FirstCharDigit.checkUsingCharMatcherForPredicateMethod(null));
+ }
+
+}
diff --git a/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/longestword/LongestWordFinderUnitTest.java b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/longestword/LongestWordFinderUnitTest.java
new file mode 100644
index 000000000000..9d5f82d49398
--- /dev/null
+++ b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/longestword/LongestWordFinderUnitTest.java
@@ -0,0 +1,62 @@
+package com.baeldung.longestword;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+class LongestWordFinderUnitTest {
+
+ LongestWordFinder longestWordFinder = new LongestWordFinder();
+
+ @Test
+ void givenNull_whenFindLongestWord_thenEmpty() {
+ assertThat(longestWordFinder.findLongestWord(null)).isEmpty();
+ }
+
+ @Test
+ void givenEmptyString_whenFindLongestWord_thenEmpty() {
+ assertThat(longestWordFinder.findLongestWord("")).isEmpty();
+ }
+
+ @Test
+ void givenStringWithOnlySpaces_whenFindLongestWord_thenEmpty() {
+ assertThat(longestWordFinder.findLongestWord(" ")).isEmpty();
+ }
+
+ @Test
+ void givenAPhraseWithALongestWord_whenFindLongestWord_thenLongestWordOfThePhrase() {
+ assertThat(longestWordFinder.findLongestWord("This is a phrase with words")).hasValue("phrase");
+ }
+
+ @Test
+ void givenAPhraseWithVariousWordsOfMaxLength_whenFindLongestWord_thenAnyOfTheLongestsWordsOfThePhrase() {
+ assertThat(longestWordFinder.findLongestWord("Baeldung is another word of size eight in this sentence")
+ .get()).isIn("Baeldung", "sentence");
+ }
+
+ @Test
+ void givenNull_whenFindLongestWords_thenEmpty() {
+ assertThat(longestWordFinder.findLongestWords(null)).isEmpty();
+ }
+
+ @Test
+ void givenEmptyString_whenFindLongestWords_thenEmpty() {
+ assertThat(longestWordFinder.findLongestWords("")).isEmpty();
+ }
+
+ @Test
+ void givenStringWithOnlySpaces_whenFindLongestWords_thenEmpty() {
+ assertThat(longestWordFinder.findLongestWords(" ")).isEmpty();
+ }
+
+ @Test
+ void givenAPhraseWithALongestWord_whenFindLongestWords_thenLongestWordOfThePhrase() {
+ assertThat(longestWordFinder.findLongestWords("This is a phrase with words")).containsExactly("phrase");
+ }
+
+ @Test
+ void givenAPhraseWithVariousWordsOfMaxLength_whenFindLongestWords_thenAllLongestsWords() {
+ assertThat(longestWordFinder.findLongestWords("Baeldung is another word of size eight in this sentence")).containsExactly("Baeldung", "sentence");
+ }
+
+}
diff --git a/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/stringwithquotes/PrintQuotesAroundAStringUnitTest.java b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/stringwithquotes/PrintQuotesAroundAStringUnitTest.java
new file mode 100644
index 000000000000..fd4ade1ef31a
--- /dev/null
+++ b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/stringwithquotes/PrintQuotesAroundAStringUnitTest.java
@@ -0,0 +1,60 @@
+package com.baeldung.stringwithquotes;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class PrintQuotesAroundAStringUnitTest {
+ private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
+ private final PrintStream originalOut = System.out;
+
+ @BeforeEach
+ void replaceOut() {
+ System.setOut(new PrintStream(outContent));
+ }
+
+ @AfterEach
+ void restoreOut() {
+ System.setOut(originalOut);
+ }
+
+ @Test
+ void whenWrappingAStringWithEscapedQuote_thenGetExpectedResult() {
+ String theySay = "All Java programmers are cute!";
+ String quoted = "\"" + theySay + "\"";
+
+ System.out.println(quoted);
+
+ //assertion
+ String expected = "\"All Java programmers are cute!\"\n";
+ assertEquals(expected, outContent.toString());
+ }
+
+ @Test
+ void whenCallingReplaceAll_thenGetExpectedResult() {
+ String theySay = "Can you write Java code?";
+ String quoted = theySay.replaceAll("^|$", "\"");
+
+ System.out.println(quoted);
+
+ //assertion
+ String expected = "\"Can you write Java code?\"\n";
+ assertEquals(expected, outContent.toString());
+ }
+
+ @Test
+ void whenWrappingAStringWithQuoteChar_thenGetExpectedResult() {
+ String weSay = "Yes, we can write beautiful Java codes!";
+ String quoted = '"' + weSay + '"';
+ System.out.println(quoted);
+
+ //assertion
+ String expected = "\"Yes, we can write beautiful Java codes!\"\n";
+ assertEquals(expected, outContent.toString());
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-operations/pom.xml b/core-java-modules/core-java-string-operations/pom.xml
index 097012528126..577736a32424 100644
--- a/core-java-modules/core-java-string-operations/pom.xml
+++ b/core-java-modules/core-java-string-operations/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-operations
- 0.1.0-SNAPSHOT
core-java-string-operations
jar
diff --git a/core-java-modules/core-java-strings/README.md b/core-java-modules/core-java-strings/README.md
index 835e9ec58259..84cf31e8bd40 100644
--- a/core-java-modules/core-java-strings/README.md
+++ b/core-java-modules/core-java-strings/README.md
@@ -13,3 +13,4 @@ This module contains articles about strings in Java.
- [Java Multi-line String](https://www.baeldung.com/java-multiline-string)
- [Guide to Java String Pool](https://www.baeldung.com/java-string-pool)
- [Fixing “constant string too long” Build Error](https://www.baeldung.com/java-constant-string-too-long-error)
+- [Reuse StringBuilder for Efficiency](https://www.baeldung.com/java-reuse-stringbuilder-for-efficiency)
diff --git a/core-java-modules/core-java-strings/pom.xml b/core-java-modules/core-java-strings/pom.xml
index 2cc35dad5fce..e3cdb3c66645 100644
--- a/core-java-modules/core-java-strings/pom.xml
+++ b/core-java-modules/core-java-strings/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-strings
- 0.1.0-SNAPSHOT
core-java-strings
jar
diff --git a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuilder/ReuseStringBuilderPerformance.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuilder/ReuseStringBuilderPerformance.java
new file mode 100644
index 000000000000..b403f859bc2b
--- /dev/null
+++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuilder/ReuseStringBuilderPerformance.java
@@ -0,0 +1,55 @@
+package com.baeldung.stringbuilder;
+
+import org.openjdk.jmh.annotations.*;
+import org.openjdk.jmh.runner.Runner;
+import org.openjdk.jmh.runner.options.Options;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+import java.util.concurrent.TimeUnit;
+
+@BenchmarkMode(Mode.SingleShotTime)
+@OutputTimeUnit(TimeUnit.MILLISECONDS)
+@Measurement(batchSize = 100000, iterations = 10)
+@Warmup(batchSize = 100000, iterations = 10)
+@State(Scope.Thread)
+public class ReuseStringBuilderPerformance {
+
+ @Benchmark
+ public void benchmarkStringBuilder() {
+ for (int i = 0; i < 100; i++) {
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.append("baeldung");
+ stringBuilder.toString();
+ }
+ }
+
+ @Benchmark
+ public void benchmarkStringBuilderReuseWithSetLength() {
+ StringBuilder stringBuilder = new StringBuilder();
+ for (int i = 0; i < 100; i++) {
+ stringBuilder.append("baeldung");
+ stringBuilder.toString();
+ stringBuilder.setLength(0);
+ }
+ }
+
+ @Benchmark()
+ public void benchmarkStringBuilderReuseWithDelete() {
+ StringBuilder stringBuilder = new StringBuilder();
+ for (int i = 0; i < 100; i++) {
+ stringBuilder.append("baeldung");
+ stringBuilder.toString();
+ stringBuilder.delete(0, stringBuilder.length());
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+ Options options = new OptionsBuilder()
+ .include(ReuseStringBuilderPerformance.class.getSimpleName()).threads(1)
+ .forks(1).shouldFailOnError(true)
+ .shouldDoGC(true)
+ .jvmArgs("-server").build();
+ new Runner(options).run();
+ }
+
+}
diff --git a/core-java-modules/core-java-sun/pom.xml b/core-java-modules/core-java-sun/pom.xml
index e959932235de..c9427f66a331 100644
--- a/core-java-modules/core-java-sun/pom.xml
+++ b/core-java-modules/core-java-sun/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-sun
- 0.1.0-SNAPSHOT
core-java-sun
jar
diff --git a/core-java-modules/core-java-time-measurements/pom.xml b/core-java-modules/core-java-time-measurements/pom.xml
index ac5fb3a5e67f..7b2bc31ebbb3 100644
--- a/core-java-modules/core-java-time-measurements/pom.xml
+++ b/core-java-modules/core-java-time-measurements/pom.xml
@@ -3,9 +3,7 @@
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">
4.0.0
- com.baeldung.exception.numberformat
core-java-time-measurements
- 0.0.1-SNAPSHOT
core-java-time-measurements
jar
diff --git a/core-java-modules/core-java-uuid/README.md b/core-java-modules/core-java-uuid/README.md
index 0a77c36acdc4..bd7bd9d9daac 100644
--- a/core-java-modules/core-java-uuid/README.md
+++ b/core-java-modules/core-java-uuid/README.md
@@ -4,3 +4,5 @@
- [Generating Alphanumeric UUID String in Java](https://www.baeldung.com/java-generate-alphanumeric-uuid)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Validate UUID String in Java](https://www.baeldung.com/java-validate-uuid-string)
+- [Generate the Same UUID From a String in Java](https://www.baeldung.com/java-generate-same-uuid-from-string)
+- [Generating Time Based UUIDs](https://www.baeldung.com/java-generating-time-based-uuids)
diff --git a/core-java-modules/core-java-uuid/pom.xml b/core-java-modules/core-java-uuid/pom.xml
index 7d851292f52f..c0e93c1d32b8 100644
--- a/core-java-modules/core-java-uuid/pom.xml
+++ b/core-java-modules/core-java-uuid/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-uuid
- 0.1.0-SNAPSHOT
core-java-uuid
jar
@@ -25,6 +24,21 @@
log4j-over-slf4j
${org.slf4j.version}
+
+ com.github.f4b6a3
+ uuid-creator
+ 5.2.0
+
+
+ com.fasterxml.uuid
+ java-uuid-generator
+ 4.1.0
+
+
+ com.github.f4b6a3
+ tsid-creator
+ 5.2.3
+
@@ -143,4 +157,4 @@
3.0.0-M1
-
\ No newline at end of file
+
diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/timebaseduuid/JavaUUIDCreatorBenchmark.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/timebaseduuid/JavaUUIDCreatorBenchmark.java
new file mode 100644
index 000000000000..20b2c127bd6d
--- /dev/null
+++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/timebaseduuid/JavaUUIDCreatorBenchmark.java
@@ -0,0 +1,42 @@
+package com.baeldung.timebaseduuid;
+
+import com.fasterxml.uuid.Generators;
+
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+public class JavaUUIDCreatorBenchmark {
+
+public static void main(String[] args) throws InterruptedException {
+
+ int threadCount = 128;
+ int iterationCount = 100_000;
+ Map uuidMap = new ConcurrentHashMap<>();
+ AtomicLong collisionCount = new AtomicLong();
+ long startNanos = System.nanoTime();
+ CountDownLatch endLatch = new CountDownLatch(threadCount);
+
+ for (long i = 0; i < threadCount; i++) {
+ long threadId = i;
+ new Thread(() -> {
+ for (long j = 0; j < iterationCount; j++) {
+ UUID uuid = Generators.timeBasedGenerator().generate();
+ Long existingUUID = uuidMap.put(uuid, (threadId * iterationCount) + j);
+ if(existingUUID != null) {
+ collisionCount.incrementAndGet();
+ }
+ }
+ endLatch.countDown();
+ }).start();
+ }
+
+ endLatch.await();
+ System.out.println(threadCount * iterationCount + " UUIDs generated, " + collisionCount + " collisions in "
+ + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos) + "ms");
+}
+}
+
diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/timebaseduuid/JavaUUIDCreatorExample.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/timebaseduuid/JavaUUIDCreatorExample.java
new file mode 100644
index 000000000000..b59d7e236a4e
--- /dev/null
+++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/timebaseduuid/JavaUUIDCreatorExample.java
@@ -0,0 +1,13 @@
+package com.baeldung.timebaseduuid;
+
+import com.fasterxml.uuid.Generators;
+
+public class JavaUUIDCreatorExample {
+
+ public static void main(String[] args) {
+ System.out.println("UUID Version 1: " + Generators.timeBasedGenerator().generate());
+ System.out.println("UUID Version 6: " + Generators.timeBasedReorderedGenerator().generate());
+ System.out.println("UUID Version 7: " + Generators.timeBasedEpochGenerator().generate());
+
+ }
+}
diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/timebaseduuid/UUIDCreatorBenchmark.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/timebaseduuid/UUIDCreatorBenchmark.java
new file mode 100644
index 000000000000..d93cd73a25c1
--- /dev/null
+++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/timebaseduuid/UUIDCreatorBenchmark.java
@@ -0,0 +1,42 @@
+package com.baeldung.timebaseduuid;
+
+import com.github.f4b6a3.uuid.UuidCreator;
+
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+public class UUIDCreatorBenchmark {
+
+ public static void main(String[] args) throws InterruptedException {
+
+ int threadCount = 128;
+ int iterationCount = 100_000;
+ Map uuidMap = new ConcurrentHashMap<>();
+ AtomicLong collisionCount = new AtomicLong();
+ long startNanos = System.nanoTime();
+ CountDownLatch endLatch = new CountDownLatch(threadCount);
+
+ for (long i = 0; i < threadCount; i++) {
+ long threadId = i;
+ new Thread(() -> {
+ for (long j = 0; j < iterationCount; j++) {
+ UUID uuid = UuidCreator.getTimeBased();
+ Long existingUUID = uuidMap.put(uuid, (threadId * iterationCount) + j);
+ if(existingUUID != null) {
+ collisionCount.incrementAndGet();
+ }
+ }
+ endLatch.countDown();
+ }).start();
+ }
+
+ endLatch.await();
+ System.out.println(threadCount * iterationCount + " UUIDs generated, " + collisionCount + " collisions in "
+ + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos) + "ms");
+ }
+}
diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/timebaseduuid/UUIDCreatorExample.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/timebaseduuid/UUIDCreatorExample.java
new file mode 100644
index 000000000000..fad2f55c931d
--- /dev/null
+++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/timebaseduuid/UUIDCreatorExample.java
@@ -0,0 +1,13 @@
+package com.baeldung.timebaseduuid;
+
+import com.github.f4b6a3.uuid.UuidCreator;
+
+public class UUIDCreatorExample {
+
+ public static void main(String[] args) {
+ System.out.println("UUID Version 1: " + UuidCreator.getTimeBased());
+ System.out.println("UUID Version 6: " + UuidCreator.getTimeOrdered());
+ System.out.println("UUID Version 7: " + UuidCreator.getTimeOrderedEpoch());
+ }
+}
+
diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDFromStringUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDFromStringUnitTest.java
new file mode 100644
index 000000000000..381d8715d58d
--- /dev/null
+++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDFromStringUnitTest.java
@@ -0,0 +1,62 @@
+package com.baeldung.uuid;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.UUID;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class UUIDFromStringUnitTest {
+ @Test
+ void whenStringInUUIDFormat_thenFromStringWorks() {
+ String inputStr = "bbcc4621-d88f-4a94-ae2f-b38072bf5087";
+
+ UUID uuid = UUID.fromString(inputStr);
+ UUID uuid2 = UUID.fromString(inputStr);
+ UUID uuid3 = UUID.fromString(inputStr);
+
+ assertEquals(inputStr, uuid.toString());
+
+ assertEquals(uuid, uuid2);
+ assertEquals(uuid, uuid3);
+
+ }
+
+ @Test
+ void whenStringNotInUUIDFormat_thenFromStringRaisesException() {
+ String inputStr = "I am not a standard UUID representation.";
+ assertThrows(IllegalArgumentException.class, () -> UUID.fromString(inputStr));
+ }
+
+ @Test
+ void whenStringInFreeFormat_thenNameUUIDFromBytesWorks() {
+ String inputStr = "I am not a standard UUID representation.";
+
+ UUID uuid = UUID.nameUUIDFromBytes(inputStr.getBytes());
+ UUID uuid2 = UUID.nameUUIDFromBytes(inputStr.getBytes());
+ UUID uuid3 = UUID.nameUUIDFromBytes(inputStr.getBytes());
+
+ assertTrue(uuid != null);
+
+ assertEquals(uuid, uuid2);
+ assertEquals(uuid, uuid3);
+
+ assertEquals(3, uuid.version());
+ }
+
+ @Test
+ void whenStringInFreeFormat_thenGenerateVer5UUIDWorks() {
+ String inputStr = "I am not a standard UUID representation.";
+
+ UUID uuid = UUIDGenerator.generateType5UUID(inputStr);
+ UUID uuid2 = UUIDGenerator.generateType5UUID(inputStr);
+ UUID uuid3 = UUIDGenerator.generateType5UUID(inputStr);
+
+ assertEquals(5, uuid.version());
+
+ assertTrue(uuid != null);
+
+ assertEquals(uuid, uuid2);
+ assertEquals(uuid, uuid3);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java/.gitignore b/core-java-modules/core-java/.gitignore
deleted file mode 100644
index 374c8bf907ed..000000000000
--- a/core-java-modules/core-java/.gitignore
+++ /dev/null
@@ -1,25 +0,0 @@
-*.class
-
-0.*
-
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-.resourceCache
-
-# Packaged files #
-*.jar
-*.war
-*.ear
-
-# Files generated by integration tests
-backup-pom.xml
-/bin/
-/temp
-
-#IntelliJ specific
-.idea/
-*.iml
\ No newline at end of file
diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md
deleted file mode 100644
index 087c5d356ee8..000000000000
--- a/core-java-modules/core-java/README.md
+++ /dev/null
@@ -1,11 +0,0 @@
-## Core Java Cookbooks and Examples
-
-### Relevant Articles:
-
-- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
-- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
-- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
-- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
-- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
-- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
-- [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error)
diff --git a/core-java-modules/core-java/customers.xml b/core-java-modules/core-java/customers.xml
deleted file mode 100644
index b52dc2763356..000000000000
--- a/core-java-modules/core-java/customers.xml
+++ /dev/null
@@ -1,95 +0,0 @@
-
-
-
- SELECT * FROM customers
- 1008
-
- true
- 1000
- 0
- 2
-
-
-
- 0
- 0
- 0
- true
- ResultSet.TYPE_SCROLL_INSENSITIVE
- false
- customers
- jdbc:h2:mem:testdb
-
- com.sun.rowset.providers.RIOptimisticProvider
- Oracle Corporation
- 1.0
- 2
- 1
-
-
-
- 2
-
- 1
- false
- true
- false
- 0
- true
- true
- 11
- ID
- ID
- PUBLIC
- 10
- 0
- CUSTOMERS
- TESTDB
- 4
- INTEGER
-
-
- 2
- false
- true
- false
- 0
- true
- true
- 50
- NAME
- NAME
- PUBLIC
- 50
- 0
- CUSTOMERS
- TESTDB
- 12
- VARCHAR
-
-
-
-
- 1
- Customer1
-
-
- 2
- Customer2
-
-
- 3
- Customer3
-
-
- 4
- Customer4
-
-
- 5
- Customer5
-
-
-
diff --git a/core-java-modules/core-java/externalizable.txt b/core-java-modules/core-java/externalizable.txt
deleted file mode 100644
index ddd3e143a8fd..000000000000
Binary files a/core-java-modules/core-java/externalizable.txt and /dev/null differ
diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml
deleted file mode 100644
index 87abe6c007a8..000000000000
--- a/core-java-modules/core-java/pom.xml
+++ /dev/null
@@ -1,199 +0,0 @@
-
-
- 4.0.0
- core-java
- 0.1.0-SNAPSHOT
- core-java
- jar
-
-
- com.baeldung.core-java-modules
- core-java-modules
- 0.0.1-SNAPSHOT
-
-
-
-
- org.unix4j
- unix4j-command
- ${unix4j.version}
-
-
- com.googlecode.grep4j
- grep4j
- ${grep4j.version}
-
-
-
-
- com.fasterxml.jackson.core
- jackson-databind
- ${jackson.version}
-
-
-
- log4j
- log4j
- ${log4j.version}
-
-
- org.slf4j
- log4j-over-slf4j
- ${org.slf4j.version}
-
-
- org.projectlombok
- lombok
- ${lombok.version}
- provided
-
-
- org.javamoney
- moneta
- ${javamoney.moneta.version}
-
-
- org.springframework
- spring-core
- ${spring.core.version}
-
-
- commons-io
- commons-io
- ${commons-io.version}
-
-
- com.google.gdata
- core
- ${gdata.version}
-
-
-
-
- core-java
-
-
- src/main/resources
- true
-
-
-
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
- copy-dependencies
- prepare-package
-
- copy-dependencies
-
-
- ${project.build.directory}/libs
-
-
-
-
-
- org.codehaus.mojo
- exec-maven-plugin
-
- java
- com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
-
- -Xmx300m
- -XX:+UseParallelGC
- -classpath
-
- com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
-
-
-
-
- org.apache.maven.plugins
- maven-javadoc-plugin
- ${maven-javadoc-plugin.version}
-
-
- ${target.version}
-
-
-
-
-
-
-
- integration
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- integration-test
-
- test
-
-
-
- **/*ManualTest.java
-
-
- **/*IntegrationTest.java
- **/*IntTest.java
-
-
-
-
-
-
- json
-
-
-
-
- org.codehaus.mojo
- exec-maven-plugin
-
-
- run-benchmarks
-
- none
-
- exec
-
-
- test
- java
-
- -classpath
-
- org.openjdk.jmh.Main
- .*
-
-
-
-
-
-
-
-
-
-
-
-
- 0.4
- 1.8.7
-
- 1.1
- 3.0.0-M1
- 1.8
- 1.8
- 4.3.20.RELEASE
- 1.47.1
-
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/.gitignore b/core-java-modules/core-java/src/main/java/com/baeldung/.gitignore
deleted file mode 100644
index 83c05e60c802..000000000000
--- a/core-java-modules/core-java/src/main/java/com/baeldung/.gitignore
+++ /dev/null
@@ -1,13 +0,0 @@
-*.class
-
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-
-# Packaged files #
-*.jar
-*.war
-*.ear
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java b/core-java-modules/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java
deleted file mode 100644
index 6c79e897175e..000000000000
--- a/core-java-modules/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.baeldung.executable;
-
-import javax.swing.JOptionPane;
-
-public class ExecutableMavenJar {
-
- public static void main(String[] args) {
- JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
- }
-
-}
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java b/core-java-modules/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java
deleted file mode 100644
index 7e6bb5d3b21a..000000000000
--- a/core-java-modules/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.baeldung.filesystem.jndi;
-
-import java.io.File;
-import java.util.Hashtable;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-public class LookupFSJNDI {
- private InitialContext ctx = null;
-
- public LookupFSJNDI() throws NamingException {
- super();
- init();
- }
-
- private void init() throws NamingException {
- Hashtable env = new Hashtable();
-
- env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
- // URI to namespace (actual directory)
- env.put(Context.PROVIDER_URL, "file:./src/test/resources");
-
- ctx = new InitialContext(env);
- }
-
- public InitialContext getCtx() {
- return ctx;
- }
-
- public File getFile(String fileName) {
- File file;
- try {
- file = (File) getCtx().lookup(fileName);
- } catch (NamingException e) {
- file = null;
- }
- return file;
- }
-
-}
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/jsonposturlconnection/PostJSONWithHttpURLConnection.java b/core-java-modules/core-java/src/main/java/com/baeldung/jsonposturlconnection/PostJSONWithHttpURLConnection.java
deleted file mode 100644
index b2469ac98469..000000000000
--- a/core-java-modules/core-java/src/main/java/com/baeldung/jsonposturlconnection/PostJSONWithHttpURLConnection.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.baeldung.jsonposturlconnection;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.net.HttpURLConnection;
-import java.net.URL;
-
-public class PostJSONWithHttpURLConnection {
-
- public static void main (String []args) throws IOException{
- //Change the URL with any other publicly accessible POST resource, which accepts JSON request body
- URL url = new URL ("https://reqres.in/api/users");
-
- HttpURLConnection con = (HttpURLConnection)url.openConnection();
- con.setRequestMethod("POST");
-
- con.setRequestProperty("Content-Type", "application/json; utf-8");
- con.setRequestProperty("Accept", "application/json");
-
- con.setDoOutput(true);
-
- //JSON String need to be constructed for the specific resource.
- //We may construct complex JSON using any third-party JSON libraries such as jackson or org.json
- String jsonInputString = "{\"name\": \"Upendra\", \"job\": \"Programmer\"}";
-
- try(OutputStream os = con.getOutputStream()){
- byte[] input = jsonInputString.getBytes("utf-8");
- os.write(input, 0, input.length);
- }
-
- int code = con.getResponseCode();
- System.out.println(code);
-
- try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
- StringBuilder response = new StringBuilder();
- String responseLine = null;
- while ((responseLine = br.readLine()) != null) {
- response.append(responseLine.trim());
- }
- System.out.println(response.toString());
- }
- }
-
-}
diff --git a/core-java-modules/core-java/src/main/java/log4j.properties b/core-java-modules/core-java/src/main/java/log4j.properties
deleted file mode 100644
index 5fe42d854c77..000000000000
--- a/core-java-modules/core-java/src/main/java/log4j.properties
+++ /dev/null
@@ -1,9 +0,0 @@
-# Set root logger level to DEBUG and its only appender to A1.
-log4j.rootLogger=DEBUG, A1
-
-# A1 is set to be a ConsoleAppender.
-log4j.appender.A1=org.apache.log4j.ConsoleAppender
-
-# A1 uses PatternLayout.
-log4j.appender.A1.layout=org.apache.log4j.PatternLayout
-log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
diff --git a/core-java-modules/core-java/src/main/resources/META-INF/BenchmarkList b/core-java-modules/core-java/src/main/resources/META-INF/BenchmarkList
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/core-java-modules/core-java/src/main/resources/META-INF/MANIFEST.MF b/core-java-modules/core-java/src/main/resources/META-INF/MANIFEST.MF
deleted file mode 100644
index 988de3193dcf..000000000000
--- a/core-java-modules/core-java/src/main/resources/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,5 +0,0 @@
-Agent-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
-Can-Redefine-Classes: true
-Can-Retransform-Classes: true
-Premain-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
-Main-Class: com.baeldung.instrumentation.application.Launcher
diff --git a/core-java-modules/core-java/src/main/resources/META-INF/persistence.xml b/core-java-modules/core-java/src/main/resources/META-INF/persistence.xml
deleted file mode 100644
index 3966afdcdac7..000000000000
--- a/core-java-modules/core-java/src/main/resources/META-INF/persistence.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/core-java-modules/core-java/src/main/resources/countries.properties b/core-java-modules/core-java/src/main/resources/countries.properties
deleted file mode 100644
index 50b5e8565399..000000000000
--- a/core-java-modules/core-java/src/main/resources/countries.properties
+++ /dev/null
@@ -1,3 +0,0 @@
-UK
-US
-Germany
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/resources/datasource.properties b/core-java-modules/core-java/src/main/resources/datasource.properties
deleted file mode 100644
index 61df0d45f790..000000000000
--- a/core-java-modules/core-java/src/main/resources/datasource.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-dataSourceClassName=//TBD
-dataSource.user=//TBD
-dataSource.password=//TBD
-dataSource.databaseName=//TBD
-dataSource.portNumber=//TBD
-dataSource.serverName=//TBD
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/resources/log4j.properties b/core-java-modules/core-java/src/main/resources/log4j.properties
deleted file mode 100644
index 621cf017354f..000000000000
--- a/core-java-modules/core-java/src/main/resources/log4j.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-log4j.rootLogger=DEBUG, A1
-
-log4j.appender.A1=org.apache.log4j.ConsoleAppender
-
-log4j.appender.A1.layout=org.apache.log4j.PatternLayout
-log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/resources/log4j2.xml b/core-java-modules/core-java/src/main/resources/log4j2.xml
deleted file mode 100644
index a824bef9b056..000000000000
--- a/core-java-modules/core-java/src/main/resources/log4j2.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/resources/log4jstructuraldp.properties b/core-java-modules/core-java/src/main/resources/log4jstructuraldp.properties
deleted file mode 100644
index 5bc2bfe4b9ee..000000000000
--- a/core-java-modules/core-java/src/main/resources/log4jstructuraldp.properties
+++ /dev/null
@@ -1,9 +0,0 @@
-
-# Root logger
-log4j.rootLogger=INFO, file, stdout
-
-# Write to console
-log4j.appender.stdout=org.apache.log4j.ConsoleAppender
-log4j.appender.stdout.Target=System.out
-log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
-log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/resources/product.png b/core-java-modules/core-java/src/main/resources/product.png
deleted file mode 100644
index 4edd01c0a179..000000000000
Binary files a/core-java-modules/core-java/src/main/resources/product.png and /dev/null differ
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/arrays/ArraysJoinAndSplitJUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/arrays/ArraysJoinAndSplitJUnitTest.java
deleted file mode 100644
index b31a829f3415..000000000000
--- a/core-java-modules/core-java/src/test/java/com/baeldung/arrays/ArraysJoinAndSplitJUnitTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.baeldung.arrays;
-
-import java.util.Arrays;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class ArraysJoinAndSplitJUnitTest {
-
- private final String[] sauces = { "Marinara", "Olive Oil" };
- private final String[] cheeses = { "Mozzarella", "Feta", "Parmesan" };
- private final String[] vegetables = { "Olives", "Spinach", "Green Peppers" };
-
- private final String[] customers = { "Jay", "Harry", "Ronnie", "Gary", "Ross" };
-
- @Test
- public void givenThreeStringArrays_whenJoiningIntoOneStringArray_shouldSucceed() {
- String[] toppings = new String[sauces.length + cheeses.length + vegetables.length];
-
- System.arraycopy(sauces, 0, toppings, 0, sauces.length);
- int AddedSoFar = sauces.length;
-
- System.arraycopy(cheeses, 0, toppings, AddedSoFar, cheeses.length);
- AddedSoFar += cheeses.length;
-
- System.arraycopy(vegetables, 0, toppings, AddedSoFar, vegetables.length);
-
- Assert.assertArrayEquals(toppings, new String[] { "Marinara", "Olive Oil", "Mozzarella", "Feta", "Parmesan", "Olives", "Spinach", "Green Peppers" });
- }
-
- @Test
- public void givenOneStringArray_whenSplittingInHalfTwoStringArrays_shouldSucceed() {
- int ordersHalved = (customers.length / 2) + (customers.length % 2);
-
- String[] driverOne = Arrays.copyOf(customers, ordersHalved);
- String[] driverTwo = Arrays.copyOfRange(customers, ordersHalved, customers.length);
-
- Assert.assertArrayEquals(driverOne, new String[] { "Jay", "Harry", "Ronnie" });
- Assert.assertArrayEquals(driverTwo, new String[] { "Gary", "Ross" });
- }
-}
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/stringisnumeric.zip b/core-java-modules/core-java/src/test/java/com/baeldung/stringisnumeric.zip
deleted file mode 100644
index b8a7b9b35a09..000000000000
Binary files a/core-java-modules/core-java/src/test/java/com/baeldung/stringisnumeric.zip and /dev/null differ
diff --git a/core-java-modules/core-java/src/test/resources/.gitignore b/core-java-modules/core-java/src/test/resources/.gitignore
deleted file mode 100644
index 83c05e60c802..000000000000
--- a/core-java-modules/core-java/src/test/resources/.gitignore
+++ /dev/null
@@ -1,13 +0,0 @@
-*.class
-
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-
-# Packaged files #
-*.jar
-*.war
-*.ear
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/newFile1.txt b/core-java-modules/core-java/src/test/resources/newFile1.txt
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/core-java-modules/core-java/src/test/resources/newFile2.txt b/core-java-modules/core-java/src/test/resources/newFile2.txt
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/core-java-modules/core-java/src/test/resources/newFile3.txt b/core-java-modules/core-java/src/test/resources/newFile3.txt
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/core-java-modules/core-java/src/test/resources/original.txt b/core-java-modules/core-java/src/test/resources/original.txt
deleted file mode 100644
index 8511f56bef6f..000000000000
--- a/core-java-modules/core-java/src/test/resources/original.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-#Copy a File with Java (www.Baeldung.com)
-Copying Files with Java is Fun!
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/sourceFile.txt b/core-java-modules/core-java/src/test/resources/sourceFile.txt
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/core-java-modules/core-java/src/test/resources/test.find b/core-java-modules/core-java/src/test/resources/test.find
deleted file mode 100644
index 0cb7d51df198..000000000000
--- a/core-java-modules/core-java/src/test/resources/test.find
+++ /dev/null
@@ -1 +0,0 @@
-Test of JNDI on file.
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read.in b/core-java-modules/core-java/src/test/resources/test_read.in
deleted file mode 100644
index 70c379b63ffa..000000000000
--- a/core-java-modules/core-java/src/test/resources/test_read.in
+++ /dev/null
@@ -1 +0,0 @@
-Hello world
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read1.in b/core-java-modules/core-java/src/test/resources/test_read1.in
deleted file mode 100644
index 1e462429938a..000000000000
--- a/core-java-modules/core-java/src/test/resources/test_read1.in
+++ /dev/null
@@ -1 +0,0 @@
-Hello world 1
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read2.in b/core-java-modules/core-java/src/test/resources/test_read2.in
deleted file mode 100644
index fe47dc003bc6..000000000000
--- a/core-java-modules/core-java/src/test/resources/test_read2.in
+++ /dev/null
@@ -1 +0,0 @@
-2,3 4
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read3.in b/core-java-modules/core-java/src/test/resources/test_read3.in
deleted file mode 100644
index db9f25a672f5..000000000000
--- a/core-java-modules/core-java/src/test/resources/test_read3.in
+++ /dev/null
@@ -1 +0,0 @@
-Hello 1
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read4.in b/core-java-modules/core-java/src/test/resources/test_read4.in
deleted file mode 100644
index 5727d54bfcb2..000000000000
Binary files a/core-java-modules/core-java/src/test/resources/test_read4.in and /dev/null differ
diff --git a/core-java-modules/core-java/src/test/resources/test_read7.in b/core-java-modules/core-java/src/test/resources/test_read7.in
deleted file mode 100644
index 28d4d45d4341..000000000000
--- a/core-java-modules/core-java/src/test/resources/test_read7.in
+++ /dev/null
@@ -1 +0,0 @@
-青空
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read8.in b/core-java-modules/core-java/src/test/resources/test_read8.in
deleted file mode 100644
index 10fc1aac8ab2..000000000000
--- a/core-java-modules/core-java/src/test/resources/test_read8.in
+++ /dev/null
@@ -1,2 +0,0 @@
-Hello world
- Test line
diff --git a/core-java-modules/core-java/src/test/resources/test_read_d.in b/core-java-modules/core-java/src/test/resources/test_read_d.in
deleted file mode 100644
index 82bbb4071f80..000000000000
--- a/core-java-modules/core-java/src/test/resources/test_read_d.in
+++ /dev/null
@@ -1 +0,0 @@
-John,Adam-Tom
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read_multiple.in b/core-java-modules/core-java/src/test/resources/test_read_multiple.in
deleted file mode 100644
index 7d64000a76dd..000000000000
--- a/core-java-modules/core-java/src/test/resources/test_read_multiple.in
+++ /dev/null
@@ -1,2 +0,0 @@
-Hello world
-Hi, John
\ No newline at end of file
diff --git a/core-java-modules/core-java/yofile.txt b/core-java-modules/core-java/yofile.txt
deleted file mode 100644
index ad56bf35f7a6..000000000000
Binary files a/core-java-modules/core-java/yofile.txt and /dev/null differ
diff --git a/core-java-modules/core-java/yofile2.txt b/core-java-modules/core-java/yofile2.txt
deleted file mode 100644
index 8393b6e98bc3..000000000000
Binary files a/core-java-modules/core-java/yofile2.txt and /dev/null differ
diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml
index e7894b2f4549..b872eef49114 100644
--- a/core-java-modules/pom.xml
+++ b/core-java-modules/pom.xml
@@ -16,20 +16,19 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
core-java-annotations
core-java-arrays-sorting
@@ -53,6 +52,7 @@
core-java-collections-maps
core-java-collections-maps-2
core-java-collections-maps-3
+ core-java-compiler
core-java-concurrency-2
core-java-concurrency-advanced
core-java-concurrency-advanced-2
@@ -67,6 +67,7 @@
core-java-datetime-string-2
core-java-date-operations-2
core-java-date-operations-3
+ core-java-documentation
core-java-exceptions
core-java-exceptions-2
core-java-exceptions-3
@@ -106,6 +107,7 @@
core-java-lang-operators-2
core-java-lang-syntax
core-java-lang-syntax-2
+ core-java-locale
core-java-networking
core-java-networking-2
core-java-networking-4
@@ -115,8 +117,10 @@
core-java-numbers-3
core-java-numbers-4
core-java-numbers-5
+ core-java-numbers-6
core-java-optional
core-java-perf
+ core-java-properties
core-java-reflection
core-java-reflection-2
core-java-security-2
@@ -130,6 +134,7 @@
core-java-string-apis-2
core-java-string-conversions
core-java-string-conversions-2
+ core-java-string-conversions-3
core-java-string-operations
core-java-string-operations-2
core-java-regex
@@ -137,6 +142,7 @@
core-java-uuid
pre-jpms
core-java-collections-maps-6
+ core-java-records
diff --git a/core-java-modules/pre-jpms/pom.xml b/core-java-modules/pre-jpms/pom.xml
index 11db8f802788..67bc9137679d 100644
--- a/core-java-modules/pre-jpms/pom.xml
+++ b/core-java-modules/pre-jpms/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
pre-jpms
- 0.0.1-SNAPSHOT
pre-jpms
jar
diff --git a/couchbase/pom.xml b/couchbase/pom.xml
index 095bda3610cb..823b33ee29dc 100644
--- a/couchbase/pom.xml
+++ b/couchbase/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
couchbase
- 0.1-SNAPSHOT
couchbase
jar
Couchbase Tutorials
diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml
index 38a5e304040e..8097d4fefafd 100644
--- a/custom-pmd/pom.xml
+++ b/custom-pmd/pom.xml
@@ -8,7 +8,6 @@
0.0.1
custom-pmd
jar
- http://maven.apache.org
com.baeldung
diff --git a/data-structures/pom.xml b/data-structures/pom.xml
index cba602878f28..aeadfcefc36b 100644
--- a/data-structures/pom.xml
+++ b/data-structures/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
data-structures
- 0.0.1-SNAPSHOT
data-structures
@@ -13,13 +12,6 @@
1.0.0-SNAPSHOT
-
-
- github.release.repo
- https://raw.github.com/bulldog2011/bulldog-repo/master/repo/releases/
-
-
-
com.leansoft
@@ -39,6 +31,13 @@
+
+
+ github.release.repo
+ https://raw.github.com/bulldog2011/bulldog-repo/master/repo/releases/
+
+
+
0.7.0
diff --git a/ddd/pom.xml b/ddd/pom.xml
index 6128bb1cd957..443b2b5148e0 100644
--- a/ddd/pom.xml
+++ b/ddd/pom.xml
@@ -3,7 +3,6 @@
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">
4.0.0
- com.baeldung.ddd
ddd
ddd
jar
diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml
index 01bac93214dd..875d8cdf85b4 100644
--- a/deeplearning4j/pom.xml
+++ b/deeplearning4j/pom.xml
@@ -3,9 +3,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
- com.baeldung.deeplearning4j
deeplearning4j
- 1.0-SNAPSHOT
deeplearning4j
jar
diff --git a/dependency-exclusion/core-java-exclusions/pom.xml b/dependency-exclusion/core-java-exclusions/pom.xml
deleted file mode 100644
index cf1b36656d9a..000000000000
--- a/dependency-exclusion/core-java-exclusions/pom.xml
+++ /dev/null
@@ -1,53 +0,0 @@
-
-
- 4.0.0
- core-java-exclusions
- 0.0.0-SNAPSHOT
- core-java-exclusions
- jar
-
-
- com.baeldung.dependency-exclusion
- dependency-exclusion
- 0.0.1-SNAPSHOT
-
-
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${surefire-version}
-
- alphabetical
- 1
-
-
- junit
- false
-
-
-
-
-
-
- org.apache.maven.surefire
- surefire-junit47
- dummy
-
-
-
-
-
-
-
-
- junit
- junit
- test
-
-
-
-
diff --git a/dependency-exclusion/dummy-surefire-junit47/pom.xml b/dependency-exclusion/dummy-surefire-junit47/pom.xml
deleted file mode 100644
index 5859ddbe72f8..000000000000
--- a/dependency-exclusion/dummy-surefire-junit47/pom.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
- 4.0.0
- org.apache.maven.surefire
- surefire-junit47
- dummy
-
diff --git a/di-modules/guice/pom.xml b/di-modules/guice/pom.xml
index a28dbe529791..d0d2876fc8e5 100644
--- a/di-modules/guice/pom.xml
+++ b/di-modules/guice/pom.xml
@@ -3,7 +3,6 @@
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">
4.0.0
- com.baeldung.examples.guice
guice
guice
jar
diff --git a/disruptor/pom.xml b/disruptor/pom.xml
index c2f9cf34b0db..75e783e9354b 100644
--- a/disruptor/pom.xml
+++ b/disruptor/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
disruptor
- 0.1.0-SNAPSHOT
disruptor
jar
diff --git a/docker-modules/docker-caching/multi-module-caching/core/pom.xml b/docker-modules/docker-caching/multi-module-caching/core-module/pom.xml
similarity index 95%
rename from docker-modules/docker-caching/multi-module-caching/core/pom.xml
rename to docker-modules/docker-caching/multi-module-caching/core-module/pom.xml
index bcfc4b5783c3..159d76830bb8 100644
--- a/docker-modules/docker-caching/multi-module-caching/core/pom.xml
+++ b/docker-modules/docker-caching/multi-module-caching/core-module/pom.xml
@@ -3,7 +3,7 @@
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">
4.0.0
- core
+ core-module
multi-module-caching
diff --git a/docker-modules/docker-caching/multi-module-caching/core/src/main/java/com/baeldung/maven_caching/CoreClass.java b/docker-modules/docker-caching/multi-module-caching/core-module/src/main/java/com/baeldung/maven_caching/CoreClass.java
similarity index 100%
rename from docker-modules/docker-caching/multi-module-caching/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
rename to docker-modules/docker-caching/multi-module-caching/core-module/src/main/java/com/baeldung/maven_caching/CoreClass.java
diff --git a/docker-modules/docker-caching/multi-module-caching/pom.xml b/docker-modules/docker-caching/multi-module-caching/pom.xml
index 94a370453c7e..b64cf1a8b8dc 100644
--- a/docker-modules/docker-caching/multi-module-caching/pom.xml
+++ b/docker-modules/docker-caching/multi-module-caching/pom.xml
@@ -1,7 +1,7 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.baeldung
multi-module-caching
@@ -10,8 +10,8 @@
pom
- runner
- core
+ runner-module
+ core-module
diff --git a/docker-modules/docker-caching/multi-module-caching/runner/pom.xml b/docker-modules/docker-caching/multi-module-caching/runner-module/pom.xml
similarity index 95%
rename from docker-modules/docker-caching/multi-module-caching/runner/pom.xml
rename to docker-modules/docker-caching/multi-module-caching/runner-module/pom.xml
index e3f234bac07b..e60870686418 100644
--- a/docker-modules/docker-caching/multi-module-caching/runner/pom.xml
+++ b/docker-modules/docker-caching/multi-module-caching/runner-module/pom.xml
@@ -3,7 +3,7 @@
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">
4.0.0
- runner
+ runner-module
multi-module-caching
@@ -14,7 +14,7 @@
com.baeldung
- core
+ core-module
0.0.1-SNAPSHOT
diff --git a/docker-modules/docker-caching/multi-module-caching/runner/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java b/docker-modules/docker-caching/multi-module-caching/runner-module/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
similarity index 100%
rename from docker-modules/docker-caching/multi-module-caching/runner/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
rename to docker-modules/docker-caching/multi-module-caching/runner-module/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
diff --git a/docker-modules/docker-caching/single-module-caching/pom.xml b/docker-modules/docker-caching/single-module-caching/pom.xml
index 4a4e53f1d346..a388c7563f61 100644
--- a/docker-modules/docker-caching/single-module-caching/pom.xml
+++ b/docker-modules/docker-caching/single-module-caching/pom.xml
@@ -1,7 +1,7 @@
+ 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">
4.0.0
com.baeldung
single-module-caching
diff --git a/docker-modules/docker-compose-2/pom.xml b/docker-modules/docker-compose-2/pom.xml
index 851742309d66..3a94ee3901c6 100644
--- a/docker-modules/docker-compose-2/pom.xml
+++ b/docker-modules/docker-compose-2/pom.xml
@@ -1,7 +1,7 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
docker-compose-2
Demo project for Spring Boot and Docker - Module docker-compose-2
diff --git a/docker-modules/docker-containers/pom.xml b/docker-modules/docker-containers/pom.xml
index 42c2d403e4a4..79bf0aee722d 100644
--- a/docker-modules/docker-containers/pom.xml
+++ b/docker-modules/docker-containers/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.docker
docker-containers
- 0.0.1-SNAPSHOT
Demo project for Spring Boot
diff --git a/docker-modules/pom.xml b/docker-modules/pom.xml
index 1a87fa5d1c9e..b4c5240718d2 100644
--- a/docker-modules/pom.xml
+++ b/docker-modules/pom.xml
@@ -3,9 +3,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.baeldung
docker-modules
- 1.0.0-SNAPSHOT
docker-modules
pom
diff --git a/dozer/pom.xml b/dozer/pom.xml
index 840763445c44..66f4ee8227a1 100644
--- a/dozer/pom.xml
+++ b/dozer/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
dozer
- 1.0
dozer
diff --git a/ethereum/pom.xml b/ethereum/pom.xml
index 6c1a0e900f83..8dc25427d9f8 100644
--- a/ethereum/pom.xml
+++ b/ethereum/pom.xml
@@ -1,7 +1,7 @@
+ 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">
4.0.0
com.baeldung.ethereum
ethereum
@@ -113,7 +113,8 @@
test
${spring.boot.version}
-
+
junit
junit
@@ -195,4 +196,5 @@
2.0.4.RELEASE
3.1
+
\ No newline at end of file
diff --git a/feign/pom.xml b/feign/pom.xml
index 7f71794e291b..edb55e7da5f0 100644
--- a/feign/pom.xml
+++ b/feign/pom.xml
@@ -3,7 +3,6 @@
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">
4.0.0
- com.baeldung.feign
feign
feign
diff --git a/gcp-firebase/pom.xml b/gcp-firebase/pom.xml
index c563099ad6cf..10a899f37030 100644
--- a/gcp-firebase/pom.xml
+++ b/gcp-firebase/pom.xml
@@ -1,48 +1,51 @@
-
- 4.0.0
+
+ 4.0.0
+ gcp-firebase
+
com.baeldung
parent-boot-2
0.0.1-SNAPSHOT
../parent-boot-2
- gcp-firebase
-
-
- 9.1.1
-
-
-
- com.google.firebase
- firebase-admin
- ${firebase-admin.version}
-
-
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
- org.springframework.boot
- spring-boot-starter-test
- test
-
-
- org.springframework.boot
- spring-boot-configuration-processor
- true
-
-
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
+
+
+ com.google.firebase
+ firebase-admin
+ ${firebase-admin.version}
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.springframework.boot
+ spring-boot-configuration-processor
+ true
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
+ 9.1.1
+
+
\ No newline at end of file
diff --git a/gcp-firebase/src/main/resources/firebase-service-account.json b/gcp-firebase/src/main/resources/firebase-service-account.json
index ed5afa9f134e..cd87ff6bda42 100644
--- a/gcp-firebase/src/main/resources/firebase-service-account.json
+++ b/gcp-firebase/src/main/resources/firebase-service-account.json
@@ -1,10 +1,10 @@
{
"type": "service_account",
- "project_id": "tutorials-2cdfb",
- "private_key_id": "d9f6a684d6814f85ed2d0490585eb7bf590f983a",
- "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDdJWTeGT2eBFo+\nXxzT9xFJYPtyawTAj0K1rVUNlWNUwj3zszK6P2sAsrpI2Rz1klwQ9aDz9i3+Opxv\n7UZ3pOzur6S58JnoswtNs6BZ9P7oeggLJJC6MPjioxwh8jLLIGMgdVtC2/iPYW3r\nGzurWlwkM8M8DyCgNq7KKJcx44pGcyy16ZGCYiijuTEmK6R+WHJTTyICzRFu3Org\nuHGlZUs/G4E76p10HanoFX2AIS/fDEEMP2DXBB73yoCal5GuvMY9yZWxnvV65Y5z\nGveY3NDB9EESbO2AAhDvHekWT17uWhymtO5N3gM8da48J9d51tVzi0D/NIPZnF0u\nTS64uxK3AgMBAAECggEAYuEQa7oPcfLyQscWRbRH1250n2E4e7zSkBcTW4J7Km+7\ncZajTOGEP4iqgF4Lc8XgQnkBYXOmdvDP97+47VAh3EtOtRDeUEyV9kUlonNH8rx1\nkj3kNEwnTHav4oG/slEl4WJ3zro6NinTEvdXQ7OgVVOLrPP6m4g3uQ5TJCxgLEUI\nTd3Hs3cg3P71mzEqfBF4NmGVmC1ea5lXFELd6giJJMvL7g+O2w22/fquGWOrreAM\ncj/G2Xv9/vmzeb9yzbgGxqCJyY6vspmd90fQLUu7bxkEY5/PPc6Zk8qay4AdEn47\nkL6hnJiR8H1wMCzV2RTUKE7ospriNVdBilXgxm9IMQKBgQD1TmF0Bg85zvXmEKBa\nLBhbc3xTtM7DOgKs+pI12sYDKwgL/QKEI/TKkYXua0aVGiQWc2Bk2/0sYhO6aB2f\n6AN1ZUrf4PRM8c53jebChc7beVLSjWI8Tx+kE+0t8864OwvELYZUzP35oSx3RdJD\nE/CvqBM7NQfJwx2Mw2VJK/YRGQKBgQDmyWLm/IWitehkITw6xMQpkkFs2m4Joq3A\nJvAyri58TRkw/7rqWaIxb5Wcy/7BOvjDN8PZNTHh4ZvhQiHpn7NGUks2/ULnWxUB\nWAA9YbeO9PNHJfZ6PjD2FSvwOXHj+vVkWt2GCXT8pDGYM2ImqXon85Oe3OH/h+N5\nktO9taesTwKBgQCSdPGKK/P7N61oZpTWQW1pbFHWSCUKOiBO1mtk6/E9AvwS7EQM\nUMteBfRInJPPgYP6Q3hRv2YwkX3l1TOavRMTjB5f/BbfuZ7jkj0r9mfCcXUZcIAu\nMa9abus0fFP3eolT3zpMdvdLiwbZTz5x/f29YkPZHZhAxdVmrWJThYOsQQKBgBDu\nZVsc25D8V3hBF/IXzWxfVn1t6PS8ApM+SBDvxmlIHrkBiez3dna6APfn32C9utJX\nnP6qcGZp7s2v1F0XYkeecfYuzmG6xOe8VQgryxOp1M87ccG2HlFvbDHLhRd8qdQa\n9nWG7BY81Yac/m5nsJaNwB6/hbUBeybIJtCcKxjxAoGBAJ3y+QSFb4AYmxLFtmMA\nklOvlT+r70w4RV/z4SEO1gjWEh9IozNSXknl5Q/8Zh9IVm3+/qYap//IzEv9JUc3\nv4+HlpZu0trxTpvRWWjPqVr3ssxRdiFLC0LCLEk4rzqWLBVyzJm8uHVIF9Inv8PE\naudInvdbnfAWi60+1Wi8u0Co\n-----END PRIVATE KEY-----\n",
- "client_email": "firebase-adminsdk-2afzd@tutorials-2cdfb.iam.gserviceaccount.com",
- "client_id": "111111112074248894669",
+ "project_id": "REPLACE WITH VALID PROJECT ID",
+ "private_key_id": "REPLACE WITH VALID PRIVATE KEY ID",
+ "private_key": "REPLACE WITH VALID PRIVATE KEY",
+ "client_email": "REPLACE WITH VALID CLIENT EMAIL",
+ "client_id": "REPLACE WITH VALID CLIENT ID",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
diff --git a/geotools/pom.xml b/geotools/pom.xml
index f17b4cc5daba..61682ae0f526 100644
--- a/geotools/pom.xml
+++ b/geotools/pom.xml
@@ -4,10 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
geotools
- 0.0.1-SNAPSHOT
geotools
jar
- http://maven.apache.org
com.baeldung
@@ -15,14 +13,6 @@
1.0.0-SNAPSHOT
-
-
- osgeo-release
- OSGeo Repository
- https://repo.osgeo.org/repository/release/
-
-
-
org.geotools
@@ -41,6 +31,14 @@
+
+
+ osgeo-release
+ OSGeo Repository
+ https://repo.osgeo.org/repository/release/
+
+
+
28.1
28.1
diff --git a/code-generation/README.md b/google-auto-project/README.md
similarity index 100%
rename from code-generation/README.md
rename to google-auto-project/README.md
diff --git a/code-generation/pom.xml b/google-auto-project/pom.xml
similarity index 96%
rename from code-generation/pom.xml
rename to google-auto-project/pom.xml
index ed8890e1dd64..839ccabc5fa4 100644
--- a/code-generation/pom.xml
+++ b/google-auto-project/pom.xml
@@ -3,9 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
- code-generation
+ google-auto-project
1.0
- code-generation
+ google-auto-project
com.baeldung
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/App.java b/google-auto-project/src/main/java/com/baeldung/autofactory/App.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/App.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/App.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/CustomStorage.java b/google-auto-project/src/main/java/com/baeldung/autofactory/CustomStorage.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/CustomStorage.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/CustomStorage.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/custom/AbstractFactory.java b/google-auto-project/src/main/java/com/baeldung/autofactory/custom/AbstractFactory.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/custom/AbstractFactory.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/custom/AbstractFactory.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/custom/CustomPhone.java b/google-auto-project/src/main/java/com/baeldung/autofactory/custom/CustomPhone.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/custom/CustomPhone.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/custom/CustomPhone.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/custom/SmartPhone.java b/google-auto-project/src/main/java/com/baeldung/autofactory/custom/SmartPhone.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/custom/SmartPhone.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/custom/SmartPhone.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/model/Camera.java b/google-auto-project/src/main/java/com/baeldung/autofactory/model/Camera.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/model/Camera.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/model/Camera.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/model/ClassicPhone.java b/google-auto-project/src/main/java/com/baeldung/autofactory/model/ClassicPhone.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/model/ClassicPhone.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/model/ClassicPhone.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/model/Phone.java b/google-auto-project/src/main/java/com/baeldung/autofactory/model/Phone.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/model/Phone.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/model/Phone.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/modules/SonyCameraModule.java b/google-auto-project/src/main/java/com/baeldung/autofactory/modules/SonyCameraModule.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/modules/SonyCameraModule.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/modules/SonyCameraModule.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/provided/IntermediateAssembler.java b/google-auto-project/src/main/java/com/baeldung/autofactory/provided/IntermediateAssembler.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/provided/IntermediateAssembler.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/provided/IntermediateAssembler.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/provider/SonyCameraProvider.java b/google-auto-project/src/main/java/com/baeldung/autofactory/provider/SonyCameraProvider.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/provider/SonyCameraProvider.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/provider/SonyCameraProvider.java
diff --git a/code-generation/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java b/google-auto-project/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java
rename to google-auto-project/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java
diff --git a/code-generation/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java b/google-auto-project/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java
rename to google-auto-project/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java
diff --git a/code-generation/src/main/java/com/baeldung/autoservice/TranslationService.java b/google-auto-project/src/main/java/com/baeldung/autoservice/TranslationService.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autoservice/TranslationService.java
rename to google-auto-project/src/main/java/com/baeldung/autoservice/TranslationService.java
diff --git a/code-generation/src/main/java/com/baeldung/autovalue/AutoValueMoney.java b/google-auto-project/src/main/java/com/baeldung/autovalue/AutoValueMoney.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autovalue/AutoValueMoney.java
rename to google-auto-project/src/main/java/com/baeldung/autovalue/AutoValueMoney.java
diff --git a/code-generation/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java b/google-auto-project/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java
rename to google-auto-project/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java
diff --git a/code-generation/src/main/java/com/baeldung/autovalue/Foo.java b/google-auto-project/src/main/java/com/baeldung/autovalue/Foo.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autovalue/Foo.java
rename to google-auto-project/src/main/java/com/baeldung/autovalue/Foo.java
diff --git a/code-generation/src/main/java/com/baeldung/autovalue/ImmutableMoney.java b/google-auto-project/src/main/java/com/baeldung/autovalue/ImmutableMoney.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autovalue/ImmutableMoney.java
rename to google-auto-project/src/main/java/com/baeldung/autovalue/ImmutableMoney.java
diff --git a/code-generation/src/main/java/com/baeldung/autovalue/MutableMoney.java b/google-auto-project/src/main/java/com/baeldung/autovalue/MutableMoney.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autovalue/MutableMoney.java
rename to google-auto-project/src/main/java/com/baeldung/autovalue/MutableMoney.java
diff --git a/code-generation/src/main/java/com/baeldung/autovalue/Person.java b/google-auto-project/src/main/java/com/baeldung/autovalue/Person.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autovalue/Person.java
rename to google-auto-project/src/main/java/com/baeldung/autovalue/Person.java
diff --git a/code-generation/src/main/resources/logback.xml b/google-auto-project/src/main/resources/logback.xml
similarity index 100%
rename from code-generation/src/main/resources/logback.xml
rename to google-auto-project/src/main/resources/logback.xml
diff --git a/code-generation/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java b/google-auto-project/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java
similarity index 100%
rename from code-generation/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java
rename to google-auto-project/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java
diff --git a/code-generation/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java b/google-auto-project/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java
similarity index 100%
rename from code-generation/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java
rename to google-auto-project/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java
diff --git a/code-generation/src/test/java/com/baeldung/autovalue/PersonUnitTest.java b/google-auto-project/src/test/java/com/baeldung/autovalue/PersonUnitTest.java
similarity index 100%
rename from code-generation/src/test/java/com/baeldung/autovalue/PersonUnitTest.java
rename to google-auto-project/src/test/java/com/baeldung/autovalue/PersonUnitTest.java
diff --git a/google-cloud/pom.xml b/google-cloud/pom.xml
index 72b9647bc824..8bb535f12aa1 100644
--- a/google-cloud/pom.xml
+++ b/google-cloud/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
google-cloud
- 0.1-SNAPSHOT
google-cloud
jar
Google Cloud Tutorials
@@ -24,7 +23,6 @@
org.projectlombok
lombok
-
${lombok.version}
provided
diff --git a/gradle-modules/gradle-7/dependency-version/.gitattributes b/gradle-modules/gradle-7/dependency-version/.gitattributes
new file mode 100644
index 000000000000..097f9f98d9ee
--- /dev/null
+++ b/gradle-modules/gradle-7/dependency-version/.gitattributes
@@ -0,0 +1,9 @@
+#
+# https://help.github.com/articles/dealing-with-line-endings/
+#
+# Linux start script should use lf
+/gradlew text eol=lf
+
+# These are Windows script files and should use crlf
+*.bat text eol=crlf
+
diff --git a/gradle-modules/gradle-7/dependency-version/.gitignore b/gradle-modules/gradle-7/dependency-version/.gitignore
new file mode 100644
index 000000000000..1b6985c0094c
--- /dev/null
+++ b/gradle-modules/gradle-7/dependency-version/.gitignore
@@ -0,0 +1,5 @@
+# Ignore Gradle project-specific cache directory
+.gradle
+
+# Ignore Gradle build output directory
+build
diff --git a/gradle-modules/gradle-7/dependency-version/build.gradle b/gradle-modules/gradle-7/dependency-version/build.gradle
new file mode 100644
index 000000000000..7a8b51f5cc0b
--- /dev/null
+++ b/gradle-modules/gradle-7/dependency-version/build.gradle
@@ -0,0 +1,19 @@
+plugins {
+ id 'java'
+}
+
+group = "com.baeldung.gradle"
+version = "1.0.0-SNAPSHOT"
+sourceCompatibility = JavaVersion.VERSION_17
+
+repositories {
+ mavenLocal()
+ mavenCentral()
+}
+
+dependencies {
+ implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
+ implementation group: 'org.apache.commons', name: 'commons-collections4', version: '4.+'
+ implementation group: 'org.apache.commons', name: 'commons-math3', version: '[3.4, 3.5)'
+ implementation group: 'org.apache.commons', name: 'commons-text', version: 'latest.release'
+}
\ No newline at end of file
diff --git a/gradle-modules/gradle-7/dependency-version/gradle/wrapper/gradle-wrapper.properties b/gradle-modules/gradle-7/dependency-version/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000000..bdc9a83b1e65
--- /dev/null
+++ b/gradle-modules/gradle-7/dependency-version/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip
+networkTimeout=10000
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradle-modules/gradle-7/dependency-version/gradlew b/gradle-modules/gradle-7/dependency-version/gradlew
new file mode 100755
index 000000000000..79a61d421cc4
--- /dev/null
+++ b/gradle-modules/gradle-7/dependency-version/gradlew
@@ -0,0 +1,244 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+# Collect all arguments for the java command;
+# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
+# shell script including quotes and variable substitutions, so put them in
+# double quotes to make sure that they get re-expanded; and
+# * put everything else in single quotes, so that it's not re-expanded.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/gradle-modules/gradle-7/dependency-version/gradlew.bat b/gradle-modules/gradle-7/dependency-version/gradlew.bat
new file mode 100644
index 000000000000..93e3f59f135d
--- /dev/null
+++ b/gradle-modules/gradle-7/dependency-version/gradlew.bat
@@ -0,0 +1,92 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/gradle-modules/gradle-7/dependency-version/settings.gradle b/gradle-modules/gradle-7/dependency-version/settings.gradle
new file mode 100644
index 000000000000..a2e76e5b2113
--- /dev/null
+++ b/gradle-modules/gradle-7/dependency-version/settings.gradle
@@ -0,0 +1,10 @@
+/*
+ * This file was generated by the Gradle 'init' task.
+ *
+ * The settings file is used to specify which projects to include in your build.
+ *
+ * Detailed information about configuring a multi-project build in Gradle can be found
+ * in the user manual at https://docs.gradle.org/8.0.2/userguide/multi_project_builds.html
+ */
+
+rootProject.name = 'dependency-version'
diff --git a/gradle-modules/gradle-7/gradle-javadoc/.gitignore b/gradle-modules/gradle-7/gradle-javadoc/.gitignore
new file mode 100644
index 000000000000..b63da4551b2e
--- /dev/null
+++ b/gradle-modules/gradle-7/gradle-javadoc/.gitignore
@@ -0,0 +1,42 @@
+.gradle
+build/
+!gradle/wrapper/gradle-wrapper.jar
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### IntelliJ IDEA ###
+.idea/modules.xml
+.idea/jarRepositories.xml
+.idea/compiler.xml
+.idea/libraries/
+*.iws
+*.iml
+*.ipr
+out/
+!**/src/main/**/out/
+!**/src/test/**/out/
+
+### Eclipse ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+bin/
+!**/src/main/**/bin/
+!**/src/test/**/bin/
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+
+### VS Code ###
+.vscode/
+
+### Mac OS ###
+.DS_Store
\ No newline at end of file
diff --git a/gradle-modules/gradle-7/gradle-javadoc/build.gradle b/gradle-modules/gradle-7/gradle-javadoc/build.gradle
new file mode 100644
index 000000000000..5d8303d64c25
--- /dev/null
+++ b/gradle-modules/gradle-7/gradle-javadoc/build.gradle
@@ -0,0 +1,25 @@
+plugins {
+ id 'java'
+}
+
+group 'org.example'
+version '1.0-SNAPSHOT'
+
+javadoc {
+ destinationDir = file("${buildDir}/docs/javadoc")
+ include 'com/baeldung/addition/**'
+ exclude 'com/baeldung/subtraction/**'
+}
+
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
+ testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
+}
+
+test {
+ useJUnitPlatform()
+}
\ No newline at end of file
diff --git a/gradle-modules/gradle-7/gradle-javadoc/gradle/wrapper/gradle-wrapper.jar b/gradle-modules/gradle-7/gradle-javadoc/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000000..249e5832f090
Binary files /dev/null and b/gradle-modules/gradle-7/gradle-javadoc/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle-modules/gradle-7/gradle-javadoc/gradle/wrapper/gradle-wrapper.properties b/gradle-modules/gradle-7/gradle-javadoc/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000000..ae04661ee733
--- /dev/null
+++ b/gradle-modules/gradle-7/gradle-javadoc/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradle-modules/gradle-7/gradle-javadoc/gradlew b/gradle-modules/gradle-7/gradle-javadoc/gradlew
new file mode 100755
index 000000000000..a69d9cb6c206
--- /dev/null
+++ b/gradle-modules/gradle-7/gradle-javadoc/gradlew
@@ -0,0 +1,240 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+
+APP_NAME="Gradle"
+APP_BASE_NAME=${0##*/}
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+# Collect all arguments for the java command;
+# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
+# shell script including quotes and variable substitutions, so put them in
+# double quotes to make sure that they get re-expanded; and
+# * put everything else in single quotes, so that it's not re-expanded.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/gradle-modules/gradle-7/gradle-javadoc/gradlew.bat b/gradle-modules/gradle-7/gradle-javadoc/gradlew.bat
new file mode 100644
index 000000000000..53a6b238d414
--- /dev/null
+++ b/gradle-modules/gradle-7/gradle-javadoc/gradlew.bat
@@ -0,0 +1,91 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/gradle-modules/gradle-7/gradle-javadoc/settings.gradle b/gradle-modules/gradle-7/gradle-javadoc/settings.gradle
new file mode 100644
index 000000000000..3a648ffa2f5e
--- /dev/null
+++ b/gradle-modules/gradle-7/gradle-javadoc/settings.gradle
@@ -0,0 +1,2 @@
+rootProject.name = 'gradle-javadoc'
+
diff --git a/gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/addition/Sum.java b/gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/addition/Sum.java
new file mode 100644
index 000000000000..612196fb9d9c
--- /dev/null
+++ b/gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/addition/Sum.java
@@ -0,0 +1,17 @@
+package com.baeldung.addition;
+
+/**
+ * This is a sample class that demonstrates Javadoc comments.
+ */
+public class Sum {
+ /**
+ * This method returns the sum of two integers.
+ *
+ * @param a the first integer
+ * @param b the second integer
+ * @return the sum of a and b
+ */
+ public int add(int a, int b) {
+ return a + b;
+ }
+}
\ No newline at end of file
diff --git a/gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/subtraction/Difference.java b/gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/subtraction/Difference.java
new file mode 100644
index 000000000000..083cf2d1b8a8
--- /dev/null
+++ b/gradle-modules/gradle-7/gradle-javadoc/src/main/java/com/baeldung/subtraction/Difference.java
@@ -0,0 +1,17 @@
+package com.baeldung.subtraction;
+
+/**
+ * This is a sample class that demonstrates Javadoc comments.
+ */
+public class Difference {
+ /**
+ * This method returns the difference between the two integers.
+ *
+ * @param a the first integer
+ * @param b the second integer
+ * @return the difference between a and b
+ */
+ public int subtract(int a, int b) {
+ return a - b;
+ }
+}
\ No newline at end of file
diff --git a/gradle-modules/gradle-customization/protobuf/README.md b/gradle-modules/gradle-customization/protobuf/README.md
new file mode 100644
index 000000000000..4e94aa3557dc
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Configuring Protobuf Compilation with Custom Source Directories](https://www.baeldung.com/java-configure-protobuf-compilation-custom-source-directories)
diff --git a/gradle-modules/gradle-customization/protobuf/build.gradle b/gradle-modules/gradle-customization/protobuf/build.gradle
new file mode 100644
index 000000000000..3cac57fb03dd
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/build.gradle
@@ -0,0 +1,45 @@
+plugins {
+ id 'java'
+ id "com.google.protobuf" version "0.8.18"
+}
+
+group = 'com.baeldung'
+version = '0.0.1-SNAPSHOT'
+sourceCompatibility = '17'
+
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ implementation group: 'com.google.protobuf', name: 'protobuf-java', version: '3.15.0'
+ implementation group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'
+ testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
+ testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
+}
+
+tasks.named('test') {
+ useJUnitPlatform()
+}
+
+protobuf {
+ protoc {
+ artifact = 'com.google.protobuf:protoc:3.15.0'
+ }
+}
+
+sourceSets {
+ main {
+ proto {
+ srcDir 'src/sample_protofiles'
+ }
+ java {
+ srcDirs 'build/generated/source/proto/main/java'
+ }
+ }
+ test {
+ proto {
+ srcDir 'src/sample_protofiles'
+ }
+ }
+}
\ No newline at end of file
diff --git a/gradle-modules/gradle-customization/protobuf/gradle/wrapper/gradle-wrapper.properties b/gradle-modules/gradle-customization/protobuf/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000000..774fae87671b
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradle-modules/gradle-customization/protobuf/gradlew b/gradle-modules/gradle-customization/protobuf/gradlew
new file mode 100755
index 000000000000..a69d9cb6c206
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/gradlew
@@ -0,0 +1,240 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+
+APP_NAME="Gradle"
+APP_BASE_NAME=${0##*/}
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+# Collect all arguments for the java command;
+# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
+# shell script including quotes and variable substitutions, so put them in
+# double quotes to make sure that they get re-expanded; and
+# * put everything else in single quotes, so that it's not re-expanded.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/gradle-modules/gradle-customization/protobuf/gradlew.bat b/gradle-modules/gradle-customization/protobuf/gradlew.bat
new file mode 100644
index 000000000000..f127cfd49d40
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/gradlew.bat
@@ -0,0 +1,91 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/gradle-modules/gradle-customization/protobuf/settings.gradle b/gradle-modules/gradle-customization/protobuf/settings.gradle
new file mode 100644
index 000000000000..63483bae11d3
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = 'protobuf'
diff --git a/gradle-modules/gradle-customization/protobuf/src/main/resources/application.properties b/gradle-modules/gradle-customization/protobuf/src/main/resources/application.properties
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/src/main/resources/application.properties
@@ -0,0 +1 @@
+
diff --git a/gradle-modules/gradle-customization/protobuf/src/sample_protofiles/user_message.proto b/gradle-modules/gradle-customization/protobuf/src/sample_protofiles/user_message.proto
new file mode 100644
index 000000000000..60e06c20167c
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/src/sample_protofiles/user_message.proto
@@ -0,0 +1,13 @@
+syntax = "proto3";
+
+package com.baeldung.protobuf;
+
+option java_multiple_files = true;
+option java_package = "com.baeldung.protobuf.service";
+
+message User {
+ string firstName = 1;
+ optional string middleName = 2;
+ string lastName = 3;
+ optional uint32 age = 4;
+}
\ No newline at end of file
diff --git a/gradle-modules/gradle-customization/protobuf/src/test/java/com/baeldung/protobuf/ProtobufCodeGenerationUnitTest.java b/gradle-modules/gradle-customization/protobuf/src/test/java/com/baeldung/protobuf/ProtobufCodeGenerationUnitTest.java
new file mode 100644
index 000000000000..12187e3efb56
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/src/test/java/com/baeldung/protobuf/ProtobufCodeGenerationUnitTest.java
@@ -0,0 +1,28 @@
+package com.baeldung.protobuf;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+import com.baeldung.protobuf.service.User;
+
+class ProtobufCodeGenerationUnitTest {
+
+ @Test
+ void givenUserData_whenObjectCreated_thenDataShouldMatch() {
+ final String firstName = "John";
+ final String lastName = "Doe";
+ final int age = 28;
+
+ User user = User.newBuilder()
+ .setFirstName(firstName)
+ .setLastName(lastName)
+ .setAge(age)
+ .build();
+
+ assertEquals(firstName, user.getFirstName());
+ assertEquals(lastName, user.getLastName());
+ assertEquals(age, user.getAge());
+ }
+
+}
diff --git a/graphql-modules/graphql-dgs/pom.xml b/graphql-modules/graphql-dgs/pom.xml
index 051785b4b8b5..313e598130ce 100644
--- a/graphql-modules/graphql-dgs/pom.xml
+++ b/graphql-modules/graphql-dgs/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
graphql-dgs
- 1.0
graphql-dgs
diff --git a/graphql-modules/graphql-java/pom.xml b/graphql-modules/graphql-java/pom.xml
index 01b7a4fbc36e..88f2beb57437 100644
--- a/graphql-modules/graphql-java/pom.xml
+++ b/graphql-modules/graphql-java/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
graphql-java
- 1.0
graphql-java
@@ -13,21 +12,6 @@
1.0.0-SNAPSHOT
-
-
- jitpack.io
- https://jitpack.io
-
-
-
- false
-
- central
- Central Repository
- https://repo.maven.apache.org/maven2
-
-
-
com.graphql-java
@@ -143,6 +127,13 @@
+
+
+ jitpack.io
+ https://jitpack.io
+
+
+
11.0
5.2.4
diff --git a/graphql-modules/graphql-spqr-boot-starter/pom.xml b/graphql-modules/graphql-spqr-boot-starter/pom.xml
index 6cb1d7432977..fd9ebc0224b4 100644
--- a/graphql-modules/graphql-spqr-boot-starter/pom.xml
+++ b/graphql-modules/graphql-spqr-boot-starter/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
graphql-spqr-boot-starter
- 1.0
graphql-spqr-boot-starter
diff --git a/graphql-modules/graphql-spqr/pom.xml b/graphql-modules/graphql-spqr/pom.xml
index d845d1ac8a74..756930f2ac75 100644
--- a/graphql-modules/graphql-spqr/pom.xml
+++ b/graphql-modules/graphql-spqr/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
graphql-spqr
- 1.0
graphql-spqr
diff --git a/graphql-modules/pom.xml b/graphql-modules/pom.xml
index a42400b7cca2..4b43cbffde9c 100644
--- a/graphql-modules/pom.xml
+++ b/graphql-modules/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.graphql
graphql-modules
- 1.0.0-SNAPSHOT
graphql-modules
pom
diff --git a/grpc/pom.xml b/grpc/pom.xml
index 40d35183dc81..fed1e801f204 100644
--- a/grpc/pom.xml
+++ b/grpc/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
grpc
- 0.0.1-SNAPSHOT
grpc
jar
diff --git a/guava-modules/guava-18/pom.xml b/guava-modules/guava-18/pom.xml
index 8f5108bff13a..873555bf2478 100644
--- a/guava-modules/guava-18/pom.xml
+++ b/guava-modules/guava-18/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-18
- 0.1.0-SNAPSHOT
guava-18
diff --git a/guava-modules/guava-19/pom.xml b/guava-modules/guava-19/pom.xml
index ba85fe0ae8c0..9a40677e08fd 100644
--- a/guava-modules/guava-19/pom.xml
+++ b/guava-modules/guava-19/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-19
- 0.1.0-SNAPSHOT
guava-19
diff --git a/guava-modules/guava-21/pom.xml b/guava-modules/guava-21/pom.xml
index 9e791bfe231d..a26176ba0b1a 100644
--- a/guava-modules/guava-21/pom.xml
+++ b/guava-modules/guava-21/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-21
- 1.0-SNAPSHOT
guava-21
diff --git a/guava-modules/guava-collections-list/pom.xml b/guava-modules/guava-collections-list/pom.xml
index 6863b4011ce8..a07f34e56cf5 100644
--- a/guava-modules/guava-collections-list/pom.xml
+++ b/guava-modules/guava-collections-list/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-collections-list
- 0.1.0-SNAPSHOT
guava-collections-list
diff --git a/guava-modules/guava-collections-map/pom.xml b/guava-modules/guava-collections-map/pom.xml
index 04beaa13a164..6b73e8c29a40 100644
--- a/guava-modules/guava-collections-map/pom.xml
+++ b/guava-modules/guava-collections-map/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.guava
guava-collections-map
- 0.1.0-SNAPSHOT
guava-collections-map
diff --git a/guava-modules/guava-collections-set/pom.xml b/guava-modules/guava-collections-set/pom.xml
index 49bfc46ee252..ffd6c80a3ed9 100644
--- a/guava-modules/guava-collections-set/pom.xml
+++ b/guava-modules/guava-collections-set/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-collections-set
- 0.1.0-SNAPSHOT
guava-collections-set
diff --git a/guava-modules/guava-collections/pom.xml b/guava-modules/guava-collections/pom.xml
index 8dc052db7591..e016b1c5477f 100644
--- a/guava-modules/guava-collections/pom.xml
+++ b/guava-modules/guava-collections/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-collections
- 0.1.0-SNAPSHOT
guava-collections
diff --git a/guava-modules/guava-core/pom.xml b/guava-modules/guava-core/pom.xml
index dd68fef43a64..6c4f76356fe0 100644
--- a/guava-modules/guava-core/pom.xml
+++ b/guava-modules/guava-core/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-core
- 0.1.0-SNAPSHOT
guava-core
diff --git a/guava-modules/guava-io/pom.xml b/guava-modules/guava-io/pom.xml
index 2ea91c5e4f23..367533139e89 100644
--- a/guava-modules/guava-io/pom.xml
+++ b/guava-modules/guava-io/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-io
- 0.1.0-SNAPSHOT
guava-io
diff --git a/guava-modules/guava-utilities/pom.xml b/guava-modules/guava-utilities/pom.xml
index ab849072a544..407a44587e24 100644
--- a/guava-modules/guava-utilities/pom.xml
+++ b/guava-modules/guava-utilities/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-utilities
- 0.1.0-SNAPSHOT
guava-utilities
diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml
index 694563790f9d..4742f213e52c 100644
--- a/hazelcast/pom.xml
+++ b/hazelcast/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
hazelcast
- 0.0.1-SNAPSHOT
hazelcast
diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml
index eea056477c43..a6049432ce53 100644
--- a/httpclient-simple/pom.xml
+++ b/httpclient-simple/pom.xml
@@ -1,10 +1,9 @@
+ 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">
4.0.0
httpclient-simple
- 0.1-SNAPSHOT
httpclient-simple
war
diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java
index 616b6470af1e..3992fd821e8a 100644
--- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java
+++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java
@@ -25,26 +25,22 @@ class HttpClientHeadersLiveTest {
@Test
void whenClientUsesCustomUserAgent_thenCorrect() throws IOException {
- final HttpGet request = new HttpGet(SAMPLE_URL);
-
- try (CloseableHttpClient client = HttpClients.custom()
+ final CloseableHttpClient client = HttpClients.custom()
.setUserAgent("Mozilla/5.0 Firefox/26.0")
- .build()) {
+ .build();
+ final HttpGet request = new HttpGet(SAMPLE_URL);
- String response = client.execute(request, new BasicHttpClientResponseHandler());
- logger.info("Response -> {}", response);
- }
+ String response = client.execute(request, new BasicHttpClientResponseHandler());
+ logger.info("Response -> {}", response);
}
@Test
void whenRequestHasCustomUserAgent_thenCorrect() throws IOException {
+ CloseableHttpClient client = HttpClients.createDefault();
final HttpGet request = new HttpGet(SAMPLE_URL);
request.setHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 Firefox/26.0");
-
- try (CloseableHttpClient client = HttpClients.createDefault()) {
- String response = client.execute(request, new BasicHttpClientResponseHandler());
- logger.info("Response -> {}", response);
- }
+ String response = client.execute(request, new BasicHttpClientResponseHandler());
+ logger.info("Response -> {}", response);
}
@Test
diff --git a/hystrix/pom.xml b/hystrix/pom.xml
index 639d4eba0222..007c2e237b2a 100644
--- a/hystrix/pom.xml
+++ b/hystrix/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
hystrix
- 1.0
hystrix
diff --git a/image-processing/pom.xml b/image-processing/pom.xml
index 3780ecfd331c..2a2b92ca4848 100644
--- a/image-processing/pom.xml
+++ b/image-processing/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
image-processing
- 1.0-SNAPSHOT
image-processing
diff --git a/jackson-modules/jackson-annotations/pom.xml b/jackson-modules/jackson-annotations/pom.xml
index 4bb9341e43a9..e2d5e1e60758 100644
--- a/jackson-modules/jackson-annotations/pom.xml
+++ b/jackson-modules/jackson-annotations/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-annotations
- 0.0.1-SNAPSHOT
jackson-annotations
diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/format/User.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/format/User.java
index e655deb93ba2..119c1e3ce3e5 100644
--- a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/format/User.java
+++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/format/User.java
@@ -1,26 +1,41 @@
package com.baeldung.jackson.format;
-import java.util.Date;
-
-import com.baeldung.jackson.domain.Person;
import com.fasterxml.jackson.annotation.JsonFormat;
-/**
- * @author Jay Sridhar
- * @version 1.0
- */
-public class User extends Person {
+import java.util.Date;
+
+public class User {
private String firstName;
private String lastName;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
private Date createdDate;
+ public User() {
+ }
+
public User(String firstName, String lastName) {
- super(firstName, lastName);
+ this.firstName = firstName;
+ this.lastName = lastName;
this.createdDate = new Date();
}
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
public Date getCreatedDate() {
return createdDate;
}
@@ -35,3 +50,51 @@ public Date getDateNum() {
return new Date();
}
}
+
+@JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
+class UserIgnoreCase {
+ private String firstName;
+ private String lastName;
+
+ @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
+ private Date createdDate;
+
+ public UserIgnoreCase() {
+ }
+
+ public UserIgnoreCase(String firstName, String lastName) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.createdDate = new Date();
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public Date getCreatedDate() {
+ return createdDate;
+ }
+
+ @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB")
+ public Date getCurrentDate() {
+ return new Date();
+ }
+
+ @JsonFormat(shape = JsonFormat.Shape.NUMBER)
+ public Date getDateNum() {
+ return new Date();
+ }
+}
\ No newline at end of file
diff --git a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java
index cf166fdc369a..5cdc248d3bdd 100644
--- a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java
+++ b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java
@@ -1,24 +1,25 @@
package com.baeldung.jackson.format;
-import java.util.Date;
-
import com.fasterxml.jackson.core.JsonProcessingException;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-
+import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import org.junit.Test;
-import static io.restassured.path.json.JsonPath.from;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.TimeZone;
+import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.from;
import static org.assertj.core.data.Percentage.withPercentage;
-/**
- * @author Jay Sridhar
- * @version 1.0
- */
public class JsonFormatUnitTest {
+ private static final String JSON_STRING = "{\"FIRSTNAME\":\"John\",\"lastname\":\"Smith\",\"cReAtEdDaTe\":\"2016-12-18@07:53:34.740+0000\"}";
+
@Test
public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException {
@@ -32,6 +33,24 @@ public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingExceptio
// Expected to be close to current time
long now = new Date().getTime();
assertThat(from(result).getLong("dateNum")).isCloseTo(now, withPercentage(10.0));
+ }
+ @Test
+ public void whenDeserializeJsonStrToUserObject_thenFail() {
+ assertThatThrownBy(() -> new ObjectMapper().readValue(JSON_STRING, User.class)).isInstanceOf(UnrecognizedPropertyException.class);
}
-}
+
+ @Test
+ public void whenDeserializeJsonStrToUserIgnoreCaseObject_thenSuccess() throws JsonProcessingException, ParseException {
+ UserIgnoreCase result = new ObjectMapper().readValue(JSON_STRING, UserIgnoreCase.class);
+ SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSzz");
+ Date expectedDate = fmt.parse("2016-12-18T07:53:34.740+0000");
+
+ assertThat(result)
+ .isNotNull()
+ .returns("John", from(UserIgnoreCase::getFirstName))
+ .returns("Smith", from(UserIgnoreCase::getLastName))
+ .returns(expectedDate, from(UserIgnoreCase::getCreatedDate));
+ }
+
+}
\ No newline at end of file
diff --git a/jackson-modules/jackson-conversions-2/pom.xml b/jackson-modules/jackson-conversions-2/pom.xml
index 1c6d2fc0024c..457045b460b9 100644
--- a/jackson-modules/jackson-conversions-2/pom.xml
+++ b/jackson-modules/jackson-conversions-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-conversions-2
- 0.0.1-SNAPSHOT
jackson-conversions-2
diff --git a/jackson-modules/jackson-conversions/pom.xml b/jackson-modules/jackson-conversions/pom.xml
index 9218f209ac33..e0990ed34fe6 100644
--- a/jackson-modules/jackson-conversions/pom.xml
+++ b/jackson-modules/jackson-conversions/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-conversions
- 0.0.1-SNAPSHOT
jackson-conversions
@@ -24,6 +23,11 @@
jackson-datatype-jsr310
${jackson.version}
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
diff --git a/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/Fruit.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/Fruit.java
new file mode 100644
index 000000000000..49e45f216183
--- /dev/null
+++ b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/Fruit.java
@@ -0,0 +1,21 @@
+package com.baeldung.jackson.map;
+
+import com.fasterxml.jackson.annotation.JsonKey;
+import com.fasterxml.jackson.annotation.JsonValue;
+
+public class Fruit {
+ public String variety;
+
+ @JsonKey
+ public String name;
+
+ public Fruit(String variety, String name) {
+ this.variety = variety;
+ this.name = name;
+ }
+
+ @JsonValue
+ public String getFullName() {
+ return this.variety + " " + this.name;
+ }
+}
diff --git a/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/map/MapWithJsonKeyValueUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/map/MapWithJsonKeyValueUnitTest.java
new file mode 100644
index 000000000000..0b4639ca3b70
--- /dev/null
+++ b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/map/MapWithJsonKeyValueUnitTest.java
@@ -0,0 +1,48 @@
+package com.baeldung.jackson.map;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class MapWithJsonKeyValueUnitTest {
+ private static final Fruit FRUIT1 = new Fruit("Alphonso", "Mango");
+ private static final Fruit FRUIT2 = new Fruit("Black", "Grapes");
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ @Test
+ public void givenObject_WhenSerialize_ThenUseJsonValueForSerialization() throws JsonProcessingException {
+ String serializedValueForFruit1 = OBJECT_MAPPER.writeValueAsString(FRUIT1);
+ Assertions.assertEquals("\"Alphonso Mango\"", serializedValueForFruit1);
+ String serializedValueForFruit2 = OBJECT_MAPPER.writeValueAsString(FRUIT2);
+ Assertions.assertEquals("\"Black Grapes\"", serializedValueForFruit2);
+ }
+
+ @Test
+ public void givenMapWithObjectKeys_WhenSerialize_ThenUseJsonKeyForSerialization() throws JsonProcessingException {
+ // Given
+ Map selectionByFruit = new LinkedHashMap();
+ selectionByFruit.put(FRUIT1, "Hagrid");
+ selectionByFruit.put(FRUIT2, "Hercules");
+ // When
+ String serializedValue = OBJECT_MAPPER.writeValueAsString(selectionByFruit);
+ // Then
+ Assertions.assertEquals("{\"Mango\":\"Hagrid\",\"Grapes\":\"Hercules\"}", serializedValue);
+ }
+
+ @Test
+ public void givenMapWithObjectValues_WhenSerialize_ThenUseJsonValueForSerialization() throws JsonProcessingException {
+ // Given
+ Map selectionByPerson = new LinkedHashMap();
+ selectionByPerson.put("Hagrid", FRUIT1);
+ selectionByPerson.put("Hercules", FRUIT2);
+ // When
+ String serializedValue = OBJECT_MAPPER.writeValueAsString(selectionByPerson);
+ // Then
+ Assertions.assertEquals("{\"Hagrid\":\"Alphonso Mango\",\"Hercules\":\"Black Grapes\"}", serializedValue);
+ }
+}
diff --git a/jackson-modules/jackson-core/README.md b/jackson-modules/jackson-core/README.md
index d34a9e8bf79c..73293b1e842f 100644
--- a/jackson-modules/jackson-core/README.md
+++ b/jackson-modules/jackson-core/README.md
@@ -15,3 +15,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model)
- [Get all the Keys in a JSON String Using JsonNode](https://www.baeldung.com/java-jsonnode-get-keys)
- [Difference Between asText() and toString() in JsonNode](https://www.baeldung.com/java-jsonnode-astext-vs-tostring)
+- [Deserialize Generic Type with Jackson](https://www.baeldung.com/java-deserialize-generic-type-with-jackson)
diff --git a/jackson-modules/jackson-core/pom.xml b/jackson-modules/jackson-core/pom.xml
index f3edffc07ca2..4eccd4d8f8dc 100644
--- a/jackson-modules/jackson-core/pom.xml
+++ b/jackson-modules/jackson-core/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-core
- 0.0.1-SNAPSHOT
jackson-core
diff --git a/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/deserialization/jsongeneric/JsonResponse.java b/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/deserialization/jsongeneric/JsonResponse.java
new file mode 100644
index 000000000000..14f6b3f8ad79
--- /dev/null
+++ b/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/deserialization/jsongeneric/JsonResponse.java
@@ -0,0 +1,14 @@
+package com.baeldung.jackson.deserialization.jsongeneric;
+
+public class JsonResponse {
+
+ private T result;
+
+ public T getResult() {
+ return result;
+ }
+
+ public void setResult(T result) {
+ this.result = result;
+ }
+}
diff --git a/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/deserialization/jsongeneric/User.java b/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/deserialization/jsongeneric/User.java
new file mode 100644
index 000000000000..1efb3af7f9d3
--- /dev/null
+++ b/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/deserialization/jsongeneric/User.java
@@ -0,0 +1,33 @@
+package com.baeldung.jackson.deserialization.jsongeneric;
+
+public class User {
+
+ private Long id;
+ private String firstName;
+ private String lastName;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+}
+
diff --git a/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/deserialization/jsongeneric/GenericTypeDeserializerUnitTest.java b/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/deserialization/jsongeneric/GenericTypeDeserializerUnitTest.java
new file mode 100644
index 000000000000..24baeb7f1f68
--- /dev/null
+++ b/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/deserialization/jsongeneric/GenericTypeDeserializerUnitTest.java
@@ -0,0 +1,40 @@
+package com.baeldung.jackson.deserialization.jsongeneric;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GenericTypeDeserializerUnitTest {
+
+ ObjectMapper objectMapper = new ObjectMapper();
+
+ @Test
+ void givenJsonObject_whenDeserializeIntoGenericTypeByTypeReference_thenCorrect() throws JsonProcessingException {
+ String json = "{\"result\":{\"id\":1,\"firstName\":\"John\",\"lastName\":\"Lewis\"}}";
+
+ TypeReference> typeRef = new TypeReference>() {};
+ JsonResponse jsonResponse = objectMapper.readValue(json, typeRef);
+ User user = jsonResponse.getResult();
+
+ assertThat(user.getId()).isEqualTo(1);
+ assertThat(user.getFirstName()).isEqualTo("John");
+ assertThat(user.getLastName()).isEqualTo("Lewis");
+ }
+
+ @Test
+ void givenJsonObject_whenDeserializeIntoGenericTypeByJavaType_thenCorrect() throws JsonProcessingException {
+ String json = "{\"result\":{\"id\":1,\"firstName\":\"John\",\"lastName\":\"Lewis\"}}";
+
+ JavaType javaType = objectMapper.getTypeFactory().constructParametricType(JsonResponse.class, User.class);
+ JsonResponse jsonResponse = objectMapper.readValue(json, javaType);
+ User user = jsonResponse.getResult();
+
+ assertThat(user.getId()).isEqualTo(1);
+ assertThat(user.getFirstName()).isEqualTo("John");
+ assertThat(user.getLastName()).isEqualTo("Lewis");
+ }
+}
\ No newline at end of file
diff --git a/jackson-modules/jackson-custom-conversions/README.md b/jackson-modules/jackson-custom-conversions/README.md
index 68e9a6d50d0e..2f45a2f43b2d 100644
--- a/jackson-modules/jackson-custom-conversions/README.md
+++ b/jackson-modules/jackson-custom-conversions/README.md
@@ -7,3 +7,4 @@ This module contains articles about Jackson custom conversions.
- [Getting Started with Custom Deserialization in Jackson](https://www.baeldung.com/jackson-deserialization)
- [Serialize Only Fields that meet a Custom Criteria with Jackson](https://www.baeldung.com/jackson-serialize-field-custom-criteria)
- [Calling Default Serializer from Custom Serializer in Jackson](https://www.baeldung.com/jackson-call-default-serializer-from-custom-serializer)
+- [OffsetDateTime Serialization With Jackson](https://www.baeldung.com/java-jackson-offsetdatetime)
diff --git a/jackson-modules/jackson-custom-conversions/pom.xml b/jackson-modules/jackson-custom-conversions/pom.xml
index 79af962eece7..31e460511a40 100644
--- a/jackson-modules/jackson-custom-conversions/pom.xml
+++ b/jackson-modules/jackson-custom-conversions/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-custom-conversions
- 0.0.1-SNAPSHOT
jackson-custom-conversions
diff --git a/jackson-modules/jackson-exceptions/README.md b/jackson-modules/jackson-exceptions/README.md
index 6f082aaaa563..b9c43cb09f1d 100644
--- a/jackson-modules/jackson-exceptions/README.md
+++ b/jackson-modules/jackson-exceptions/README.md
@@ -5,3 +5,4 @@ This module contains articles about Jackson exceptions.
### Relevant Articles:
- [Jackson Exceptions – Problems and Solutions](https://www.baeldung.com/jackson-exception)
- [Jackson – JsonMappingException (No serializer found for class)](https://www.baeldung.com/jackson-jsonmappingexception)
+- [Fix the JsonMappingException: Can not deserialize instance of java.util.ArrayList from Object value (token `JsonToken.START_OBJECT`)](https://www.baeldung.com/jsonmappingexception-can-not-deserialize-instance-of-java-util-arraylist-from-object-value-token-jsontoken-start_object)
diff --git a/jackson-modules/jackson-exceptions/pom.xml b/jackson-modules/jackson-exceptions/pom.xml
index a24a0ab4b710..e19ef4f8835b 100644
--- a/jackson-modules/jackson-exceptions/pom.xml
+++ b/jackson-modules/jackson-exceptions/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-exceptions
- 0.0.1-SNAPSHOT
jackson-exceptions
diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/Country.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/Country.java
new file mode 100644
index 000000000000..a8e6dfbc9456
--- /dev/null
+++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/Country.java
@@ -0,0 +1,26 @@
+package com.baeldung.mappingexception;
+
+import java.util.List;
+
+public class Country {
+
+ private String name;
+ private List cities;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public List getCities() {
+ return cities;
+ }
+
+ public void setCities(List cities) {
+ this.cities = cities;
+ }
+
+}
diff --git a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java
index df3562682822..026fd6719fc6 100644
--- a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java
+++ b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java
@@ -1,34 +1,33 @@
package com.baeldung.mappingexception;
import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Arrays;
-import java.io.IOException;
-import java.util.List;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
-import com.fasterxml.jackson.core.JsonGenerationException;
-import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.module.SimpleModule;
-import com.google.common.collect.Lists;
public class JacksonMappingExceptionUnitTest {
@Test(expected = JsonMappingException.class)
- public final void givenObjectHasNoAccessors_whenSerializing_thenException() throws JsonParseException, IOException {
+ public void givenObjectHasNoAccessors_whenSerializing_thenException() throws JsonProcessingException {
final String dtoAsString = new ObjectMapper().writeValueAsString(new MyDtoNoAccessors());
assertThat(dtoAsString, notNullValue());
}
@Test
- public final void givenObjectHasNoAccessors_whenSerializingWithPrivateFieldsVisibility_thenNoException() throws JsonParseException, IOException {
+ public void givenObjectHasNoAccessors_whenSerializingWithPrivateFieldsVisibility_thenNoException() throws JsonProcessingException {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
final String dtoAsString = objectMapper.writeValueAsString(new MyDtoNoAccessors());
@@ -39,7 +38,7 @@ public final void givenObjectHasNoAccessors_whenSerializingWithPrivateFieldsVisi
}
@Test
- public final void givenObjectHasNoAccessorsButHasVisibleFields_whenSerializing_thenNoException() throws JsonParseException, IOException {
+ public void givenObjectHasNoAccessorsButHasVisibleFields_whenSerializing_thenNoException() throws JsonProcessingException {
final ObjectMapper objectMapper = new ObjectMapper();
final String dtoAsString = objectMapper.writeValueAsString(new MyDtoNoAccessorsAndFieldVisibility());
@@ -48,4 +47,30 @@ public final void givenObjectHasNoAccessorsButHasVisibleFields_whenSerializing_t
assertThat(dtoAsString, containsString("booleanValue"));
}
+ @Test
+ public void givenJsonWithInvalidList_whenDeserializing_thenThrowException() throws JsonProcessingException {
+ final String json = "{\"name\":\"Netherlands\",\"cities\":{\"Amsterdam\", \"Tamassint\"}}";
+ final ObjectMapper mapper = new ObjectMapper();
+
+ Exception exception = assertThrows(JsonMappingException.class, () -> mapper.reader()
+ .forType(Country.class)
+ .readValue(json));
+
+ assertTrue(exception.getMessage()
+ .contains("Cannot deserialize value of type `java.util.ArrayList`"));
+ }
+
+ @Test
+ public void givenJsonWithValidList_whenDeserializing_thenCorrect() throws JsonProcessingException {
+ final String json = "{\"name\":\"Netherlands\",\"cities\":[\"Amsterdam\", \"Tamassint\"]}";
+ final ObjectMapper mapper = new ObjectMapper();
+
+ Country country = mapper.reader()
+ .forType(Country.class)
+ .readValue(json);
+
+ assertEquals("Netherlands", country.getName());
+ assertEquals(Arrays.asList("Amsterdam", "Tamassint"), country.getCities());
+ }
+
}
diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml
index f71cb1ffbfdc..d1fcc867cf19 100644
--- a/jackson-simple/pom.xml
+++ b/jackson-simple/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-simple
- 0.0.1-SNAPSHOT
jackson-simple
@@ -33,4 +32,8 @@
+
+ 2.14.2
+
+
\ No newline at end of file
diff --git a/jackson-simple/src/main/java/com/baeldung/jackson/annotation/BeanWithInclude.java b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/BeanWithInclude.java
new file mode 100644
index 000000000000..18130fc9f21a
--- /dev/null
+++ b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/BeanWithInclude.java
@@ -0,0 +1,18 @@
+package com.baeldung.jackson.annotation;
+
+import com.fasterxml.jackson.annotation.JsonIncludeProperties;
+
+@JsonIncludeProperties({ "name" })
+public class BeanWithInclude {
+ public int id;
+ public String name;
+
+ public BeanWithInclude() {
+
+ }
+
+ public BeanWithInclude(final int id, final String name) {
+ this.id = id;
+ this.name = name;
+ }
+}
diff --git a/jackson-simple/src/main/java/com/baeldung/jackson/annotation/GeneralBean.java b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/GeneralBean.java
new file mode 100644
index 000000000000..a8333f54ae5d
--- /dev/null
+++ b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/GeneralBean.java
@@ -0,0 +1,26 @@
+package com.baeldung.jackson.annotation;
+
+import com.fasterxml.jackson.annotation.JsonValue;
+
+public class GeneralBean {
+ Integer id;
+
+ @JsonValue
+ String name;
+
+ public GeneralBean() {
+ }
+
+ public GeneralBean(Integer id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+}
diff --git a/jackson-simple/src/main/java/com/baeldung/jackson/annotation/PriorityEnum.java b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/PriorityEnum.java
new file mode 100644
index 000000000000..ed74052edebb
--- /dev/null
+++ b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/PriorityEnum.java
@@ -0,0 +1,16 @@
+package com.baeldung.jackson.annotation;
+
+import com.fasterxml.jackson.annotation.JsonValue;
+
+public enum PriorityEnum {
+
+ LOW(0), MEDIUM(1), HIGH(3);
+
+ @JsonValue
+ private int level;
+
+ PriorityEnum(int level) {
+ this.level = level;
+ }
+
+}
diff --git a/jackson-simple/src/main/java/com/baeldung/jackson/annotation/dtos/withEnum/TypeEnumWithValue.java b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/dtos/withEnum/TypeEnumWithValue.java
new file mode 100644
index 000000000000..2c8718dfd8fd
--- /dev/null
+++ b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/dtos/withEnum/TypeEnumWithValue.java
@@ -0,0 +1,23 @@
+package com.baeldung.jackson.annotation.dtos.withEnum;
+
+import com.fasterxml.jackson.annotation.JsonValue;
+
+public enum TypeEnumWithValue {
+ TYPE1(1, "Type A"), TYPE2(2, "Type 2");
+
+ private Integer id;
+
+ @JsonValue
+ private String name;
+
+
+ TypeEnumWithValue(int id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ //@JsonValue
+ public String getName() {
+ return name;
+ }
+}
diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/annotation/JacksonAnnotationUnitTest.java b/jackson-simple/src/test/java/com/baeldung/jackson/annotation/JacksonAnnotationUnitTest.java
index bbbb79b0a85f..1a6c7b128671 100644
--- a/jackson-simple/src/test/java/com/baeldung/jackson/annotation/JacksonAnnotationUnitTest.java
+++ b/jackson-simple/src/test/java/com/baeldung/jackson/annotation/JacksonAnnotationUnitTest.java
@@ -20,10 +20,12 @@
import com.baeldung.jackson.annotation.bidirection.UserWithRef;
import com.baeldung.jackson.annotation.date.EventWithFormat;
import com.baeldung.jackson.annotation.date.EventWithSerializer;
+import com.baeldung.jackson.annotation.dtos.withEnum.TypeEnumWithValue;
import com.baeldung.jackson.annotation.ignore.MyMixInForIgnoreType;
import com.baeldung.jackson.annotation.dtos.withEnum.DistanceEnumWithValue;
import com.baeldung.jackson.annotation.exception.UserWithRoot;
import com.baeldung.jackson.annotation.exception.UserWithRootNamespace;
+import com.baeldung.jackson.annotation.ignore.MyMixInForIgnoreType;
import com.baeldung.jackson.annotation.jsonview.Item;
import com.baeldung.jackson.annotation.jsonview.Views;
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -95,6 +97,14 @@ public void whenSerializingUsingJsonValue_thenCorrect() throws IOException {
assertThat(enumAsString, is("1609.34"));
}
+
+ @Test
+ public void whenSerializingFieldUsingJsonValue_thenCorrect() throws IOException {
+ final String enumAsString = new ObjectMapper().writeValueAsString(PriorityEnum.HIGH);
+
+ assertEquals("3", enumAsString);
+ }
+
@Test
public void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessingException, ParseException {
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
@@ -107,6 +117,19 @@ public void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessin
assertThat(result, containsString(toParse));
}
+ @Test
+ public void whenSerializingUsingJsonValueAnnotatedField_thenCorrect() throws JsonProcessingException {
+ final String enumValue = new ObjectMapper().writeValueAsString(TypeEnumWithValue.TYPE1);
+ assertThat(enumValue, is("\"Type A\""));
+ }
+
+ @Test
+ public void whenSerializingUsingJsonValueAnnotatedFieldInPojo_thenCorrect() throws JsonProcessingException {
+ GeneralBean bean1 = new GeneralBean(1, "Bean 1");
+ final String bean1AsString = new ObjectMapper().writeValueAsString(bean1);
+ assertThat(bean1AsString, is("\"Bean 1\""));
+ }
+
// ========================= Deserializing annotations ============================
@Test
@@ -118,6 +141,7 @@ public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException {
assertEquals("My bean", bean.name);
}
+
@Test
public void whenDeserializingUsingJsonInject_thenCorrect() throws IOException {
final String json = "{\"name\":\"My bean\"}";
@@ -161,6 +185,23 @@ public void whenDeserializingUsingJsonDeserialize_thenCorrect() throws IOExcepti
assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
}
+ @Test
+ public void whenDeserializingUsingJsonValue_thenCorrect() throws JsonProcessingException {
+ final String str = "\"Type A\"";
+ TypeEnumWithValue te = new ObjectMapper().readerFor(TypeEnumWithValue.class)
+ .readValue(str);
+ assertThat(te, is(TypeEnumWithValue.TYPE1));
+ }
+
+ @Test(expected = Exception.class)
+ public void whenDeserializingUsingJsonValueAnnotatedFieldInPojo_thenGetException() throws JsonProcessingException {
+ GeneralBean bean1 = new GeneralBean(1, "Bean 1");
+ final String bean1AsString = new ObjectMapper().writeValueAsString(bean1);
+ GeneralBean bean = new ObjectMapper().readerFor(GeneralBean.class)
+ .readValue(bean1AsString);
+ assertThat(bean.getName(), is(bean1.getName()));
+ }
+
// ========================= Inclusion annotations ============================
@Test
@@ -172,6 +213,15 @@ public void whenSerializingUsingJsonIgnoreProperties_thenCorrect() throws JsonPr
assertThat(result, not(containsString("id")));
}
+ @Test
+ public void whenSerializingUsingJsonIncludeProperties_thenCorrect() throws JsonProcessingException {
+ final BeanWithInclude bean = new BeanWithInclude(1, "My bean");
+ final String result = new ObjectMapper().writeValueAsString(bean);
+ assertThat(result, containsString("My bean"));
+ assertThat(result, not(containsString("id")));
+ assertThat(result, containsString("name"));
+ }
+
@Test
public void whenSerializingUsingJsonIgnore_thenCorrect() throws JsonProcessingException {
final BeanWithIgnore bean = new BeanWithIgnore(1, "My bean");
@@ -399,7 +449,5 @@ public void whenSerializingUsingXMLRootNameWithNameSpace_thenCorrect() throws Js
*/
}
-
-
}
diff --git a/java-blockchain/pom.xml b/java-blockchain/pom.xml
index 2279a7ceff8b..d45d2bf57378 100644
--- a/java-blockchain/pom.xml
+++ b/java-blockchain/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.blockchain
java-blockchain
- 0.1.0-SNAPSHOT
java-blockchain
jar
diff --git a/java-jdi/pom.xml b/java-jdi/pom.xml
index a8716de4eefd..dded13896f77 100644
--- a/java-jdi/pom.xml
+++ b/java-jdi/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
java-jdi
- 0.1.0-SNAPSHOT
java-jdi
jar
@@ -16,13 +15,7 @@
-
- com.sun
- tools
- ${tools.version}
- system
- ${java.home}/../lib/tools.jar
-
+
@@ -33,10 +26,25 @@
true
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ ${maven.compiler.target.version}
+
+ --add-exports=jdk.jdi/com.sun.jdi=ALL-UNNAMED
+
+
+
+
+
- 1.8
+ 17
+ 17
\ No newline at end of file
diff --git a/java-panama/pom.xml b/java-panama/pom.xml
index 8453a38abd7f..7c6b420eebae 100644
--- a/java-panama/pom.xml
+++ b/java-panama/pom.xml
@@ -1,49 +1,48 @@
-
- ${project.model.version}
+
+ ${project.model.version}
+ com.baeldung.java.panama
+ java-panama
+ ${project.version}
+ java-panama
+ jar
- com.baeldung.java.panama
- java-panama
- ${project.version}
- jar
+
+
+ org.junit.jupiter
+ junit-jupiter
+ ${junit.jupiter.version}
+ test
+
+
- java-panama
- https://maven.apache.org
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven.compiler.version}
+
+
+ ${maven.compiler.target}
+
+ --add-opens=java.base/java.lang.foreign=ALL-UNNAMED
+ --enable-preview
+
+
+
+
+
-
- 4.0.0
- UTF-8
- 1.0
- 19
- 19
- 3.10.1
- 5.9.0
-
+
+ 4.0.0
+ UTF-8
+ 1.0
+ 19
+ 19
+ 3.10.1
+ 5.9.0
+
-
-
- org.junit.jupiter
- junit-jupiter
- ${junit.jupiter.version}
- test
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven.compiler.version}
-
-
- ${maven.compiler.target}
-
- --add-opens=java.base/java.lang.foreign=ALL-UNNAMED
- --enable-preview
-
-
-
-
-
diff --git a/java-rmi/pom.xml b/java-rmi/pom.xml
index fee5107423ce..2256883f84ba 100644
--- a/java-rmi/pom.xml
+++ b/java-rmi/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.rmi
java-rmi
- 1.0-SNAPSHOT
java-rmi
jar
diff --git a/java-websocket/pom.xml b/java-websocket/pom.xml
index 41c1b251c023..7c5c006aa9ec 100644
--- a/java-websocket/pom.xml
+++ b/java-websocket/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
java-websocket
- 0.0.1-SNAPSHOT
java-websocket
war
diff --git a/javax-sound/pom.xml b/javax-sound/pom.xml
index dcd08cbcb8d5..6652022a404b 100644
--- a/javax-sound/pom.xml
+++ b/javax-sound/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.javax-sound
javax-sound
- 1.0-SNAPSHOT
javax-sound
jar
diff --git a/javax-validation-advanced/pom.xml b/javax-validation-advanced/pom.xml
index 39da16607112..7709f37883b9 100644
--- a/javax-validation-advanced/pom.xml
+++ b/javax-validation-advanced/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
javax-validation-advanced
- 0.1-SNAPSHOT
javax-validation-advanced
diff --git a/javaxval-2/README.md b/javaxval-2/README.md
index 52c9b42ac46e..0fd5ce163bf0 100644
--- a/javaxval-2/README.md
+++ b/javaxval-2/README.md
@@ -4,7 +4,6 @@ This module contains articles about Bean Validation.
### Relevant Articles:
- [Method Constraints with Bean Validation 2.0](https://www.baeldung.com/javax-validation-method-constraints)
-- [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank)
- [Guide to ParameterMessageInterpolator](https://www.baeldung.com/hibernate-parametermessageinterpolator)
- [Hibernate Validator Annotation Processor in Depth](https://www.baeldung.com/hibernate-validator-annotation-processor)
- More articles: [[<-- prev]](../javaxval)
\ No newline at end of file
diff --git a/javaxval/README.md b/javaxval/README.md
index 95d9410fffd9..b7e19d579405 100644
--- a/javaxval/README.md
+++ b/javaxval/README.md
@@ -10,4 +10,5 @@ This module contains articles about Bean Validation.
- [Grouping Javax Validation Constraints](https://www.baeldung.com/javax-validation-groups)
- [Constraint Composition with Bean Validation](https://www.baeldung.com/java-bean-validation-constraint-composition)
- [Using @NotNull on a Method Parameter](https://www.baeldung.com/java-notnull-method-parameter)
+- [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank)
- More articles: [[next -->]](../javaxval-2)
\ No newline at end of file
diff --git a/javaxval/pom.xml b/javaxval/pom.xml
index 1feed71abb57..bececb2ea781 100644
--- a/javaxval/pom.xml
+++ b/javaxval/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
javaxval
- 0.1-SNAPSHOT
javaxval
@@ -14,26 +13,6 @@
-
- org.hibernate.validator
- hibernate-validator
- ${hibernate-validator.version}
-
-
- org.glassfish
- javax.el
- ${javax.el.version}
-
-
- org.springframework
- spring-context
- ${org.springframework.version}
-
-
- org.springframework
- spring-test
- ${org.springframework.version}
-
org.springframework.boot
spring-boot-starter-validation
@@ -46,7 +25,7 @@
test
-
+
@@ -58,11 +37,8 @@
- 6.2.3.Final
6.2.0.Final
- 3.0.0
- 5.3.21
- 2.7.1
+ 3.0.4
\ No newline at end of file
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/beanvalidation/User.java b/javaxval/src/main/java/com/baeldung/javaxval/beanvalidation/User.java
index d583ac51d241..7305b6c20118 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/beanvalidation/User.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/beanvalidation/User.java
@@ -4,14 +4,14 @@
import java.util.List;
import java.util.Optional;
-import javax.validation.constraints.AssertTrue;
-import javax.validation.constraints.Email;
-import javax.validation.constraints.Max;
-import javax.validation.constraints.Min;
-import javax.validation.constraints.NotBlank;
-import javax.validation.constraints.NotNull;
-import javax.validation.constraints.Past;
-import javax.validation.constraints.Size;
+import jakarta.validation.constraints.AssertTrue;
+import jakarta.validation.constraints.Email;
+import jakarta.validation.constraints.Max;
+import jakarta.validation.constraints.Min;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Past;
+import jakarta.validation.constraints.Size;
public class User {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/bigdecimal/Invoice.java b/javaxval/src/main/java/com/baeldung/javaxval/bigdecimal/Invoice.java
index c14a6bd2b125..c946a8df68e7 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/bigdecimal/Invoice.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/bigdecimal/Invoice.java
@@ -2,8 +2,8 @@
import java.math.BigDecimal;
-import javax.validation.constraints.DecimalMin;
-import javax.validation.constraints.Digits;
+import jakarta.validation.constraints.DecimalMin;
+import jakarta.validation.constraints.Digits;
public class Invoice {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/AlphanumericReturnValue.java b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/AlphanumericReturnValue.java
index 6e3408712bfb..65f6eceb3400 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/AlphanumericReturnValue.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/AlphanumericReturnValue.java
@@ -2,12 +2,12 @@
import org.hibernate.validator.constraints.Length;
-import javax.validation.Constraint;
-import javax.validation.Payload;
-import javax.validation.constraints.NotNull;
-import javax.validation.constraints.Pattern;
-import javax.validation.constraintvalidation.SupportedValidationTarget;
-import javax.validation.constraintvalidation.ValidationTarget;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Pattern;
+import jakarta.validation.constraintvalidation.SupportedValidationTarget;
+import jakarta.validation.constraintvalidation.ValidationTarget;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumeric.java b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumeric.java
index 916b4e36a472..9d4d4995c536 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumeric.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumeric.java
@@ -11,10 +11,10 @@
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import javax.validation.Constraint;
-import javax.validation.Payload;
-import javax.validation.constraints.NotNull;
-import javax.validation.constraints.Pattern;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumericWithSingleViolation.java b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumericWithSingleViolation.java
index edc5b6af3e65..31eca29a0771 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumericWithSingleViolation.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumericWithSingleViolation.java
@@ -11,11 +11,11 @@
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import javax.validation.Constraint;
-import javax.validation.Payload;
-import javax.validation.ReportAsSingleViolation;
-import javax.validation.constraints.NotNull;
-import javax.validation.constraints.Pattern;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
+import jakarta.validation.ReportAsSingleViolation;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidLengthOrNumericCharacter.java b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidLengthOrNumericCharacter.java
index 444cb4a63a93..9f46e1e7b856 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidLengthOrNumericCharacter.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidLengthOrNumericCharacter.java
@@ -4,9 +4,9 @@
import org.hibernate.validator.constraints.ConstraintComposition;
import org.hibernate.validator.constraints.Length;
-import javax.validation.Constraint;
-import javax.validation.Payload;
-import javax.validation.constraints.Pattern;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
+import jakarta.validation.constraints.Pattern;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java
index 03811635eed0..c0b23f0ae8f3 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java
@@ -4,9 +4,9 @@
import java.util.Optional;
import java.util.OptionalInt;
-import javax.validation.constraints.Min;
-import javax.validation.constraints.NotBlank;
-import javax.validation.constraints.PositiveOrZero;
+import jakarta.validation.constraints.Min;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.PositiveOrZero;
public class Customer {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/CustomerMap.java b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/CustomerMap.java
index 554285fbae7f..902f04c654c2 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/CustomerMap.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/CustomerMap.java
@@ -2,8 +2,8 @@
import java.util.Map;
-import javax.validation.constraints.Email;
-import javax.validation.constraints.NotNull;
+import jakarta.validation.constraints.Email;
+import jakarta.validation.constraints.NotNull;
public class CustomerMap {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java
index 03e0c7aac4de..a3a21fe88b0e 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java
@@ -1,8 +1,8 @@
package com.baeldung.javaxval.container.validation.valueextractors;
-import javax.validation.valueextraction.ExtractedValue;
-import javax.validation.valueextraction.UnwrapByDefault;
-import javax.validation.valueextraction.ValueExtractor;
+import jakarta.validation.valueextraction.ExtractedValue;
+import jakarta.validation.valueextraction.UnwrapByDefault;
+import jakarta.validation.valueextraction.ValueExtractor;
import com.baeldung.javaxval.container.validation.Profile;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java
index c91f449badf8..da86ec6c89da 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java
@@ -2,8 +2,8 @@
import java.util.Arrays;
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
+import jakarta.validation.ConstraintValidator;
+import jakarta.validation.ConstraintValidatorContext;
import com.baeldung.javaxval.enums.constraints.CustomerTypeSubset;
import com.baeldung.javaxval.enums.demo.CustomerType;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumNamePatternValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumNamePatternValidator.java
index 3d56d4056308..5cce8e10e76b 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumNamePatternValidator.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumNamePatternValidator.java
@@ -4,8 +4,8 @@
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
+import jakarta.validation.ConstraintValidator;
+import jakarta.validation.ConstraintValidatorContext;
import com.baeldung.javaxval.enums.constraints.EnumNamePattern;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumSubSetValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumSubSetValidator.java
index 04cccb8b0c93..a3a92a4f4eb6 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumSubSetValidator.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumSubSetValidator.java
@@ -3,8 +3,8 @@
import java.lang.annotation.Annotation;
import java.util.Arrays;
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
+import jakarta.validation.ConstraintValidator;
+import jakarta.validation.ConstraintValidatorContext;
public abstract class EnumSubSetValidator implements ConstraintValidator {
private U[] subset;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/ValueOfEnumValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/ValueOfEnumValidator.java
index 0203d639231b..c2f2ecee3b34 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/ValueOfEnumValidator.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/ValueOfEnumValidator.java
@@ -4,8 +4,8 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
+import jakarta.validation.ConstraintValidator;
+import jakarta.validation.ConstraintValidatorContext;
import com.baeldung.javaxval.enums.constraints.ValueOfEnum;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java
index 97c2137f6a87..fe03e228f601 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java
@@ -12,8 +12,8 @@
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import javax.validation.Constraint;
-import javax.validation.Payload;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
import com.baeldung.javaxval.enums.CustomerTypeSubSetValidator;
import com.baeldung.javaxval.enums.demo.CustomerType;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/EnumNamePattern.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/EnumNamePattern.java
index 29fff857c868..4ef1eac9c0f0 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/EnumNamePattern.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/EnumNamePattern.java
@@ -12,8 +12,8 @@
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import javax.validation.Constraint;
-import javax.validation.Payload;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
import com.baeldung.javaxval.enums.EnumNamePatternValidator;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/ValueOfEnum.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/ValueOfEnum.java
index 29b44a1793c8..bbfe6ed5ab34 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/ValueOfEnum.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/ValueOfEnum.java
@@ -12,8 +12,8 @@
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import javax.validation.Constraint;
-import javax.validation.Payload;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
import com.baeldung.javaxval.enums.ValueOfEnumValidator;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/Customer.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/Customer.java
index 15cd9e0da737..db38dd00151d 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/Customer.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/Customer.java
@@ -1,6 +1,6 @@
package com.baeldung.javaxval.enums.demo;
-import javax.validation.constraints.NotNull;
+import jakarta.validation.constraints.NotNull;
import com.baeldung.javaxval.enums.constraints.CustomerTypeSubset;
import com.baeldung.javaxval.enums.constraints.EnumNamePattern;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/application/Application.java b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/application/Application.java
index 22157f351c5b..b1c53c5be35b 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/application/Application.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/application/Application.java
@@ -1,7 +1,7 @@
package com.baeldung.javaxval.javabeanconstraints.application;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import com.baeldung.javaxval.javabeanconstraints.entities.UserNotBlank;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java
index 5542be8c25f0..1a6c634ed480 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java
@@ -1,6 +1,6 @@
package com.baeldung.javaxval.javabeanconstraints.entities;
-import javax.validation.constraints.NotBlank;
+import jakarta.validation.constraints.NotBlank;
public class UserNotBlank {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java
index e3dbe27b0e8f..0e01c4138858 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java
@@ -1,6 +1,6 @@
package com.baeldung.javaxval.javabeanconstraints.entities;
-import javax.validation.constraints.NotEmpty;
+import jakarta.validation.constraints.NotEmpty;
public class UserNotEmpty {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java
index b3a0f90d3607..39164e2f6bda 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java
@@ -1,6 +1,6 @@
package com.baeldung.javaxval.javabeanconstraints.entities;
-import javax.validation.constraints.NotNull;
+import jakarta.validation.constraints.NotNull;
public class UserNotNull {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/CompleteInfo.java b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/CompleteInfo.java
index 4ecdc3c5f1c5..22c0b01ddf9a 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/CompleteInfo.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/CompleteInfo.java
@@ -1,6 +1,6 @@
package com.baeldung.javaxval.validationgroup;
-import javax.validation.GroupSequence;
+import jakarta.validation.GroupSequence;
@GroupSequence({ BasicInfo.class, AdvanceInfo.class })
public interface CompleteInfo {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/RegistrationForm.java b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/RegistrationForm.java
index a30a074556ec..2f759d633d6b 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/RegistrationForm.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/RegistrationForm.java
@@ -1,7 +1,7 @@
package com.baeldung.javaxval.validationgroup;
-import javax.validation.constraints.Email;
-import javax.validation.constraints.NotBlank;
+import jakarta.validation.constraints.Email;
+import jakarta.validation.constraints.NotBlank;
public class RegistrationForm {
@NotBlank(groups = BasicInfo.class)
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java b/javaxval/src/test/java/com/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java
index 3e60fa7acd72..132dddad5d5b 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java
@@ -6,10 +6,10 @@
import java.util.Collections;
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
-import javax.validation.ValidatorFactory;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
+import jakarta.validation.ValidatorFactory;
import org.junit.Before;
import org.junit.Test;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java
index 801d7966a5d4..a149a3a6fe35 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java
@@ -4,9 +4,9 @@
import org.junit.BeforeClass;
import org.junit.Test;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import java.math.BigDecimal;
import java.util.Set;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/constraint/composition/ConstraintCompositionUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/constraint/composition/ConstraintCompositionUnitTest.java
index 6c2b8f801c0f..918944cd5f72 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/constraint/composition/ConstraintCompositionUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/constraint/composition/ConstraintCompositionUnitTest.java
@@ -5,11 +5,11 @@
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.ConstraintViolationException;
-import javax.validation.Validation;
-import javax.validation.Validator;
-import javax.validation.ValidatorFactory;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.ConstraintViolationException;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
+import jakarta.validation.ValidatorFactory;
import org.junit.Before;
import org.junit.Test;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java b/javaxval/src/test/java/com/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java
index d96b64144256..5c50fde7c602 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java
@@ -6,10 +6,10 @@
import java.util.OptionalInt;
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
-import javax.validation.ValidatorFactory;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
+import jakarta.validation.ValidatorFactory;
import com.baeldung.javaxval.container.validation.valueextractors.ProfileValueExtractor;
import org.junit.Before;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java
index 524f8eec3603..7ccd840e8cae 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java
@@ -4,9 +4,9 @@
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import org.junit.BeforeClass;
import org.junit.Test;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java
index 805d40ee5e7b..0556f8883232 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java
@@ -6,9 +6,9 @@
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import org.junit.BeforeClass;
import org.junit.Test;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java
index 150da5d83bac..c7eb740d8666 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java
@@ -4,9 +4,9 @@
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import org.junit.BeforeClass;
import org.junit.Test;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/enums/demo/CustomerUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/enums/demo/CustomerUnitTest.java
index 02a49f50fa0a..c4380f75fa48 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/enums/demo/CustomerUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/enums/demo/CustomerUnitTest.java
@@ -5,9 +5,9 @@
import java.util.Set;
import java.util.function.Predicate;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import org.junit.BeforeClass;
import org.junit.Test;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotBlankUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotBlankUnitTest.java
index 4cb87e8e270c..68e48de41d36 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotBlankUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotBlankUnitTest.java
@@ -4,9 +4,9 @@
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import com.baeldung.javaxval.javabeanconstraints.entities.UserNotBlank;
import org.junit.BeforeClass;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotEmptyUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotEmptyUnitTest.java
index eb76ac260c20..bd83d3060124 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotEmptyUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotEmptyUnitTest.java
@@ -4,9 +4,9 @@
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import com.baeldung.javaxval.javabeanconstraints.entities.UserNotEmpty;
import org.junit.BeforeClass;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotNullUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotNullUnitTest.java
index f0280000de42..36874f4f21bd 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotNullUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotNullUnitTest.java
@@ -4,9 +4,9 @@
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import com.baeldung.javaxval.javabeanconstraints.entities.UserNotNull;
import org.junit.BeforeClass;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java
index 333370332825..52aadf80b05b 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java
@@ -4,9 +4,9 @@
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import org.junit.BeforeClass;
import org.junit.Test;
diff --git a/jaxb/pom.xml b/jaxb/pom.xml
index a7f0324bc016..ac448d2d62c9 100644
--- a/jaxb/pom.xml
+++ b/jaxb/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jaxb
- 0.0.1-SNAPSHOT
jaxb
diff --git a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java
index 18960b1d9ef6..9117bb621e84 100644
--- a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java
+++ b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java
@@ -48,7 +48,7 @@ public void marshal() throws JAXBException, IOException {
}
@Test
- public void unMashal() throws JAXBException, IOException {
+ public void unmarshal() throws JAXBException, IOException {
Unmarshaller unmarshaller = context.createUnmarshaller();
String bookFile = this.getClass().getResource("/book.xml").getFile();
Book unMarshallerbook = (Book) unmarshaller.unmarshal(new FileReader(bookFile));
diff --git a/jenkins-modules/plugins/pom.xml b/jenkins-modules/plugins/pom.xml
index 7f88382e2235..42add1664e4a 100644
--- a/jenkins-modules/plugins/pom.xml
+++ b/jenkins-modules/plugins/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
plugins
- 1.0-SNAPSHOT
plugins
hpi
A sample Jenkins Hello World plugin
diff --git a/jersey/pom.xml b/jersey/pom.xml
index 9a212c6da1cd..005fa85077d1 100644
--- a/jersey/pom.xml
+++ b/jersey/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jersey
- 0.0.1-SNAPSHOT
jersey
war
diff --git a/jetbrains/pom.xml b/jetbrains/pom.xml
index a10fd3b91366..ec46dc54f0af 100644
--- a/jetbrains/pom.xml
+++ b/jetbrains/pom.xml
@@ -7,7 +7,6 @@
1.0-SNAPSHOT
jetbrains
jar
- http://maven.apache.org
com.baeldung
diff --git a/jgit/pom.xml b/jgit/pom.xml
index 91881fbec8fb..4e8880809740 100644
--- a/jgit/pom.xml
+++ b/jgit/pom.xml
@@ -4,10 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jgit
- 1.0-SNAPSHOT
jgit
jar
- http://maven.apache.org
com.baeldung
@@ -15,14 +13,6 @@
1.0.0-SNAPSHOT
-
-
- jgit-repository
- https://repo.eclipse.org/content/groups/releases/
-
-
-
-
org.eclipse.jgit
@@ -36,7 +26,6 @@
-
4.5.0.201609210915-r
diff --git a/jhipster-5/bookstore-monolith/.yo-rc.json b/jhipster-5/bookstore-monolith/.yo-rc.json
deleted file mode 100644
index d852aeeddcd6..000000000000
--- a/jhipster-5/bookstore-monolith/.yo-rc.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "generator-jhipster": {
- "promptValues": {
- "packageName": "com.baeldung.jhipster5"
- },
- "jhipsterVersion": "5.8.2",
- "applicationType": "monolith",
- "baseName": "Bookstore",
- "packageName": "com.baeldung.jhipster5",
- "packageFolder": "com/baeldung/jhipster5",
- "serverPort": "8080",
- "authenticationType": "jwt",
- "cacheProvider": "no",
- "websocket": false,
- "databaseType": "sql",
- "devDatabaseType": "h2Memory",
- "prodDatabaseType": "mysql",
- "searchEngine": false,
- "messageBroker": false,
- "serviceDiscoveryType": false,
- "buildTool": "maven",
- "enableSwaggerCodegen": false,
- "jwtSecretKey": "NDJmOTVlZjI2NzhlZDRjNmVkNTM1NDE2NjkyNDljZDJiNzBlMjI5YmZjMjY3MzdjZmZlMjI3NjE4OTRkNzc5MWYzNDNlYWMzYmJjOWRmMjc5ZWQyZTZmOWZkOTMxZWZhNWE1MTVmM2U2NjFmYjhlNDc2Y2Q3NzliMGY0YzFkNmI=",
- "clientFramework": "angularX",
- "useSass": true,
- "clientPackageManager": "npm",
- "testFrameworks": [],
- "jhiPrefix": "jhi",
- "entitySuffix": "",
- "dtoSuffix": "DTO",
- "otherModules": [],
- "enableTranslation": false
- }
-}
diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/audit/package-info.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/audit/package-info.java
deleted file mode 100644
index 49a2a73a6163..000000000000
--- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/audit/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Audit specific code.
- */
-package com.baeldung.jhipster5.config.audit;
diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/package-info.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/package-info.java
deleted file mode 100644
index eba92a598e67..000000000000
--- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * JPA domain objects.
- */
-package com.baeldung.jhipster5.domain;
diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/package-info.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/package-info.java
deleted file mode 100644
index a5002eb2015d..000000000000
--- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Spring Data JPA repositories.
- */
-package com.baeldung.jhipster5.repository;
diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/package-info.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/package-info.java
deleted file mode 100644
index 87951796ead0..000000000000
--- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Data Transfer Objects.
- */
-package com.baeldung.jhipster5.service.dto;
diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/package-info.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/package-info.java
deleted file mode 100644
index a54ed5cca0fd..000000000000
--- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Service layer beans.
- */
-package com.baeldung.jhipster5.service;
diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/package-info.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/package-info.java
deleted file mode 100644
index 75bf6840f622..000000000000
--- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Spring MVC REST controllers.
- */
-package com.baeldung.jhipster5.web.rest;
diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/logs/logs.component.spec.ts b/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/logs/logs.component.spec.ts
deleted file mode 100644
index def356c0f2cc..000000000000
--- a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/logs/logs.component.spec.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { ComponentFixture, TestBed, async } from '@angular/core/testing';
-import { of } from 'rxjs';
-import { HttpHeaders, HttpResponse } from '@angular/common/http';
-
-import { BookstoreTestModule } from '../../../test.module';
-import { LogsComponent } from 'app/admin/logs/logs.component';
-import { LogsService } from 'app/admin/logs/logs.service';
-import { ITEMS_PER_PAGE } from 'app/shared';
-import { Log } from 'app/admin';
-
-describe('Component Tests', () => {
- describe('LogsComponent', () => {
- let comp: LogsComponent;
- let fixture: ComponentFixture;
- let service: LogsService;
-
- beforeEach(async(() => {
- TestBed.configureTestingModule({
- imports: [BookstoreTestModule],
- declarations: [LogsComponent],
- providers: [LogsService]
- })
- .overrideTemplate(LogsComponent, '')
- .compileComponents();
- }));
-
- beforeEach(() => {
- fixture = TestBed.createComponent(LogsComponent);
- comp = fixture.componentInstance;
- service = fixture.debugElement.injector.get(LogsService);
- });
-
- describe('OnInit', () => {
- it('should set all default values correctly', () => {
- expect(comp.filter).toBe('');
- expect(comp.orderProp).toBe('name');
- expect(comp.reverse).toBe(false);
- });
- it('Should call load all on init', () => {
- // GIVEN
- const headers = new HttpHeaders().append('link', 'link;link');
- const log = new Log('main', 'WARN');
- spyOn(service, 'findAll').and.returnValue(
- of(
- new HttpResponse({
- body: [log],
- headers
- })
- )
- );
-
- // WHEN
- comp.ngOnInit();
-
- // THEN
- expect(service.findAll).toHaveBeenCalled();
- expect(comp.loggers[0]).toEqual(jasmine.objectContaining(log));
- });
- });
- describe('change log level', () => {
- it('should change log level correctly', () => {
- // GIVEN
- const log = new Log('main', 'ERROR');
- spyOn(service, 'changeLevel').and.returnValue(of(new HttpResponse()));
- spyOn(service, 'findAll').and.returnValue(of(new HttpResponse({ body: [log] })));
-
- // WHEN
- comp.changeLevel('main', 'ERROR');
-
- // THEN
- expect(service.changeLevel).toHaveBeenCalled();
- expect(service.findAll).toHaveBeenCalled();
- expect(comp.loggers[0]).toEqual(jasmine.objectContaining(log));
- });
- });
- });
-});
diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/logs/logs.service.spec.ts b/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/logs/logs.service.spec.ts
deleted file mode 100644
index c34833922e99..000000000000
--- a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/logs/logs.service.spec.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { TestBed } from '@angular/core/testing';
-
-import { LogsService } from 'app/admin/logs/logs.service';
-import { Log } from 'app/admin/logs/log.model';
-import { SERVER_API_URL } from 'app/app.constants';
-import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
-
-describe('Service Tests', () => {
- describe('Logs Service', () => {
- let service: LogsService;
- let httpMock;
-
- beforeEach(() => {
- TestBed.configureTestingModule({
- imports: [HttpClientTestingModule]
- });
-
- service = TestBed.get(LogsService);
- httpMock = TestBed.get(HttpTestingController);
- });
-
- afterEach(() => {
- httpMock.verify();
- });
-
- describe('Service methods', () => {
- it('should call correct URL', () => {
- service.findAll().subscribe(() => {});
-
- const req = httpMock.expectOne({ method: 'GET' });
- const resourceUrl = SERVER_API_URL + 'management/logs';
- expect(req.request.url).toEqual(resourceUrl);
- });
-
- it('should return Logs', () => {
- const log = new Log('main', 'ERROR');
-
- service.findAll().subscribe(received => {
- expect(received.body[0]).toEqual(log);
- });
-
- const req = httpMock.expectOne({ method: 'GET' });
- req.flush([log]);
- });
-
- it('should change log level', () => {
- const log = new Log('main', 'ERROR');
-
- service.changeLevel(log).subscribe(received => {
- expect(received.body[0]).toEqual(log);
- });
-
- const req = httpMock.expectOne({ method: 'PUT' });
- req.flush([log]);
- });
- });
- });
-});
diff --git a/jhipster-5/README.md b/jhipster-6/README.md
similarity index 89%
rename from jhipster-5/README.md
rename to jhipster-6/README.md
index ba05641af0c0..9db409a03227 100644
--- a/jhipster-5/README.md
+++ b/jhipster-6/README.md
@@ -1,3 +1,3 @@
-## JHipster 5
+## JHipster 6
This module contains articles about JHipster 5. This is an aggregator module, articles are in the relevant submodules.
diff --git a/jhipster-5/bookstore-monolith/.editorconfig b/jhipster-6/bookstore-monolith/.editorconfig
similarity index 100%
rename from jhipster-5/bookstore-monolith/.editorconfig
rename to jhipster-6/bookstore-monolith/.editorconfig
diff --git a/jhipster-5/bookstore-monolith/.gitattributes b/jhipster-6/bookstore-monolith/.gitattributes
similarity index 100%
rename from jhipster-5/bookstore-monolith/.gitattributes
rename to jhipster-6/bookstore-monolith/.gitattributes
diff --git a/jhipster-5/bookstore-monolith/.gitignore b/jhipster-6/bookstore-monolith/.gitignore
similarity index 100%
rename from jhipster-5/bookstore-monolith/.gitignore
rename to jhipster-6/bookstore-monolith/.gitignore
diff --git a/jhipster-5/bookstore-monolith/.huskyrc b/jhipster-6/bookstore-monolith/.huskyrc
similarity index 100%
rename from jhipster-5/bookstore-monolith/.huskyrc
rename to jhipster-6/bookstore-monolith/.huskyrc
diff --git a/jhipster-5/bookstore-monolith/.jhipster/Book.json b/jhipster-6/bookstore-monolith/.jhipster/Book.json
similarity index 100%
rename from jhipster-5/bookstore-monolith/.jhipster/Book.json
rename to jhipster-6/bookstore-monolith/.jhipster/Book.json
diff --git a/jhipster-5/bookstore-monolith/.mvn/wrapper/MavenWrapperDownloader.java b/jhipster-6/bookstore-monolith/.mvn/wrapper/MavenWrapperDownloader.java
similarity index 100%
rename from jhipster-5/bookstore-monolith/.mvn/wrapper/MavenWrapperDownloader.java
rename to jhipster-6/bookstore-monolith/.mvn/wrapper/MavenWrapperDownloader.java
diff --git a/jhipster-5/bookstore-monolith/.mvn/wrapper/maven-wrapper.jar b/jhipster-6/bookstore-monolith/.mvn/wrapper/maven-wrapper.jar
similarity index 100%
rename from jhipster-5/bookstore-monolith/.mvn/wrapper/maven-wrapper.jar
rename to jhipster-6/bookstore-monolith/.mvn/wrapper/maven-wrapper.jar
diff --git a/jhipster-5/bookstore-monolith/.mvn/wrapper/maven-wrapper.properties b/jhipster-6/bookstore-monolith/.mvn/wrapper/maven-wrapper.properties
similarity index 100%
rename from jhipster-5/bookstore-monolith/.mvn/wrapper/maven-wrapper.properties
rename to jhipster-6/bookstore-monolith/.mvn/wrapper/maven-wrapper.properties
diff --git a/jhipster-5/bookstore-monolith/.prettierignore b/jhipster-6/bookstore-monolith/.prettierignore
similarity index 100%
rename from jhipster-5/bookstore-monolith/.prettierignore
rename to jhipster-6/bookstore-monolith/.prettierignore
diff --git a/jhipster-5/bookstore-monolith/.prettierrc b/jhipster-6/bookstore-monolith/.prettierrc
similarity index 100%
rename from jhipster-5/bookstore-monolith/.prettierrc
rename to jhipster-6/bookstore-monolith/.prettierrc
diff --git a/jhipster-6/bookstore-monolith/.yo-rc.json b/jhipster-6/bookstore-monolith/.yo-rc.json
new file mode 100644
index 000000000000..3ec14d8ada6e
--- /dev/null
+++ b/jhipster-6/bookstore-monolith/.yo-rc.json
@@ -0,0 +1,36 @@
+{
+ "generator-jhipster": {
+ "promptValues": {
+ "packageName": "com.baeldung.jhipster5"
+ },
+ "jhipsterVersion": "6.0.0",
+ "applicationType": "monolith",
+ "baseName": "Bookstore",
+ "packageName": "com.baeldung.jhipster5",
+ "packageFolder": "com/baeldung/jhipster5",
+ "serverPort": "8080",
+ "authenticationType": "jwt",
+ "cacheProvider": "no",
+ "websocket": false,
+ "databaseType": "sql",
+ "devDatabaseType": "h2Memory",
+ "prodDatabaseType": "mysql",
+ "searchEngine": false,
+ "messageBroker": false,
+ "serviceDiscoveryType": false,
+ "buildTool": "maven",
+ "enableSwaggerCodegen": false,
+ "jwtSecretKey": "NDJmOTVlZjI2NzhlZDRjNmVkNTM1NDE2NjkyNDljZDJiNzBlMjI5YmZjMjY3MzdjZmZlMjI3NjE4OTRkNzc5MWYzNDNlYWMzYmJjOWRmMjc5ZWQyZTZmOWZkOTMxZWZhNWE1MTVmM2U2NjFmYjhlNDc2Y2Q3NzliMGY0YzFkNmI=",
+ "clientFramework": "angularX",
+ "useSass": true,
+ "clientPackageManager": "npm",
+ "testFrameworks": [],
+ "jhiPrefix": "jhi",
+ "entitySuffix": "",
+ "dtoSuffix": "DTO",
+ "otherModules": [],
+ "enableTranslation": false,
+ "enableHibernateCache": false,
+ "clientTheme": "none"
+ }
+}
\ No newline at end of file
diff --git a/jhipster-5/bookstore-monolith/README.md b/jhipster-6/bookstore-monolith/README.md
similarity index 100%
rename from jhipster-5/bookstore-monolith/README.md
rename to jhipster-6/bookstore-monolith/README.md
diff --git a/jhipster-5/bookstore-monolith/angular.json b/jhipster-6/bookstore-monolith/angular.json
similarity index 100%
rename from jhipster-5/bookstore-monolith/angular.json
rename to jhipster-6/bookstore-monolith/angular.json
diff --git a/jhipster-5/bookstore-monolith/mvnw b/jhipster-6/bookstore-monolith/mvnw
old mode 100755
new mode 100644
similarity index 100%
rename from jhipster-5/bookstore-monolith/mvnw
rename to jhipster-6/bookstore-monolith/mvnw
diff --git a/jhipster-5/bookstore-monolith/mvnw.cmd b/jhipster-6/bookstore-monolith/mvnw.cmd
similarity index 100%
rename from jhipster-5/bookstore-monolith/mvnw.cmd
rename to jhipster-6/bookstore-monolith/mvnw.cmd
diff --git a/jhipster-5/bookstore-monolith/package.json b/jhipster-6/bookstore-monolith/package.json
similarity index 99%
rename from jhipster-5/bookstore-monolith/package.json
rename to jhipster-6/bookstore-monolith/package.json
index 46b920edb3cf..76b74a431204 100644
--- a/jhipster-5/bookstore-monolith/package.json
+++ b/jhipster-6/bookstore-monolith/package.json
@@ -51,7 +51,7 @@
"file-loader": "3.0.1",
"fork-ts-checker-webpack-plugin": "0.5.2",
"friendly-errors-webpack-plugin": "1.7.0",
- "generator-jhipster": "5.8.2",
+ "generator-jhipster": "6.0.0",
"html-loader": "0.5.5",
"html-webpack-plugin": "3.2.0",
"husky": "1.3.1",
diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-6/bookstore-monolith/pom.xml
similarity index 89%
rename from jhipster-5/bookstore-monolith/pom.xml
rename to jhipster-6/bookstore-monolith/pom.xml
index ccaa802a3973..f719baab8b5c 100644
--- a/jhipster-5/bookstore-monolith/pom.xml
+++ b/jhipster-6/bookstore-monolith/pom.xml
@@ -2,14 +2,14 @@
4.0.0
- com.baeldung.jhipster5
+ com.baeldung.jhipster6
bookstore-monolith
0.0.1-SNAPSHOT
war
bookstore-monolith
- jhipster-5
+ jhipster-6
com.baeldung.jhipster
1.0.0-SNAPSHOT
@@ -41,8 +41,25 @@
io.github.jhipster
jhipster-framework
+ 3.0.1
+
+
+ jakarta.xml.bind
+ jakarta.xml.bind-api
+ 4.0.0
+
+
+
+ org.glassfish.jaxb
+ jaxb-runtime
+ 4.0.0
+
+
+
+
+
com.fasterxml.jackson.datatype
jackson-datatype-hibernate5
@@ -78,10 +95,10 @@
io.springfox
springfox-bean-validators
-
- com.mattbertolini
- liquibase-slf4j
-
+
+
+
+
com.zaxxer
HikariCP
@@ -94,6 +111,10 @@
org.apache.commons
commons-lang3
+
+ mysql
+ mysql-connector-java
+
org.assertj
assertj-core
@@ -120,9 +141,13 @@
net.logstash.logback
logstash-logback-encoder
+
+
+
+
org.mapstruct
- mapstruct-jdk8
+ mapstruct
org.mapstruct
@@ -269,6 +294,11 @@
hibernate-jpamodelgen
${hibernate.version}
+
+ org.glassfish.jaxb
+ jaxb-runtime
+ ${jaxb-runtime.version}
+
@@ -492,9 +522,8 @@
[${maven.version},)
-
- You are running an incompatible version of Java. JHipster requires JDK ${java.version}
- [1.8,1.9)
+ You are running an incompatible version of Java. JHipster supports JDK 11.
+ [${java.version},)
@@ -681,6 +710,9 @@
npm
+
+ install --legacy-peer-deps
+
webpack build dev
@@ -1023,135 +1055,12 @@
-
-
- default-first
-
-
-
-
- com.github.eirslett
- frontend-maven-plugin
-
-
-
- install node and npm
- none
-
-
- npm install
- none
-
-
- webpack build dev
- none
-
-
- webpack build test
- none
-
-
-
-
-
-
-
- default-second
-
-
-
-
- com.github.eirslett
- frontend-maven-plugin
-
-
-
- install node and npm
- none
-
-
- npm install
- none
-
-
- webpack build dev
- none
-
-
- webpack build test
- none
-
-
-
-
-
-
-
- integration-lite-first
-
-
-
- com.github.eirslett
- frontend-maven-plugin
-
-
-
- install node and npm
- none
-
-
- npm install
- none
-
-
- webpack build dev
- none
-
-
- webpack build test
- none
-
-
-
-
-
-
-
- integration-lite-second
-
-
-
- com.github.eirslett
- frontend-maven-plugin
-
-
-
- install node and npm
- none
-
-
- npm install
- none
-
-
- webpack build dev
- none
-
-
- webpack build test
- none
-
-
-
-
-
-
3.0.0
- 1.8
+ 11
2.12.6
v10.15.0
6.4.1
@@ -1168,34 +1077,36 @@
- 2.1.1
+ 3.0.1
- 2.7.8
+ 2.7.5
- 5.2.17.Final
+ 5.3.9.Final
- 3.22.0-GA
+ 3.23.1-GA
- 3.5.5
+ 3.6.3
3.6
+ 5.1.5.RELEASE
2.0.1.Final
- 1.2.0.Final
+ 2.3.2
+ 1.3.0.Final
3.1.0
3.8.0
2.10
- 3.0.0-M2
+ 3.0.0-M1
2.2.1
3.1.0
- 2.22.2
+ 3.0.0-M3
3.2.2
0.9.11
- 1.6
+ 1.7.6
0.8.2
1.0.0
3.4.2
diff --git a/jhipster-5/bookstore-monolith/postcss.config.js b/jhipster-6/bookstore-monolith/postcss.config.js
similarity index 100%
rename from jhipster-5/bookstore-monolith/postcss.config.js
rename to jhipster-6/bookstore-monolith/postcss.config.js
diff --git a/jhipster-5/bookstore-monolith/proxy.conf.json b/jhipster-6/bookstore-monolith/proxy.conf.json
similarity index 100%
rename from jhipster-5/bookstore-monolith/proxy.conf.json
rename to jhipster-6/bookstore-monolith/proxy.conf.json
diff --git a/jhipster-5/bookstore-monolith/src/main/docker/.dockerignore b/jhipster-6/bookstore-monolith/src/main/docker/.dockerignore
similarity index 100%
rename from jhipster-5/bookstore-monolith/src/main/docker/.dockerignore
rename to jhipster-6/bookstore-monolith/src/main/docker/.dockerignore
diff --git a/jhipster-5/bookstore-monolith/src/main/docker/Dockerfile b/jhipster-6/bookstore-monolith/src/main/docker/Dockerfile
similarity index 100%
rename from jhipster-5/bookstore-monolith/src/main/docker/Dockerfile
rename to jhipster-6/bookstore-monolith/src/main/docker/Dockerfile
diff --git a/jhipster-5/bookstore-monolith/src/main/docker/app.yml b/jhipster-6/bookstore-monolith/src/main/docker/app.yml
similarity index 100%
rename from jhipster-5/bookstore-monolith/src/main/docker/app.yml
rename to jhipster-6/bookstore-monolith/src/main/docker/app.yml
diff --git a/jhipster-5/bookstore-monolith/src/main/docker/entrypoint.sh b/jhipster-6/bookstore-monolith/src/main/docker/entrypoint.sh
similarity index 100%
rename from jhipster-5/bookstore-monolith/src/main/docker/entrypoint.sh
rename to jhipster-6/bookstore-monolith/src/main/docker/entrypoint.sh
diff --git a/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/dashboards/JVM.json b/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/dashboards/JVM.json
new file mode 100644
index 000000000000..b299032c99e3
--- /dev/null
+++ b/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/dashboards/JVM.json
@@ -0,0 +1,3778 @@
+{
+ "annotations": {
+ "list": [
+ {
+ "builtIn": 1,
+ "datasource": "-- Grafana --",
+ "enable": true,
+ "hide": true,
+ "iconColor": "rgba(0, 211, 255, 1)",
+ "limit": 100,
+ "name": "Annotations & Alerts",
+ "showIn": 0,
+ "type": "dashboard"
+ },
+ {
+ "datasource": "Prometheus",
+ "enable": true,
+ "expr": "resets(process_uptime_seconds{application=\"$application\", instance=\"$instance\"}[1m]) > 0",
+ "iconColor": "rgba(255, 96, 96, 1)",
+ "name": "Restart Detection",
+ "showIn": 0,
+ "step": "1m",
+ "tagKeys": "restart-tag",
+ "textFormat": "uptime reset",
+ "titleFormat": "Restart"
+ }
+ ]
+ },
+ "description": "Dashboard for Micrometer instrumented applications (Java, Spring Boot, Micronaut)",
+ "editable": true,
+ "gnetId": 4701,
+ "graphTooltip": 1,
+ "iteration": 1553765841423,
+ "links": [],
+ "panels": [
+ {
+ "content": "\n# Acknowledgments\n\nThank you to [Michael Weirauch](https://twitter.com/emwexx) for creating this dashboard: see original JVM (Micrometer) dashboard at [https://grafana.com/dashboards/4701](https://grafana.com/dashboards/4701)\n\n\n\n",
+ "gridPos": {
+ "h": 3,
+ "w": 24,
+ "x": 0,
+ "y": 0
+ },
+ "id": 141,
+ "links": [],
+ "mode": "markdown",
+ "timeFrom": null,
+ "timeShift": null,
+ "title": "Acknowledgments",
+ "type": "text"
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 3
+ },
+ "id": 125,
+ "panels": [],
+ "repeat": null,
+ "title": "Quick Facts",
+ "type": "row"
+ },
+ {
+ "cacheTimeout": null,
+ "colorBackground": false,
+ "colorValue": true,
+ "colors": ["rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)"],
+ "datasource": "Prometheus",
+ "decimals": 1,
+ "editable": true,
+ "error": false,
+ "format": "s",
+ "gauge": {
+ "maxValue": 100,
+ "minValue": 0,
+ "show": false,
+ "thresholdLabels": false,
+ "thresholdMarkers": true
+ },
+ "gridPos": {
+ "h": 3,
+ "w": 6,
+ "x": 0,
+ "y": 4
+ },
+ "height": "",
+ "id": 63,
+ "interval": null,
+ "links": [],
+ "mappingType": 1,
+ "mappingTypes": [
+ {
+ "name": "value to text",
+ "value": 1
+ },
+ {
+ "name": "range to text",
+ "value": 2
+ }
+ ],
+ "maxDataPoints": 100,
+ "nullPointMode": "connected",
+ "nullText": null,
+ "postfix": "",
+ "postfixFontSize": "50%",
+ "prefix": "",
+ "prefixFontSize": "70%",
+ "rangeMaps": [
+ {
+ "from": "null",
+ "text": "N/A",
+ "to": "null"
+ }
+ ],
+ "sparkline": {
+ "fillColor": "rgba(31, 118, 189, 0.18)",
+ "full": false,
+ "lineColor": "rgb(31, 120, 193)",
+ "show": false
+ },
+ "tableColumn": "",
+ "targets": [
+ {
+ "expr": "process_uptime_seconds{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "",
+ "metric": "",
+ "refId": "A",
+ "step": 14400
+ }
+ ],
+ "thresholds": "",
+ "title": "Uptime",
+ "type": "singlestat",
+ "valueFontSize": "80%",
+ "valueMaps": [
+ {
+ "op": "=",
+ "text": "N/A",
+ "value": "null"
+ }
+ ],
+ "valueName": "current"
+ },
+ {
+ "cacheTimeout": null,
+ "colorBackground": false,
+ "colorValue": true,
+ "colors": ["rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)"],
+ "datasource": "Prometheus",
+ "decimals": null,
+ "editable": true,
+ "error": false,
+ "format": "dateTimeAsIso",
+ "gauge": {
+ "maxValue": 100,
+ "minValue": 0,
+ "show": false,
+ "thresholdLabels": false,
+ "thresholdMarkers": true
+ },
+ "gridPos": {
+ "h": 3,
+ "w": 6,
+ "x": 6,
+ "y": 4
+ },
+ "height": "",
+ "id": 92,
+ "interval": null,
+ "links": [],
+ "mappingType": 1,
+ "mappingTypes": [
+ {
+ "name": "value to text",
+ "value": 1
+ },
+ {
+ "name": "range to text",
+ "value": 2
+ }
+ ],
+ "maxDataPoints": 100,
+ "nullPointMode": "connected",
+ "nullText": null,
+ "postfix": "",
+ "postfixFontSize": "50%",
+ "prefix": "",
+ "prefixFontSize": "70%",
+ "rangeMaps": [
+ {
+ "from": "null",
+ "text": "N/A",
+ "to": "null"
+ }
+ ],
+ "sparkline": {
+ "fillColor": "rgba(31, 118, 189, 0.18)",
+ "full": false,
+ "lineColor": "rgb(31, 120, 193)",
+ "show": false
+ },
+ "tableColumn": "",
+ "targets": [
+ {
+ "expr": "process_start_time_seconds{application=\"$application\", instance=\"$instance\"}*1000",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "",
+ "metric": "",
+ "refId": "A",
+ "step": 14400
+ }
+ ],
+ "thresholds": "",
+ "title": "Start time",
+ "type": "singlestat",
+ "valueFontSize": "70%",
+ "valueMaps": [
+ {
+ "op": "=",
+ "text": "N/A",
+ "value": "null"
+ }
+ ],
+ "valueName": "current"
+ },
+ {
+ "cacheTimeout": null,
+ "colorBackground": false,
+ "colorValue": true,
+ "colors": ["rgba(50, 172, 45, 0.97)", "rgba(237, 129, 40, 0.89)", "rgba(245, 54, 54, 0.9)"],
+ "datasource": "Prometheus",
+ "decimals": 2,
+ "editable": true,
+ "error": false,
+ "format": "percent",
+ "gauge": {
+ "maxValue": 100,
+ "minValue": 0,
+ "show": false,
+ "thresholdLabels": false,
+ "thresholdMarkers": true
+ },
+ "gridPos": {
+ "h": 3,
+ "w": 6,
+ "x": 12,
+ "y": 4
+ },
+ "id": 65,
+ "interval": null,
+ "links": [],
+ "mappingType": 1,
+ "mappingTypes": [
+ {
+ "name": "value to text",
+ "value": 1
+ },
+ {
+ "name": "range to text",
+ "value": 2
+ }
+ ],
+ "maxDataPoints": 100,
+ "nullPointMode": "connected",
+ "nullText": null,
+ "postfix": "",
+ "postfixFontSize": "50%",
+ "prefix": "",
+ "prefixFontSize": "70%",
+ "rangeMaps": [
+ {
+ "from": "null",
+ "text": "N/A",
+ "to": "null"
+ }
+ ],
+ "sparkline": {
+ "fillColor": "rgba(31, 118, 189, 0.18)",
+ "full": false,
+ "lineColor": "rgb(31, 120, 193)",
+ "show": false
+ },
+ "tableColumn": "",
+ "targets": [
+ {
+ "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"})*100/sum(jvm_memory_max_bytes{application=\"$application\",instance=\"$instance\", area=\"heap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "",
+ "refId": "A",
+ "step": 14400
+ }
+ ],
+ "thresholds": "70,90",
+ "title": "Heap used",
+ "type": "singlestat",
+ "valueFontSize": "80%",
+ "valueMaps": [
+ {
+ "op": "=",
+ "text": "N/A",
+ "value": "null"
+ }
+ ],
+ "valueName": "current"
+ },
+ {
+ "cacheTimeout": null,
+ "colorBackground": false,
+ "colorValue": true,
+ "colors": ["rgba(50, 172, 45, 0.97)", "rgba(237, 129, 40, 0.89)", "rgba(245, 54, 54, 0.9)"],
+ "datasource": "Prometheus",
+ "decimals": 2,
+ "editable": true,
+ "error": false,
+ "format": "percent",
+ "gauge": {
+ "maxValue": 100,
+ "minValue": 0,
+ "show": false,
+ "thresholdLabels": false,
+ "thresholdMarkers": true
+ },
+ "gridPos": {
+ "h": 3,
+ "w": 6,
+ "x": 18,
+ "y": 4
+ },
+ "id": 75,
+ "interval": null,
+ "links": [],
+ "mappingType": 2,
+ "mappingTypes": [
+ {
+ "name": "value to text",
+ "value": 1
+ },
+ {
+ "name": "range to text",
+ "value": 2
+ }
+ ],
+ "maxDataPoints": 100,
+ "nullPointMode": "connected",
+ "nullText": null,
+ "postfix": "",
+ "postfixFontSize": "50%",
+ "prefix": "",
+ "prefixFontSize": "70%",
+ "rangeMaps": [
+ {
+ "from": "null",
+ "text": "N/A",
+ "to": "null"
+ },
+ {
+ "from": "-99999999999999999999999999999999",
+ "text": "N/A",
+ "to": "0"
+ }
+ ],
+ "sparkline": {
+ "fillColor": "rgba(31, 118, 189, 0.18)",
+ "full": false,
+ "lineColor": "rgb(31, 120, 193)",
+ "show": false
+ },
+ "tableColumn": "",
+ "targets": [
+ {
+ "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"})*100/sum(jvm_memory_max_bytes{application=\"$application\",instance=\"$instance\", area=\"nonheap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "",
+ "refId": "A",
+ "step": 14400
+ }
+ ],
+ "thresholds": "70,90",
+ "title": "Non-Heap used",
+ "type": "singlestat",
+ "valueFontSize": "80%",
+ "valueMaps": [
+ {
+ "op": "=",
+ "text": "N/A",
+ "value": "null"
+ },
+ {
+ "op": "=",
+ "text": "x",
+ "value": ""
+ }
+ ],
+ "valueName": "current"
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 7
+ },
+ "id": 126,
+ "panels": [],
+ "repeat": null,
+ "title": "I/O Overview",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 0,
+ "y": 8
+ },
+ "id": 111,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "sum(rate(http_server_requests_seconds_count{application=\"$application\", instance=\"$instance\"}[1m]))",
+ "format": "time_series",
+ "intervalFactor": 1,
+ "legendFormat": "HTTP",
+ "refId": "A"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Rate",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "decimals": null,
+ "format": "ops",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {
+ "HTTP": "#890f02",
+ "HTTP - 5xx": "#bf1b00"
+ },
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 8,
+ "y": 8
+ },
+ "id": 112,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "sum(rate(http_server_requests_seconds_count{application=\"$application\", instance=\"$instance\", status=~\"5..\"}[1m]))",
+ "format": "time_series",
+ "intervalFactor": 1,
+ "legendFormat": "HTTP - 5xx",
+ "refId": "A"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Errors",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "decimals": null,
+ "format": "ops",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 16,
+ "y": 8
+ },
+ "id": 113,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "sum(rate(http_server_requests_seconds_sum{application=\"$application\", instance=\"$instance\", status!~\"5..\"}[1m]))/sum(rate(http_server_requests_seconds_count{application=\"$application\", instance=\"$instance\", status!~\"5..\"}[1m]))",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 1,
+ "legendFormat": "HTTP - AVG",
+ "refId": "A"
+ },
+ {
+ "expr": "max(http_server_requests_seconds_max{application=\"$application\", instance=\"$instance\", status!~\"5..\"})",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 1,
+ "legendFormat": "HTTP - MAX",
+ "refId": "B"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Duration",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "format": "s",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 15
+ },
+ "id": 127,
+ "panels": [],
+ "repeat": null,
+ "title": "JVM Memory",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 0,
+ "y": 16
+ },
+ "id": 24,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "sum(jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "committed",
+ "refId": "B",
+ "step": 2400
+ },
+ {
+ "expr": "sum(jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "refId": "C",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "JVM Heap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 8,
+ "y": 16
+ },
+ "id": 25,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"})",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "sum(jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "committed",
+ "refId": "B",
+ "step": 2400
+ },
+ {
+ "expr": "sum(jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "refId": "C",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "JVM Non-Heap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 16,
+ "y": 16
+ },
+ "id": 26,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "sum(jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "committed",
+ "refId": "B",
+ "step": 2400
+ },
+ {
+ "expr": "sum(jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "refId": "C",
+ "step": 2400
+ },
+ {
+ "expr": "process_memory_vss_bytes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "hide": true,
+ "intervalFactor": 2,
+ "legendFormat": "vss",
+ "metric": "",
+ "refId": "D",
+ "step": 2400
+ },
+ {
+ "expr": "process_memory_rss_bytes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "rss",
+ "refId": "E",
+ "step": 2400
+ },
+ {
+ "expr": "process_memory_pss_bytes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "pss",
+ "refId": "F",
+ "step": 2400
+ },
+ {
+ "expr": "process_memory_swap_bytes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "swap",
+ "refId": "G",
+ "step": 2400
+ },
+ {
+ "expr": "process_memory_swappss_bytes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "swappss",
+ "refId": "H",
+ "step": 2400
+ },
+ {
+ "expr": "process_memory_pss_bytes{application=\"$application\", instance=\"$instance\"} + process_memory_swap_bytes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "phys (pss+swap)",
+ "refId": "I",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "JVM Total",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": "",
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 23
+ },
+ "id": 128,
+ "panels": [],
+ "repeat": null,
+ "title": "JVM Misc",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 0,
+ "y": 24
+ },
+ "id": 106,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "system_cpu_usage{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 1,
+ "legendFormat": "system",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "process_cpu_usage{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 1,
+ "legendFormat": "process",
+ "refId": "B"
+ },
+ {
+ "expr": "avg_over_time(process_cpu_usage{application=\"$application\", instance=\"$instance\"}[1h])",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 1,
+ "legendFormat": "process-1h",
+ "refId": "C"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "CPU",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 1,
+ "format": "percentunit",
+ "label": "",
+ "logBase": 1,
+ "max": "1",
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 6,
+ "y": 24
+ },
+ "id": 93,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "system_load_average_1m{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "system-1m",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "refId": "B"
+ },
+ {
+ "expr": "system_cpu_count{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "cpu",
+ "refId": "C"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Load",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 1,
+ "format": "short",
+ "label": "",
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 12,
+ "y": 24
+ },
+ "id": 32,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_threads_live{application=\"$application\", instance=\"$instance\"} or jvm_threads_live_threads{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "live",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "jvm_threads_daemon{application=\"$application\", instance=\"$instance\"} or jvm_threads_daemon_threads{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "daemon",
+ "metric": "",
+ "refId": "B",
+ "step": 2400
+ },
+ {
+ "expr": "jvm_threads_peak{application=\"$application\", instance=\"$instance\"} or jvm_threads_peak_threads{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "peak",
+ "refId": "C",
+ "step": 2400
+ },
+ {
+ "expr": "process_threads{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "process",
+ "refId": "D",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Threads",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 0,
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {
+ "blocked": "#bf1b00",
+ "new": "#fce2de",
+ "runnable": "#7eb26d",
+ "terminated": "#511749",
+ "timed-waiting": "#c15c17",
+ "waiting": "#eab839"
+ },
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 18,
+ "y": 24
+ },
+ "id": 124,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_threads_states_threads{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "{{state}}",
+ "refId": "A"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Thread States",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {
+ "debug": "#1F78C1",
+ "error": "#BF1B00",
+ "info": "#508642",
+ "trace": "#6ED0E0",
+ "warn": "#EAB839"
+ },
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 18,
+ "x": 0,
+ "y": 31
+ },
+ "height": "",
+ "id": 91,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "hideEmpty": false,
+ "hideZero": false,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": true,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [
+ {
+ "alias": "error",
+ "yaxis": 1
+ },
+ {
+ "alias": "warn",
+ "yaxis": 1
+ }
+ ],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "increase(logback_events_total{application=\"$application\", instance=\"$instance\"}[1m])",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "{{level}}",
+ "metric": "",
+ "refId": "A",
+ "step": 1200
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Log Events (1m)",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 0,
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 18,
+ "y": 31
+ },
+ "id": 61,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "process_open_fds{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 2,
+ "legendFormat": "open",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "process_max_fds{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "B",
+ "step": 2400
+ },
+ {
+ "expr": "process_files_open{application=\"$application\", instance=\"$instance\"} or process_files_open_files{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "open",
+ "refId": "C"
+ },
+ {
+ "expr": "process_files_max{application=\"$application\", instance=\"$instance\"} or process_files_max_files{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "refId": "D"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "File Descriptors",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 0,
+ "format": "short",
+ "label": null,
+ "logBase": 10,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 38
+ },
+ "id": 129,
+ "panels": [],
+ "repeat": "persistence_counts",
+ "title": "JVM Memory Pools (Heap)",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 0,
+ "y": 39
+ },
+ "id": 3,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "maxPerRow": 3,
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "repeat": "jvm_memory_pool_heap",
+ "scopedVars": {
+ "jvm_memory_pool_heap": {
+ "selected": false,
+ "text": "PS Eden Space",
+ "value": "PS Eden Space"
+ }
+ },
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "commited",
+ "metric": "",
+ "refId": "B",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "C",
+ "step": 1800
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "$jvm_memory_pool_heap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 8,
+ "y": 39
+ },
+ "id": 134,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "maxPerRow": 3,
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "repeat": null,
+ "repeatIteration": 1553765841423,
+ "repeatPanelId": 3,
+ "scopedVars": {
+ "jvm_memory_pool_heap": {
+ "selected": false,
+ "text": "PS Old Gen",
+ "value": "PS Old Gen"
+ }
+ },
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "commited",
+ "metric": "",
+ "refId": "B",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "C",
+ "step": 1800
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "$jvm_memory_pool_heap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 16,
+ "y": 39
+ },
+ "id": 135,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "maxPerRow": 3,
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "repeat": null,
+ "repeatIteration": 1553765841423,
+ "repeatPanelId": 3,
+ "scopedVars": {
+ "jvm_memory_pool_heap": {
+ "selected": false,
+ "text": "PS Survivor Space",
+ "value": "PS Survivor Space"
+ }
+ },
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "commited",
+ "metric": "",
+ "refId": "B",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "C",
+ "step": 1800
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "$jvm_memory_pool_heap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 46
+ },
+ "id": 130,
+ "panels": [],
+ "repeat": null,
+ "title": "JVM Memory Pools (Non-Heap)",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 0,
+ "y": 47
+ },
+ "id": 78,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "maxPerRow": 3,
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "repeat": "jvm_memory_pool_nonheap",
+ "scopedVars": {
+ "jvm_memory_pool_nonheap": {
+ "selected": false,
+ "text": "Metaspace",
+ "value": "Metaspace"
+ }
+ },
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "commited",
+ "metric": "",
+ "refId": "B",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "C",
+ "step": 1800
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "$jvm_memory_pool_nonheap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 8,
+ "y": 47
+ },
+ "id": 136,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "maxPerRow": 3,
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "repeat": null,
+ "repeatIteration": 1553765841423,
+ "repeatPanelId": 78,
+ "scopedVars": {
+ "jvm_memory_pool_nonheap": {
+ "selected": false,
+ "text": "Compressed Class Space",
+ "value": "Compressed Class Space"
+ }
+ },
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "commited",
+ "metric": "",
+ "refId": "B",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "C",
+ "step": 1800
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "$jvm_memory_pool_nonheap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 16,
+ "y": 47
+ },
+ "id": 137,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "maxPerRow": 3,
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "repeat": null,
+ "repeatIteration": 1553765841423,
+ "repeatPanelId": 78,
+ "scopedVars": {
+ "jvm_memory_pool_nonheap": {
+ "selected": false,
+ "text": "Code Cache",
+ "value": "Code Cache"
+ }
+ },
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "commited",
+ "metric": "",
+ "refId": "B",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "C",
+ "step": 1800
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "$jvm_memory_pool_nonheap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 54
+ },
+ "id": 131,
+ "panels": [],
+ "repeat": null,
+ "title": "Garbage Collection",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 0,
+ "y": 55
+ },
+ "id": 98,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "rate(jvm_gc_pause_seconds_count{application=\"$application\", instance=\"$instance\"}[1m])",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 2,
+ "legendFormat": "{{action}} ({{cause}})",
+ "refId": "A"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Collections",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "format": "ops",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": "",
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 8,
+ "y": 55
+ },
+ "id": 101,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "rate(jvm_gc_pause_seconds_sum{application=\"$application\", instance=\"$instance\"}[1m])/rate(jvm_gc_pause_seconds_count{application=\"$application\", instance=\"$instance\"}[1m])",
+ "format": "time_series",
+ "hide": false,
+ "instant": false,
+ "intervalFactor": 1,
+ "legendFormat": "avg {{action}} ({{cause}})",
+ "refId": "A"
+ },
+ {
+ "expr": "jvm_gc_pause_seconds_max{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "hide": false,
+ "instant": false,
+ "intervalFactor": 1,
+ "legendFormat": "max {{action}} ({{cause}})",
+ "refId": "B"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Pause Durations",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "format": "s",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": "",
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 16,
+ "y": 55
+ },
+ "id": 99,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "rate(jvm_gc_memory_allocated_bytes_total{application=\"$application\", instance=\"$instance\"}[1m])",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 1,
+ "legendFormat": "allocated",
+ "refId": "A"
+ },
+ {
+ "expr": "rate(jvm_gc_memory_promoted_bytes_total{application=\"$application\", instance=\"$instance\"}[1m])",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 1,
+ "legendFormat": "promoted",
+ "refId": "B"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Allocated/Promoted",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 62
+ },
+ "id": 132,
+ "panels": [],
+ "repeat": null,
+ "title": "Classloading",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 12,
+ "x": 0,
+ "y": 63
+ },
+ "id": 37,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_classes_loaded{application=\"$application\", instance=\"$instance\"} or jvm_classes_loaded_classes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "loaded",
+ "metric": "",
+ "refId": "A",
+ "step": 1200
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Classes loaded",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 12,
+ "x": 12,
+ "y": 63
+ },
+ "id": 38,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "delta(jvm_classes_loaded{application=\"$application\",instance=\"$instance\"}[5m]) or delta(jvm_classes_loaded_classes{application=\"$application\",instance=\"$instance\"}[5m])",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "delta",
+ "metric": "",
+ "refId": "A",
+ "step": 1200
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Class delta (5m)",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["ops", "short"],
+ "yaxes": [
+ {
+ "decimals": null,
+ "format": "short",
+ "label": "",
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 70
+ },
+ "id": 133,
+ "panels": [],
+ "repeat": null,
+ "title": "Buffer Pools",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 0,
+ "y": 71
+ },
+ "id": 33,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_buffer_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"direct\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "jvm_buffer_total_capacity_bytes{application=\"$application\", instance=\"$instance\", id=\"direct\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "capacity",
+ "metric": "",
+ "refId": "B",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Direct Buffers",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 6,
+ "y": 71
+ },
+ "id": 83,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_buffer_count{application=\"$application\", instance=\"$instance\", id=\"direct\"} or jvm_buffer_count_buffers{application=\"$application\", instance=\"$instance\", id=\"direct\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "count",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Direct Buffers",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 0,
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 12,
+ "y": 71
+ },
+ "id": 85,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_buffer_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"mapped\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "jvm_buffer_total_capacity_bytes{application=\"$application\", instance=\"$instance\", id=\"mapped\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "capacity",
+ "metric": "",
+ "refId": "B",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Mapped Buffers",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 18,
+ "y": 71
+ },
+ "id": 84,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_buffer_count{application=\"$application\", instance=\"$instance\", id=\"mapped\"} or jvm_buffer_count_buffers{application=\"$application\", instance=\"$instance\", id=\"mapped\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "count",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Mapped Buffers",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 0,
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ }
+ ],
+ "refresh": "10s",
+ "schemaVersion": 18,
+ "style": "dark",
+ "tags": [],
+ "templating": {
+ "list": [
+ {
+ "allValue": null,
+ "current": {
+ "text": "test",
+ "value": "test"
+ },
+ "datasource": "Prometheus",
+ "definition": "",
+ "hide": 0,
+ "includeAll": false,
+ "label": "Application",
+ "multi": false,
+ "name": "application",
+ "options": [],
+ "query": "label_values(application)",
+ "refresh": 2,
+ "regex": "",
+ "skipUrlSync": false,
+ "sort": 0,
+ "tagValuesQuery": "",
+ "tags": [],
+ "tagsQuery": "",
+ "type": "query",
+ "useTags": false
+ },
+ {
+ "allFormat": "glob",
+ "allValue": null,
+ "current": {
+ "text": "localhost:8080",
+ "value": "localhost:8080"
+ },
+ "datasource": "Prometheus",
+ "definition": "",
+ "hide": 0,
+ "includeAll": false,
+ "label": "Instance",
+ "multi": false,
+ "multiFormat": "glob",
+ "name": "instance",
+ "options": [],
+ "query": "label_values(jvm_memory_used_bytes{application=\"$application\"}, instance)",
+ "refresh": 2,
+ "regex": "",
+ "skipUrlSync": false,
+ "sort": 0,
+ "tagValuesQuery": "",
+ "tags": [],
+ "tagsQuery": "",
+ "type": "query",
+ "useTags": false
+ },
+ {
+ "allFormat": "glob",
+ "allValue": null,
+ "current": {
+ "text": "All",
+ "value": "$__all"
+ },
+ "datasource": "Prometheus",
+ "definition": "",
+ "hide": 0,
+ "includeAll": true,
+ "label": "JVM Memory Pools Heap",
+ "multi": false,
+ "multiFormat": "glob",
+ "name": "jvm_memory_pool_heap",
+ "options": [],
+ "query": "label_values(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"},id)",
+ "refresh": 1,
+ "regex": "",
+ "skipUrlSync": false,
+ "sort": 1,
+ "tagValuesQuery": "",
+ "tags": [],
+ "tagsQuery": "",
+ "type": "query",
+ "useTags": false
+ },
+ {
+ "allFormat": "glob",
+ "allValue": null,
+ "current": {
+ "text": "All",
+ "value": "$__all"
+ },
+ "datasource": "Prometheus",
+ "definition": "",
+ "hide": 0,
+ "includeAll": true,
+ "label": "JVM Memory Pools Non-Heap",
+ "multi": false,
+ "multiFormat": "glob",
+ "name": "jvm_memory_pool_nonheap",
+ "options": [],
+ "query": "label_values(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"},id)",
+ "refresh": 1,
+ "regex": "",
+ "skipUrlSync": false,
+ "sort": 2,
+ "tagValuesQuery": "",
+ "tags": [],
+ "tagsQuery": "",
+ "type": "query",
+ "useTags": false
+ }
+ ]
+ },
+ "time": {
+ "from": "now-30m",
+ "to": "now"
+ },
+ "timepicker": {
+ "now": true,
+ "refresh_intervals": ["5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d"],
+ "time_options": ["5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d"]
+ },
+ "timezone": "browser",
+ "title": "JVM (Micrometer)",
+ "uid": "Ud1CFe3iz",
+ "version": 1
+}
diff --git a/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/dashboards/dashboard.yml b/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/dashboards/dashboard.yml
new file mode 100644
index 000000000000..5b46e1f4ca81
--- /dev/null
+++ b/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/dashboards/dashboard.yml
@@ -0,0 +1,11 @@
+apiVersion: 1
+
+providers:
+ - name: 'Prometheus'
+ orgId: 1
+ folder: ''
+ type: file
+ disableDeletion: false
+ editable: true
+ options:
+ path: /etc/grafana/provisioning/dashboards
diff --git a/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/datasources/datasource.yml b/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/datasources/datasource.yml
new file mode 100644
index 000000000000..20506dab30f3
--- /dev/null
+++ b/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/datasources/datasource.yml
@@ -0,0 +1,50 @@
+apiVersion: 1
+
+# list of datasources that should be deleted from the database
+deleteDatasources:
+ - name: Prometheus
+ orgId: 1
+
+# list of datasources to insert/update depending
+# whats available in the database
+datasources:
+ # name of the datasource. Required
+ - name: Prometheus
+ # datasource type. Required
+ type: prometheus
+ # access mode. direct or proxy. Required
+ access: proxy
+ # org id. will default to orgId 1 if not specified
+ orgId: 1
+ # url
+ # On MacOS, replace localhost by host.docker.internal
+ url: http://localhost:9090
+ # database password, if used
+ password:
+ # database user, if used
+ user:
+ # database name, if used
+ database:
+ # enable/disable basic auth
+ basicAuth: false
+ # basic auth username
+ basicAuthUser: admin
+ # basic auth password
+ basicAuthPassword: admin
+ # enable/disable with credentials headers
+ withCredentials:
+ # mark as default datasource. Max one per org
+ isDefault: true
+ #
diff --git a/json-modules/gson-2/README.md b/json-modules/gson-2/README.md
new file mode 100644
index 000000000000..40d55155671e
--- /dev/null
+++ b/json-modules/gson-2/README.md
@@ -0,0 +1,7 @@
+## GSON
+
+This module contains articles about Gson
+
+### Relevant Articles:
+
+
diff --git a/json-modules/gson-2/pom.xml b/json-modules/gson-2/pom.xml
new file mode 100644
index 000000000000..aa451bdeede5
--- /dev/null
+++ b/json-modules/gson-2/pom.xml
@@ -0,0 +1,27 @@
+
+
+ 4.0.0
+ gson-2
+ gson-2
+
+
+ com.baeldung
+ json-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ com.google.code.gson
+ gson
+ ${gson.version}
+
+
+
+
+ 2.10.1
+
+
+
\ No newline at end of file
diff --git a/json-modules/gson-2/src/main/java/com/baeldung/gson/parsingerrors/Person.java b/json-modules/gson-2/src/main/java/com/baeldung/gson/parsingerrors/Person.java
new file mode 100644
index 000000000000..387d6e1582cd
--- /dev/null
+++ b/json-modules/gson-2/src/main/java/com/baeldung/gson/parsingerrors/Person.java
@@ -0,0 +1,15 @@
+package com.baeldung.gson.parsingerrors;
+
+public class Person {
+
+ public String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public Person(String name) {
+ this.name = name;
+ }
+
+}
diff --git a/json-modules/gson-2/src/test/java/com/baeldung/gson/parsingerror/GsonErrorDemoUnitTest.java b/json-modules/gson-2/src/test/java/com/baeldung/gson/parsingerror/GsonErrorDemoUnitTest.java
new file mode 100644
index 000000000000..d97f695ddf03
--- /dev/null
+++ b/json-modules/gson-2/src/test/java/com/baeldung/gson/parsingerror/GsonErrorDemoUnitTest.java
@@ -0,0 +1,55 @@
+package com.baeldung.gson.parsingerror;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.lang.reflect.Type;
+import java.util.Collection;
+
+import org.junit.jupiter.api.Test;
+
+import com.baeldung.gson.parsingerrors.Person;
+import com.google.gson.Gson;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.reflect.TypeToken;
+
+class GsonErrorDemoUnitTest {
+
+ @Test
+ void givenAJsonArray_WhenTellingGsonToExpectAnObject_ThenThrows() {
+ assertThrows(JsonSyntaxException.class, () -> {
+ Person person = new Gson().fromJson("[{\"name\":\"John\"},{\"name\":\"James\"}]", Person.class);
+ });
+ }
+
+ @Test
+ void givenAJsonArray_WhenParsingIntoAnArray_ThenOK() {
+ Person[] personArray = new Gson().fromJson("[{\"name\":\"John\"},{\"name\":\"James\"}]", Person[].class);
+ assertThat(personArray).extracting(Person::getName)
+ .containsExactly("John", "James");
+ }
+
+ @Test
+ void givenAJsonArray_WhenParsingIntoACollection_ThenOK() {
+ Type collectionType = new TypeToken>() {
+ }.getType();
+ Collection personCollection = new Gson().fromJson("[{\"name\":\"John\"},{\"name\":\"James\"}]", collectionType);
+ assertThat(personCollection).extracting(Person::getName)
+ .containsExactly("John", "James");
+ }
+
+ @Test
+ void givenAJsonObject_WhenTellingGsonToExpectAnArray_ThenThrows() {
+ assertThrows(JsonSyntaxException.class, () -> {
+ Person[] personArray = new Gson().fromJson("{\"name\":\"John\"}", Person[].class);
+ });
+ }
+
+ @Test
+ void givenAJsonObject_WhenParsingIntoAnObject_ThenOK() {
+ Person person = new Gson().fromJson("{\"name\":\"John\"}", Person.class);
+ assertEquals("John", person.getName());
+ }
+
+}
diff --git a/json-modules/gson/pom.xml b/json-modules/gson/pom.xml
index faa8a482975f..ecfbaa7be424 100644
--- a/json-modules/gson/pom.xml
+++ b/json-modules/gson/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
gson
- 0.1-SNAPSHOT
gson
diff --git a/json-modules/json-path/pom.xml b/json-modules/json-path/pom.xml
index e467ee9557b7..88b81dfc688e 100644
--- a/json-modules/json-path/pom.xml
+++ b/json-modules/json-path/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
json-path
- 0.0.1-SNAPSHOT
json-path
diff --git a/json-modules/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java b/json-modules/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java
index 85e5d3e82627..a64495c0f821 100644
--- a/json-modules/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java
+++ b/json-modules/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java
@@ -1,9 +1,11 @@
package com.baeldung.jsonpath.introduction;
import com.jayway.jsonpath.Configuration;
+import com.jayway.jsonpath.Criteria;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
+import com.jayway.jsonpath.Filter;
import org.junit.Test;
import java.io.InputStream;
@@ -98,4 +100,14 @@ public void givenDirector_whenRequestingLatestMovieTitle_thenSucceed() {
assertEquals("Spectre", title);
}
+
+ @Test
+ public void givenJsonPathWithFilterPredicate_whenReadingRootNode_thenCorrect() {
+ Filter directorSamMendesFilter = Filter.filter(Criteria.where("director")
+ .contains("Sam Mendes"));
+ List
+ discord4j
jira-rest-integration
+ sentry-servlet
+ slack
stripe
twilio
twitter4j
- sentry-servlet
diff --git a/saas-modules/sentry-servlet/pom.xml b/saas-modules/sentry-servlet/pom.xml
index 2e4f95b5fb2a..11dd2ad0ff55 100644
--- a/saas-modules/sentry-servlet/pom.xml
+++ b/saas-modules/sentry-servlet/pom.xml
@@ -11,40 +11,40 @@
sentry-servlet
sentry-servlet
war
-
+
- 6.11.0
- 1.10.4
- 3.3.2
+ 6.11.0
+ 1.10.4
+ 3.3.2
-
+
-
- io.sentry
- sentry-servlet
- ${sentry.version}
-
+
+ io.sentry
+ sentry-servlet
+ ${sentry.version}
+
-
- javax.servlet
- javax.servlet-api
- provided
-
+
+ javax.servlet
+ javax.servlet-api
+ provided
+
-
+
-
-
- org.codehaus.cargo
- cargo-maven3-plugin
- ${cargo.version}
-
-
- tomcat9x
- embedded
-
-
-
-
+
+
+ org.codehaus.cargo
+ cargo-maven3-plugin
+ ${cargo.version}
+
+
+ tomcat9x
+ embedded
+
+
+
+
\ No newline at end of file
diff --git a/slack/README.md b/saas-modules/slack/README.md
similarity index 100%
rename from slack/README.md
rename to saas-modules/slack/README.md
diff --git a/slack/pom.xml b/saas-modules/slack/pom.xml
similarity index 97%
rename from slack/pom.xml
rename to saas-modules/slack/pom.xml
index 690bf5132cbc..326167c055cc 100644
--- a/slack/pom.xml
+++ b/saas-modules/slack/pom.xml
@@ -11,7 +11,7 @@
com.baeldung
- parent-modules
+ saas-modules
1.0.0-SNAPSHOT
diff --git a/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java b/saas-modules/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java
similarity index 100%
rename from slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java
rename to saas-modules/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java
diff --git a/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java b/saas-modules/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java
similarity index 100%
rename from slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java
rename to saas-modules/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java
diff --git a/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java b/saas-modules/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java
similarity index 100%
rename from slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java
rename to saas-modules/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java
diff --git a/slack/src/main/java/com/baeldung/examples/slack/MainClass.java b/saas-modules/slack/src/main/java/com/baeldung/examples/slack/MainClass.java
similarity index 100%
rename from slack/src/main/java/com/baeldung/examples/slack/MainClass.java
rename to saas-modules/slack/src/main/java/com/baeldung/examples/slack/MainClass.java
diff --git a/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java b/saas-modules/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java
similarity index 100%
rename from slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java
rename to saas-modules/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java
diff --git a/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java b/saas-modules/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java
similarity index 100%
rename from slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java
rename to saas-modules/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java
diff --git a/slack/src/main/resources/logback.xml b/saas-modules/slack/src/main/resources/logback.xml
similarity index 100%
rename from slack/src/main/resources/logback.xml
rename to saas-modules/slack/src/main/resources/logback.xml
diff --git a/security-modules/pom.xml b/security-modules/pom.xml
index ed88ef842e9d..d0edced4e014 100644
--- a/security-modules/pom.xml
+++ b/security-modules/pom.xml
@@ -17,7 +17,7 @@
apache-shiro
cas
cloud-foundry-uaa
-
+ java-ee-8-security-api
jee-7-security
jjwt
jwt
diff --git a/spring-actuator/pom.xml b/spring-actuator/pom.xml
new file mode 100644
index 000000000000..48dae4594009
--- /dev/null
+++ b/spring-actuator/pom.xml
@@ -0,0 +1,75 @@
+
+
+ 4.0.0
+ spring-actuator
+ spring-actuator
+ war
+ Demo project for Spring Boot Actuator without Spring Boot
+
+
+ com.baeldung
+ parent-spring-6
+ 0.0.1-SNAPSHOT
+ ../parent-spring-6
+
+
+
+
+ jakarta.servlet
+ jakarta.servlet-api
+ 5.0.0
+ provided
+
+
+ org.springframework
+ spring-webmvc
+
+
+ org.springframework
+ spring-test
+ test
+
+
+ org.springframework.boot
+ spring-boot-actuator-autoconfigure
+ ${spring-boot.version}
+
+
+
+ org.eclipse.jetty
+ jetty-servlet
+ ${jetty.version}
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ 3.3.2
+
+
+
+ org.eclipse.jetty
+ jetty-maven-plugin
+ ${jetty.version}
+
+
+
+
+
+ org.eclipse.jetty
+ jetty-maven-plugin
+
+
+
+
+
+ 3.0.6
+ 11.0.15
+
+
+
diff --git a/spring-actuator/src/main/java/com/baeldung/spring/actuator/ActuatorConfiguration.java b/spring-actuator/src/main/java/com/baeldung/spring/actuator/ActuatorConfiguration.java
new file mode 100644
index 000000000000..857db1a0d58b
--- /dev/null
+++ b/spring-actuator/src/main/java/com/baeldung/spring/actuator/ActuatorConfiguration.java
@@ -0,0 +1,26 @@
+package com.baeldung.spring.actuator;
+
+import org.springframework.boot.actuate.health.Health;
+import org.springframework.boot.actuate.health.HealthIndicator;
+import org.springframework.boot.actuate.info.InfoContributor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ActuatorConfiguration {
+
+ @Bean
+ public HealthIndicator sampleHealthIndicator() {
+ return Health.up()
+ .withDetail("info", "Sample Health")
+ ::build;
+ }
+
+ @Bean
+ public InfoContributor provideSampleInfos() {
+ return builder ->
+ builder
+ .withDetail("app-title", "Actuator Sample Application");
+
+ }
+}
diff --git a/spring-actuator/src/main/java/com/baeldung/spring/actuator/AppConfig.java b/spring-actuator/src/main/java/com/baeldung/spring/actuator/AppConfig.java
new file mode 100644
index 000000000000..e080cc10e2e8
--- /dev/null
+++ b/spring-actuator/src/main/java/com/baeldung/spring/actuator/AppConfig.java
@@ -0,0 +1,11 @@
+package com.baeldung.spring.actuator;
+
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.PropertySource;
+
+@EnableAutoConfiguration
+@PropertySource("classpath:application.properties")
+@ComponentScan(basePackageClasses = AppConfig.class)
+public class AppConfig {
+}
diff --git a/spring-actuator/src/main/java/com/baeldung/spring/actuator/Start.java b/spring-actuator/src/main/java/com/baeldung/spring/actuator/Start.java
new file mode 100644
index 000000000000..66899d147962
--- /dev/null
+++ b/spring-actuator/src/main/java/com/baeldung/spring/actuator/Start.java
@@ -0,0 +1,64 @@
+package com.baeldung.spring.actuator;
+
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.servlet.ServletContextHandler;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.context.ContextLoaderListener;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
+import org.springframework.web.servlet.DispatcherServlet;
+
+public class Start {
+
+ private static final Logger logger = LoggerFactory.getLogger(Start.class);
+ private static final int DEFAULT_PORT = 8080;
+ private static final String CONTEXT_PATH = "/";
+ private static final String CONFIG_LOCATION = AppConfig.class.getName();
+ private static final String MAPPING_URL = "/*";
+
+ /*
+ * This application runs a Jetty webcontainer that runs the
+ * Spring Dispatcher Servlet.
+ */
+ public static void main(String[] args) throws Exception {
+ new Start().startJetty(getPortFromArgs(args));
+ }
+
+ private static int getPortFromArgs(String[] args) {
+ if (args.length > 0) {
+ try {
+ return Integer.parseInt(args[0]);
+ } catch (NumberFormatException ignore) {
+ }
+ }
+ logger.info("No server port configured, falling back to {}", DEFAULT_PORT);
+ return DEFAULT_PORT;
+ }
+
+ private void startJetty(int port) throws Exception {
+ logger.info("Starting server at port {}", port);
+ Server server = new Server(port);
+ server.setHandler(getServletContextHandler(getContext()));
+ server.start();
+ logger.info("Server started at port {}", port);
+ server.join();
+ }
+
+ private static ServletContextHandler getServletContextHandler(WebApplicationContext context) {
+ ServletContextHandler contextHandler = new ServletContextHandler();
+ contextHandler.setErrorHandler(null);
+ contextHandler.setContextPath(CONTEXT_PATH);
+ contextHandler.addServlet(new ServletHolder(new DispatcherServlet(context)), MAPPING_URL);
+ contextHandler.addEventListener(new ContextLoaderListener(context));
+ return contextHandler;
+ }
+
+ private static WebApplicationContext getContext() {
+ AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
+ context.setConfigLocation(CONFIG_LOCATION);
+ return context;
+ }
+
+}
diff --git a/spring-actuator/src/main/java/com/baeldung/spring/actuator/WebMvcConfiguration.java b/spring-actuator/src/main/java/com/baeldung/spring/actuator/WebMvcConfiguration.java
new file mode 100644
index 000000000000..8da216611448
--- /dev/null
+++ b/spring-actuator/src/main/java/com/baeldung/spring/actuator/WebMvcConfiguration.java
@@ -0,0 +1,23 @@
+package com.baeldung.spring.actuator;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+@Configuration
+public class WebMvcConfiguration {
+
+ @Bean
+ public WebMvcConfigurer webMvcConfigurer() {
+ return new WebMvcConfigurer() {
+ @Override
+ public void addViewControllers(ViewControllerRegistry registry) {
+ registry
+ .addViewController("/")
+ .setViewName("redirect:/actuator");
+ }
+ };
+ }
+
+}
diff --git a/spring-actuator/src/main/resources/application.properties b/spring-actuator/src/main/resources/application.properties
new file mode 100644
index 000000000000..db3cdb647bcb
--- /dev/null
+++ b/spring-actuator/src/main/resources/application.properties
@@ -0,0 +1,2 @@
+management.endpoints.web.exposure.include=*
+management.endpoint.health.show-details=always
diff --git a/spring-batch-2/pom.xml b/spring-batch-2/pom.xml
index 12d31aca14e3..378191c91cf5 100644
--- a/spring-batch-2/pom.xml
+++ b/spring-batch-2/pom.xml
@@ -11,9 +11,9 @@
com.baeldung
- parent-boot-2
+ parent-boot-3
0.0.1-SNAPSHOT
- ../parent-boot-2
+ ../parent-boot-3
@@ -51,8 +51,9 @@
- 4.3.0
- 3.1.1
+ 5.0.0
+ 4.2.0
+ com.baeldung.batch.SpringBootBatchProcessingApplication
\ No newline at end of file
diff --git a/spring-batch-2/src/main/java/com/baeldung/batch/BatchConfiguration.java b/spring-batch-2/src/main/java/com/baeldung/batch/BatchConfiguration.java
index 0c053dd86ce1..770b6330dd70 100644
--- a/spring-batch-2/src/main/java/com/baeldung/batch/BatchConfiguration.java
+++ b/spring-batch-2/src/main/java/com/baeldung/batch/BatchConfiguration.java
@@ -4,31 +4,24 @@
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
-import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
-import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
-import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
+import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
+import org.springframework.batch.core.repository.JobRepository;
+import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
+import org.springframework.transaction.PlatformTransactionManager;
@Configuration
-@EnableBatchProcessing
public class BatchConfiguration {
-
- @Autowired
- public JobBuilderFactory jobBuilderFactory;
-
- @Autowired
- public StepBuilderFactory stepBuilderFactory;
@Value("${file.input}")
private String fileInput;
@@ -59,8 +52,8 @@ public JdbcBatchItemWriter writer(DataSource dataSource) {
}
@Bean
- public Job importUserJob(JobCompletionNotificationListener listener, Step step1) {
- return jobBuilderFactory.get("importUserJob")
+ public Job importUserJob(JobRepository jobRepository, JobCompletionNotificationListener listener, Step step1) {
+ return new JobBuilder("importUserJob", jobRepository)
.incrementer(new RunIdIncrementer())
.listener(listener)
.flow(step1)
@@ -69,9 +62,9 @@ public Job importUserJob(JobCompletionNotificationListener listener, Step step1)
}
@Bean
- public Step step1(JdbcBatchItemWriter writer) {
- return stepBuilderFactory.get("step1")
- . chunk(10)
+ public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, JdbcBatchItemWriter writer) {
+ return new StepBuilder("step1", jobRepository)
+ . chunk(10, transactionManager)
.reader(reader())
.processor(processor())
.writer(writer)
diff --git a/spring-batch-2/src/main/java/com/baeldung/batch/CoffeeItemProcessor.java b/spring-batch-2/src/main/java/com/baeldung/batch/CoffeeItemProcessor.java
index b154b804536a..bd4173e9ed2d 100644
--- a/spring-batch-2/src/main/java/com/baeldung/batch/CoffeeItemProcessor.java
+++ b/spring-batch-2/src/main/java/com/baeldung/batch/CoffeeItemProcessor.java
@@ -10,7 +10,7 @@ public class CoffeeItemProcessor implements ItemProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(CoffeeItemProcessor.class);
@Override
- public Coffee process(final Coffee coffee) throws Exception {
+ public Coffee process(final Coffee coffee) {
String brand = coffee.getBrand().toUpperCase();
String origin = coffee.getOrigin().toUpperCase();
String chracteristics = coffee.getCharacteristics().toUpperCase();
diff --git a/spring-batch-2/src/main/java/com/baeldung/batch/JobCompletionNotificationListener.java b/spring-batch-2/src/main/java/com/baeldung/batch/JobCompletionNotificationListener.java
index ca1de40aea5e..b61faeb13b7c 100644
--- a/spring-batch-2/src/main/java/com/baeldung/batch/JobCompletionNotificationListener.java
+++ b/spring-batch-2/src/main/java/com/baeldung/batch/JobCompletionNotificationListener.java
@@ -4,13 +4,13 @@
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
-import org.springframework.batch.core.listener.JobExecutionListenerSupport;
+import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
-public class JobCompletionNotificationListener extends JobExecutionListenerSupport {
+public class JobCompletionNotificationListener implements JobExecutionListener {
private static final Logger LOGGER = LoggerFactory.getLogger(JobCompletionNotificationListener.class);
diff --git a/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java
index c830a41855c9..dcb2bc519995 100644
--- a/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java
+++ b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java
@@ -7,15 +7,16 @@
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.Step;
-import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
-import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
-import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
+import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.JobLauncher;
+import org.springframework.batch.core.repository.JobRepository;
+import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
@@ -24,17 +25,16 @@
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.ScheduledMethodRunnable;
+import org.springframework.transaction.PlatformTransactionManager;
import java.util.Date;
import java.util.IdentityHashMap;
-import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@Configuration
-@EnableBatchProcessing
@EnableScheduling
public class SpringBatchScheduler {
@@ -47,20 +47,20 @@ public class SpringBatchScheduler {
private final Map> scheduledTasks = new IdentityHashMap<>();
@Autowired
- private JobBuilderFactory jobBuilderFactory;
+ private JobLauncher jobLauncher;
@Autowired
- private StepBuilderFactory stepBuilderFactory;
+ private JobRepository jobRepository;
@Autowired
- private JobLauncher jobLauncher;
+ private PlatformTransactionManager transactionManager;
@Scheduled(fixedRate = 2000)
public void launchJob() throws Exception {
Date date = new Date();
logger.debug("scheduler starts at " + date);
if (enabled.get()) {
- JobExecution jobExecution = jobLauncher.run(job(), new JobParametersBuilder().addDate("launchDate", date)
+ JobExecution jobExecution = jobLauncher.run(job(jobRepository, transactionManager), new JobParametersBuilder().addDate("launchDate", date)
.toJobParameters());
batchRunCounter.incrementAndGet();
logger.debug("Batch job ends with status as " + jobExecution.getStatus());
@@ -106,17 +106,16 @@ public void cancelFutureSchedulerTasks() {
}
@Bean
- public Job job() {
- return jobBuilderFactory
- .get("job")
- .start(readBooks())
+ public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
+ return new JobBuilder("job", jobRepository)
+ .start(readBooks(jobRepository, transactionManager))
.build();
}
@Bean
- protected Step readBooks() {
- return stepBuilderFactory.get("readBooks")
- . chunk(2)
+ protected Step readBooks(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
+ return new StepBuilder("readBooks", jobRepository)
+ . chunk(2, transactionManager)
.reader(reader())
.writer(writer())
.build();
@@ -128,7 +127,7 @@ public FlatFileItemReader reader() {
.resource(new ClassPathResource("books.csv"))
.delimited()
.names(new String[] { "id", "name" })
- .fieldSetMapper(new BeanWrapperFieldSetMapper() {
+ .fieldSetMapper(new BeanWrapperFieldSetMapper<>() {
{
setTargetType(Book.class);
}
@@ -138,15 +137,10 @@ public FlatFileItemReader reader() {
@Bean
public ItemWriter writer() {
- return new ItemWriter() {
-
- @Override
- public void write(List extends Book> items) throws Exception {
- logger.debug("writer..." + items.size());
- for (Book item : items) {
- logger.debug(item.toString());
- }
-
+ return items -> {
+ logger.debug("writer..." + items.size());
+ for (Book item : items) {
+ logger.debug(item.toString());
}
};
}
diff --git a/spring-batch-2/src/test/java/com/baeldung/batch/SpringBootBatchIntegrationTest.java b/spring-batch-2/src/test/java/com/baeldung/batch/SpringBootBatchIntegrationTest.java
index ba2b8a6a1397..21fd7bf4b1e6 100644
--- a/spring-batch-2/src/test/java/com/baeldung/batch/SpringBootBatchIntegrationTest.java
+++ b/spring-batch-2/src/test/java/com/baeldung/batch/SpringBootBatchIntegrationTest.java
@@ -1,11 +1,10 @@
package com.baeldung.batch;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobInstance;
@@ -13,16 +12,17 @@
import org.springframework.batch.test.JobRepositoryTestUtils;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringBatchTest
-@SpringBootTest
@DirtiesContext
+@SpringJUnitConfig(BatchConfiguration.class)
@PropertySource("classpath:application.properties")
-@RunWith(SpringRunner.class)
+@EnableAutoConfiguration
public class SpringBootBatchIntegrationTest {
@Autowired
@@ -31,7 +31,10 @@ public class SpringBootBatchIntegrationTest {
@Autowired
private JobRepositoryTestUtils jobRepositoryTestUtils;
- @After
+ @MockBean
+ private JobCompletionNotificationListener jobCompletionNotificationListener;
+
+ @AfterEach
public void cleanUp() {
jobRepositoryTestUtils.removeJobExecutions();
}
@@ -42,8 +45,8 @@ public void givenCoffeeList_whenJobExecuted_thenSuccess() throws Exception {
JobInstance jobInstance = jobExecution.getJobInstance();
ExitStatus jobExitStatus = jobExecution.getExitStatus();
- assertThat(jobInstance.getJobName(), is("importUserJob"));
- assertThat(jobExitStatus.getExitCode(), is("COMPLETED"));
+ assertEquals("importUserJob", jobInstance.getJobName());
+ assertEquals("COMPLETED", jobExitStatus.getExitCode());
}
}
diff --git a/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java b/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java
index 61e5a1dd74ef..297e8d989f2d 100644
--- a/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java
+++ b/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java
@@ -1,28 +1,20 @@
package com.baeldung.batchscheduler;
-import com.baeldung.batchscheduler.SpringBatchScheduler;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.batch.test.context.SpringBatchTest;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.junit4.SpringRunner;
import static org.awaitility.Awaitility.await;
import static java.util.concurrent.TimeUnit.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-@SpringBatchTest
@SpringBootTest
@DirtiesContext
@PropertySource("classpath:application.properties")
-@RunWith(SpringRunner.class)
public class SpringBatchSchedulerIntegrationTest {
@Autowired
@@ -31,37 +23,36 @@ public class SpringBatchSchedulerIntegrationTest {
@Test
public void stopJobsWhenSchedulerDisabled() {
SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class);
- await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter()
+ await().untilAsserted(() -> assertEquals(2, schedulerBean.getBatchRunCounter()
.get()));
schedulerBean.stop();
await().atLeast(3, SECONDS);
- Assert.assertEquals(2, schedulerBean.getBatchRunCounter()
- .get());
+ assertEquals(2, schedulerBean.getBatchRunCounter().get());
}
@Test
- public void stopJobSchedulerWhenSchedulerDestroyed() throws Exception {
+ public void stopJobSchedulerWhenSchedulerDestroyed() {
ScheduledAnnotationBeanPostProcessor bean = context.getBean(ScheduledAnnotationBeanPostProcessor.class);
SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class);
- await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter()
+ await().untilAsserted(() -> assertEquals(2, schedulerBean.getBatchRunCounter()
.get()));
bean.postProcessBeforeDestruction(schedulerBean, "SpringBatchScheduler");
await().atLeast(3, SECONDS);
- Assert.assertEquals(2, schedulerBean.getBatchRunCounter()
+ assertEquals(2, schedulerBean.getBatchRunCounter()
.get());
}
@Test
- public void stopJobSchedulerWhenFutureTasksCancelled() throws Exception {
+ public void stopJobSchedulerWhenFutureTasksCancelled() {
SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class);
- await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter()
+ await().untilAsserted(() -> assertEquals(2, schedulerBean.getBatchRunCounter()
.get()));
schedulerBean.cancelFutureSchedulerTasks();
await().atLeast(3, SECONDS);
- Assert.assertEquals(2, schedulerBean.getBatchRunCounter()
+ assertEquals(2, schedulerBean.getBatchRunCounter()
.get());
}
diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml
index e9d3afa37681..810ddcdcdd9b 100644
--- a/spring-batch/pom.xml
+++ b/spring-batch/pom.xml
@@ -11,9 +11,9 @@
com.baeldung
- parent-boot-2
+ parent-boot-3
0.0.1-SNAPSHOT
- ../parent-boot-2
+ ../parent-boot-3
@@ -22,25 +22,15 @@
jackson-datatype-jsr310
${jackson-datatype.version}
-
-
- javax.xml.bind
- jaxb-api
- ${jaxb.version}
-
+ jakarta.xml.bind
+ jakarta.xml.bind-api
+ 4.0.0
org.glassfish.jaxb
jaxb-runtime
${jaxb.version}
-
-
-
-
- org.xerial
- sqlite-jdbc
- ${sqlite.version}
org.springframework
@@ -53,20 +43,9 @@
-
- org.springframework
- spring-jdbc
- ${spring.version}
-
-
- org.springframework.batch
- spring-batch-core
- ${spring.batch.version}
-
org.springframework.batch
spring-batch-test
- ${spring.batch.version}
com.opencsv
@@ -78,19 +57,29 @@
spring-boot-starter-batch
- org.hsqldb
- hsqldb
- runtime
+ org.apache.httpcomponents
+ httpclient
+ ${http-client.version}
+
+
+ org.codehaus.jettison
+ jettison
+ ${jettison.version}
+
+
+ com.h2database
+ h2
- 5.3.0
- 4.3.0
- 3.15.1
- 4.1
- 2.3.1
- 2.12.3
+ 6.0.6
+ 5.7.1
+ 4.0.2
+ 2.14.2
+ 4.5.14
+ 1.5.3
+ com.baeldung.batchtesting.SpringBatchApplication
\ No newline at end of file
diff --git a/spring-batch/repository.sqlite b/spring-batch/repository.sqlite
index b6a954554c96..ddf5d0c16f52 100644
Binary files a/spring-batch/repository.sqlite and b/spring-batch/repository.sqlite differ
diff --git a/spring-batch/src/main/java/com/baeldung/batch/App.java b/spring-batch/src/main/java/com/baeldung/batch/App.java
index c2db446965be..c5823590d893 100644
--- a/spring-batch/src/main/java/com/baeldung/batch/App.java
+++ b/spring-batch/src/main/java/com/baeldung/batch/App.java
@@ -18,20 +18,19 @@ public class App {
public static void main(final String[] args) {
// Spring Java config
final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
- context.register(SpringConfig.class);
+ context.getEnvironment().addActiveProfile("spring");
context.register(SpringBatchConfig.class);
context.register(SpringBatchRetryConfig.class);
context.refresh();
// Spring xml config
- // ApplicationContext context = new ClassPathXmlApplicationContext("spring-batch.xml");
+ // ApplicationContext context = new ClassPathXmlApplicationContext("spring-batch-intro.xml");
runJob(context, "firstBatchJob");
runJob(context, "skippingBatchJob");
runJob(context, "skipPolicyBatchJob");
runJob(context, "retryBatchJob");
-
}
private static void runJob(AnnotationConfigApplicationContext context, String batchJobName) {
diff --git a/spring-batch/src/main/java/com/baeldung/batch/SpringBatchConfig.java b/spring-batch/src/main/java/com/baeldung/batch/SpringBatchConfig.java
index 5546df22fc6f..5d999c68e7f0 100644
--- a/spring-batch/src/main/java/com/baeldung/batch/SpringBatchConfig.java
+++ b/spring-batch/src/main/java/com/baeldung/batch/SpringBatchConfig.java
@@ -1,5 +1,7 @@
package com.baeldung.batch;
+import javax.sql.DataSource;
+
import com.baeldung.batch.model.Transaction;
import com.baeldung.batch.service.CustomItemProcessor;
import com.baeldung.batch.service.CustomSkipPolicy;
@@ -7,10 +9,15 @@
import com.baeldung.batch.service.NegativeAmountException;
import com.baeldung.batch.service.RecordFieldSetMapper;
import com.baeldung.batch.service.SkippingItemProcessor;
+
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
-import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
-import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
+import org.springframework.batch.core.job.builder.JobBuilder;
+import org.springframework.batch.core.launch.JobLauncher;
+import org.springframework.batch.core.launch.support.TaskExecutorJobLauncher;
+import org.springframework.batch.core.repository.JobRepository;
+import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
+import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
@@ -19,24 +26,23 @@
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.xml.StaxEventItemWriter;
-import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.Resource;
+import org.springframework.core.io.WritableResource;
+import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
+import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
+import org.springframework.transaction.PlatformTransactionManager;
-import java.text.ParseException;
-
+@Configuration
@Profile("spring")
public class SpringBatchConfig {
- @Autowired
- private JobBuilderFactory jobBuilderFactory;
-
- @Autowired
- private StepBuilderFactory stepBuilderFactory;
@Value("input/record.csv")
private Resource inputCsv;
@@ -45,9 +51,9 @@ public class SpringBatchConfig {
private Resource invalidInputCsv;
@Value("file:xml/output.xml")
- private Resource outputXml;
+ private WritableResource outputXml;
- public ItemReader itemReader(Resource inputData) throws UnexpectedInputException, ParseException {
+ public ItemReader itemReader(Resource inputData) throws UnexpectedInputException {
FlatFileItemReader reader = new FlatFileItemReader<>();
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
String[] tokens = {"username", "userid", "transactiondate", "amount"};
@@ -88,10 +94,10 @@ public Marshaller marshaller() {
}
@Bean
- protected Step step1(@Qualifier("itemProcessor") ItemProcessor processor, ItemWriter writer) throws ParseException {
- return stepBuilderFactory
- .get("step1")
- . chunk(10)
+ protected Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("itemProcessor") ItemProcessor processor, ItemWriter writer) {
+ return new StepBuilder("step1", jobRepository)
+ . chunk(10, transactionManager)
.reader(itemReader(inputCsv))
.processor(processor)
.writer(writer)
@@ -99,16 +105,15 @@ protected Step step1(@Qualifier("itemProcessor") ItemProcessor processor,
- ItemWriter writer) throws ParseException {
- return stepBuilderFactory
- .get("skippingStep")
- .chunk(10)
+ public Step skippingStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("skippingItemProcessor") ItemProcessor processor, ItemWriter writer) {
+ return new StepBuilder("skippingStep", jobRepository)
+ .chunk(10, transactionManager)
.reader(itemReader(invalidInputCsv))
.processor(processor)
.writer(writer)
@@ -120,19 +125,18 @@ public Step skippingStep(@Qualifier("skippingItemProcessor") ItemProcessor processor,
- ItemWriter writer) throws ParseException {
- return stepBuilderFactory
- .get("skipPolicyStep")
- .chunk(10)
+ public Step skipPolicyStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("skippingItemProcessor") ItemProcessor processor,
+ ItemWriter writer) {
+ return new StepBuilder("skipPolicyStep", jobRepository)
+ .chunk(10, transactionManager)
.reader(itemReader(invalidInputCsv))
.processor(processor)
.writer(writer)
@@ -142,11 +146,44 @@ public Step skipPolicyStep(@Qualifier("skippingItemProcessor") ItemProcessor itemReader(Resource inputData) throws ParseException {
+ public ItemReader itemReader(Resource inputData) {
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
tokenizer.setNames(tokens);
DefaultLineMapper lineMapper = new DefaultLineMapper<>();
@@ -93,10 +86,11 @@ public Marshaller marshaller() {
}
@Bean
- public Step retryStep(@Qualifier("retryItemProcessor") ItemProcessor processor,
- ItemWriter writer) throws ParseException {
- return stepBuilderFactory.get("retryStep")
- .chunk(10)
+ public Step retryStep(
+ JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("retryItemProcessor") ItemProcessor processor,
+ ItemWriter writer) {
+ return new StepBuilder("retryStep", jobRepository)
+ .chunk(10, transactionManager)
.reader(itemReader(inputCsv))
.processor(processor)
.writer(writer)
@@ -108,9 +102,8 @@ public Step retryStep(@Qualifier("retryItemProcessor") ItemProcessor partition(int gridSize) {
- Map map = new HashMap(gridSize);
+ Map map = new HashMap<>(gridSize);
int i = 0, k = 1;
for (Resource resource : resources) {
ExecutionContext context = new ExecutionContext();
diff --git a/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionConfig.java b/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringBatchPartitionConfig.java
similarity index 77%
rename from spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionConfig.java
rename to spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringBatchPartitionConfig.java
index b08c95af53bc..ceacb36e4dcd 100644
--- a/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionConfig.java
+++ b/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringBatchPartitionConfig.java
@@ -5,13 +5,13 @@
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
-import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
-import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
+import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.JobLauncher;
-import org.springframework.batch.core.launch.support.SimpleJobLauncher;
+import org.springframework.batch.core.launch.support.TaskExecutorJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
+import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
@@ -36,42 +36,35 @@
import javax.sql.DataSource;
import java.io.IOException;
-import java.net.MalformedURLException;
import java.text.ParseException;
@Configuration
@EnableBatchProcessing
-public class SpringbatchPartitionConfig {
+public class SpringBatchPartitionConfig {
@Autowired
- ResourcePatternResolver resoursePatternResolver;
-
- @Autowired
- private JobBuilderFactory jobs;
-
- @Autowired
- private StepBuilderFactory steps;
+ private ResourcePatternResolver resourcePatternResolver;
@Bean(name = "partitionerJob")
- public Job partitionerJob() throws UnexpectedInputException, MalformedURLException, ParseException {
- return jobs.get("partitionerJob")
- .start(partitionStep())
+ public Job partitionerJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) throws UnexpectedInputException, ParseException {
+ return new JobBuilder("partitionerJob", jobRepository)
+ .start(partitionStep(jobRepository, transactionManager))
.build();
}
@Bean
- public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException {
- return steps.get("partitionStep")
+ public Step partitionStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) throws UnexpectedInputException, ParseException {
+ return new StepBuilder("partitionStep", jobRepository)
.partitioner("slaveStep", partitioner())
- .step(slaveStep())
+ .step(slaveStep(jobRepository, transactionManager))
.taskExecutor(taskExecutor())
.build();
}
@Bean
- public Step slaveStep() throws UnexpectedInputException, MalformedURLException, ParseException {
- return steps.get("slaveStep")
- .chunk(1)
+ public Step slaveStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) throws UnexpectedInputException, ParseException {
+ return new StepBuilder("slaveStep", jobRepository)
+ .chunk(1, transactionManager)
.reader(itemReader(null))
.writer(itemWriter(marshaller(), null))
.build();
@@ -82,7 +75,7 @@ public CustomMultiResourcePartitioner partitioner() {
CustomMultiResourcePartitioner partitioner = new CustomMultiResourcePartitioner();
Resource[] resources;
try {
- resources = resoursePatternResolver.getResources("file:src/main/resources/input/partitioner/*.csv");
+ resources = resourcePatternResolver.getResources("file:src/main/resources/input/partitioner/*.csv");
} catch (IOException e) {
throw new RuntimeException("I/O problems when resolving the input file pattern.", e);
}
@@ -108,7 +101,7 @@ public FlatFileItemReader itemReader(@Value("#{stepExecutionContext
@Bean(destroyMethod = "")
@StepScope
- public StaxEventItemWriter itemWriter(Marshaller marshaller, @Value("#{stepExecutionContext[opFileName]}") String filename) throws MalformedURLException {
+ public StaxEventItemWriter itemWriter(Marshaller marshaller, @Value("#{stepExecutionContext[opFileName]}") String filename) {
StaxEventItemWriter itemWriter = new StaxEventItemWriter<>();
itemWriter.setMarshaller(marshaller);
itemWriter.setRootTagName("transactionRecord");
@@ -133,7 +126,8 @@ public TaskExecutor taskExecutor() {
return taskExecutor;
}
- private JobRepository getJobRepository() throws Exception {
+ @Bean(name = "jobRepository")
+ public JobRepository getJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource());
factory.setTransactionManager(getTransactionManager());
@@ -143,20 +137,23 @@ private JobRepository getJobRepository() throws Exception {
return factory.getObject();
}
- private DataSource dataSource() {
+ @Bean(name = "dataSource")
+ public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
- return builder.setType(EmbeddedDatabaseType.HSQL)
+ return builder.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql")
.addScript("classpath:org/springframework/batch/core/schema-h2.sql")
.build();
}
- private PlatformTransactionManager getTransactionManager() {
+ @Bean(name = "transactionManager")
+ public PlatformTransactionManager getTransactionManager() {
return new ResourcelessTransactionManager();
}
+ @Bean(name = "jobLauncher")
public JobLauncher getJobLauncher() throws Exception {
- SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
+ TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher();
// SimpleJobLauncher's methods Throws Generic Exception,
// it would have been better to have a specific one
jobLauncher.setJobRepository(getJobRepository());
diff --git a/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionerApp.java b/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringBatchPartitionerApp.java
similarity index 89%
rename from spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionerApp.java
rename to spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringBatchPartitionerApp.java
index e755e21ca9c9..a1661e750e46 100644
--- a/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionerApp.java
+++ b/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringBatchPartitionerApp.java
@@ -8,14 +8,14 @@
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-public class SpringbatchPartitionerApp {
+public class SpringBatchPartitionerApp {
- private static final Logger LOGGER = LoggerFactory.getLogger(SpringbatchPartitionerApp.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(SpringBatchPartitionerApp.class);
public static void main(final String[] args) {
// Spring Java config
final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
- context.register(SpringbatchPartitionConfig.class);
+ context.register(SpringBatchPartitionConfig.class);
context.refresh();
final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
diff --git a/spring-batch/src/main/java/com/baeldung/batch/service/CustomSkipPolicy.java b/spring-batch/src/main/java/com/baeldung/batch/service/CustomSkipPolicy.java
index 25401de02203..af6fe20529f1 100644
--- a/spring-batch/src/main/java/com/baeldung/batch/service/CustomSkipPolicy.java
+++ b/spring-batch/src/main/java/com/baeldung/batch/service/CustomSkipPolicy.java
@@ -9,19 +9,13 @@ public class CustomSkipPolicy implements SkipPolicy {
private static final int INVALID_TX_AMOUNT_LIMIT = -1000;
@Override
- public boolean shouldSkip(Throwable throwable, int skipCount) throws SkipLimitExceededException {
-
+ public boolean shouldSkip(Throwable throwable, long skipCount) throws SkipLimitExceededException {
if (throwable instanceof MissingUsernameException && skipCount < MAX_SKIP_COUNT) {
return true;
}
- if (throwable instanceof NegativeAmountException && skipCount < MAX_SKIP_COUNT ) {
- NegativeAmountException ex = (NegativeAmountException) throwable;
- if(ex.getAmount() < INVALID_TX_AMOUNT_LIMIT){
- return false;
- } else{
- return true;
- }
+ if (throwable instanceof NegativeAmountException ex && skipCount < MAX_SKIP_COUNT ) {
+ return ex.getAmount() >= INVALID_TX_AMOUNT_LIMIT;
}
return false;
diff --git a/spring-batch/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java b/spring-batch/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java
index 09478e9a3099..97c77d9e6ac6 100644
--- a/spring-batch/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java
+++ b/spring-batch/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java
@@ -10,7 +10,7 @@
public class RecordFieldSetMapper implements FieldSetMapper {
- public Transaction mapFieldSet(FieldSet fieldSet) throws BindException {
+ public Transaction mapFieldSet(FieldSet fieldSet) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyy");
diff --git a/spring-batch/src/main/java/com/baeldung/batch/service/RetryItemProcessor.java b/spring-batch/src/main/java/com/baeldung/batch/service/RetryItemProcessor.java
index c380e2c0ab6b..aa49680b2ade 100644
--- a/spring-batch/src/main/java/com/baeldung/batch/service/RetryItemProcessor.java
+++ b/spring-batch/src/main/java/com/baeldung/batch/service/RetryItemProcessor.java
@@ -5,15 +5,13 @@
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import com.baeldung.batch.model.Transaction;
-import org.codehaus.jettison.json.JSONException;
+
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
-import java.io.IOException;
-
public class RetryItemProcessor implements ItemProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(RetryItemProcessor.class);
@@ -22,7 +20,7 @@ public class RetryItemProcessor implements ItemProcessor {
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
diff --git a/spring-batch/src/main/java/com/baeldung/batch/springboot/SpringBootBatchConfig.java b/spring-batch/src/main/java/com/baeldung/batch/springboot/SpringBootBatchConfig.java
index 57531ebc39ea..6c463de5dcea 100644
--- a/spring-batch/src/main/java/com/baeldung/batch/springboot/SpringBootBatchConfig.java
+++ b/spring-batch/src/main/java/com/baeldung/batch/springboot/SpringBootBatchConfig.java
@@ -5,8 +5,9 @@
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
-import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
-import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
+import org.springframework.batch.core.job.builder.JobBuilder;
+import org.springframework.batch.core.repository.JobRepository;
+import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
@@ -15,27 +16,21 @@
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.xml.StaxEventItemWriter;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.Resource;
+import org.springframework.core.io.WritableResource;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
-
-import java.text.ParseException;
+import org.springframework.transaction.PlatformTransactionManager;
@Configuration
@EnableBatchProcessing
@Profile("spring-boot")
public class SpringBootBatchConfig {
- @Autowired
- private JobBuilderFactory jobBuilderFactory;
-
- @Autowired
- private StepBuilderFactory stepBuilderFactory;
@Value("input/record.csv")
private Resource inputCsv;
@@ -44,9 +39,9 @@ public class SpringBootBatchConfig {
private Resource invalidInputCsv;
@Value("file:xml/output.xml")
- private Resource outputXml;
+ private WritableResource outputXml;
- public ItemReader itemReader(Resource inputData) throws UnexpectedInputException, ParseException {
+ public ItemReader itemReader(Resource inputData) throws UnexpectedInputException {
FlatFileItemReader reader = new FlatFileItemReader<>();
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
String[] tokens = {"username", "userid", "transactiondate", "amount"};
@@ -86,11 +81,10 @@ public Marshaller marshaller3() {
return marshaller3;
}
- @Bean
- protected Step step1(@Qualifier("itemProcessor") ItemProcessor processor, ItemWriter itemWriter3) throws ParseException {
- return stepBuilderFactory
- .get("step1")
- . chunk(10)
+ @Bean(name = "step1")
+ protected Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("itemProcessor") ItemProcessor processor, ItemWriter itemWriter3) {
+ return new StepBuilder("step1", jobRepository)
+ . chunk(10, transactionManager)
.reader(itemReader(inputCsv))
.processor(processor)
.writer(itemWriter3)
@@ -98,16 +92,15 @@ protected Step step1(@Qualifier("itemProcessor") ItemProcessor processor,
- ItemWriter itemWriter3) throws ParseException {
- return stepBuilderFactory
- .get("skippingStep")
- .chunk(10)
+ public Step skippingStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("skippingItemProcessor") ItemProcessor processor,
+ ItemWriter itemWriter3) {
+ return new StepBuilder("skippingStep", jobRepository)
+ .chunk(10, transactionManager)
.reader(itemReader(invalidInputCsv))
.processor(processor)
.writer(itemWriter3)
@@ -119,19 +112,17 @@ public Step skippingStep(@Qualifier("skippingItemProcessor") ItemProcessor processor,
- ItemWriter itemWriter3) throws ParseException {
- return stepBuilderFactory
- .get("skipPolicyStep")
- .chunk(10)
+ @Bean(name = "skipPolicyStep")
+ public Step skipPolicyStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("skippingItemProcessor") ItemProcessor processor,
+ ItemWriter itemWriter3) {
+ return new StepBuilder("skipPolicyStep", jobRepository)
+ .chunk(10, transactionManager)
.reader(itemReader(invalidInputCsv))
.processor(processor)
.writer(itemWriter3)
@@ -141,11 +132,9 @@ public Step skipPolicyStep(@Qualifier("skippingItemProcessor") ItemProcessor csvItemReader(@Value("#{jobParameters['file.input']}") String input) {
@@ -65,7 +55,7 @@ public FlatFileItemReader csvItemReader(@Value("#{jobParameters['fil
@Bean
@StepScope
- public JsonFileItemWriter jsonItemWriter(@Value("#{jobParameters['file.output']}") String output) throws IOException {
+ public JsonFileItemWriter jsonItemWriter(@Value("#{jobParameters['file.output']}") String output) {
JsonFileItemWriterBuilder builder = new JsonFileItemWriterBuilder<>();
JacksonJsonObjectMarshaller marshaller = new JacksonJsonObjectMarshaller<>();
LOGGER.info("Configuring writer to output {}", output);
@@ -81,7 +71,7 @@ public JsonFileItemWriter jsonItemWriter(@Value("#{jobParameters['file.out
@Bean
@StepScope
public ListItemWriter listItemWriter() {
- return new ListItemWriter();
+ return new ListItemWriter<>();
}
@Bean
@@ -96,12 +86,11 @@ public BookDetailsItemProcessor bookDetailsItemProcessor() {
return new BookDetailsItemProcessor();
}
- @Bean
- public Step step1(ItemReader csvItemReader, ItemWriter jsonItemWriter) throws IOException {
+ @Bean(name = "step1")
+ public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, ItemReader csvItemReader, ItemWriter jsonItemWriter) {
// @formatter:off
- return stepBuilderFactory
- .get("step1")
- . chunk(3)
+ return new StepBuilder("step1", jobRepository)
+ . chunk(3, transactionManager)
.reader(csvItemReader)
.processor(bookItemProcessor())
.writer(jsonItemWriter)
@@ -109,12 +98,11 @@ public Step step1(ItemReader csvItemReader, ItemWriter jsonIte
// @formatter:on
}
- @Bean
- public Step step2(ItemReader csvItemReader, ItemWriter listItemWriter) {
+ @Bean(name = "step2")
+ public Step step2(JobRepository jobRepository, PlatformTransactionManager transactionManager, ItemReader csvItemReader, ItemWriter listItemWriter) {
// @formatter:off
- return stepBuilderFactory
- .get("step2")
- . chunk(3)
+ return new StepBuilder("step2", jobRepository)
+ . chunk(3, transactionManager)
.reader(csvItemReader)
.processor(bookDetailsItemProcessor())
.writer(listItemWriter)
@@ -123,15 +111,13 @@ public Step step2(ItemReader csvItemReader, ItemWriter
}
@Bean(name = "transformBooksRecords")
- public Job transformBookRecords(Step step1, Step step2) throws IOException {
+ public Job transformBookRecords(JobRepository jobRepository, Step step1, Step step2) {
// @formatter:off
- return jobBuilderFactory
- .get("transformBooksRecords")
+ return new JobBuilder("transformBooksRecords", jobRepository)
.flow(step1)
.next(step2)
.end()
.build();
// @formatter:on
}
-
}
diff --git a/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookDetailsItemProcessor.java b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookDetailsItemProcessor.java
index 514a3831087e..4e4d1e90755f 100644
--- a/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookDetailsItemProcessor.java
+++ b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookDetailsItemProcessor.java
@@ -11,7 +11,7 @@ public class BookDetailsItemProcessor implements ItemProcessor {
private static Logger LOGGER = LoggerFactory.getLogger(BookItemProcessor.class);
@Override
- public Book process(BookRecord item) throws Exception {
+ public Book process(BookRecord item) {
Book book = new Book();
book.setAuthor(item.getBookAuthor());
book.setName(item.getBookName());
diff --git a/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookRecordFieldSetMapper.java b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookRecordFieldSetMapper.java
index d9e8ee115813..e4760da20f07 100644
--- a/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookRecordFieldSetMapper.java
+++ b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookRecordFieldSetMapper.java
@@ -9,7 +9,7 @@
public class BookRecordFieldSetMapper implements FieldSetMapper {
@Override
- public BookRecord mapFieldSet(FieldSet fieldSet) throws BindException {
+ public BookRecord mapFieldSet(FieldSet fieldSet) {
BookRecord bookRecord = new BookRecord();
bookRecord.setBookName(fieldSet.readString("bookname"));
bookRecord.setBookAuthor(fieldSet.readString("bookauthor"));
diff --git a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineReader.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineReader.java
index 6ffa730c19fe..d8ba2c972830 100644
--- a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineReader.java
+++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineReader.java
@@ -21,9 +21,9 @@ public void beforeStep(StepExecution stepExecution) {
}
@Override
- public Line read() throws Exception {
+ public Line read() {
Line line = fu.readLine();
- if (line != null) logger.debug("Read line: " + line.toString());
+ if (line != null) logger.debug("Read line: " + line);
return line;
}
diff --git a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LinesWriter.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LinesWriter.java
index 9f292b24b963..bcf648820cb7 100644
--- a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LinesWriter.java
+++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LinesWriter.java
@@ -7,10 +7,9 @@
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
+import org.springframework.batch.item.Chunk;
import org.springframework.batch.item.ItemWriter;
-import java.util.List;
-
public class LinesWriter implements ItemWriter, StepExecutionListener {
private final Logger logger = LoggerFactory.getLogger(LinesWriter.class);
@@ -30,7 +29,7 @@ public ExitStatus afterStep(StepExecution stepExecution) {
}
@Override
- public void write(List extends Line> lines) throws Exception {
+ public void write(Chunk extends Line> lines) {
for (Line line : lines) {
fu.writeLine(line);
logger.debug("Wrote line " + line.toString());
diff --git a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/ChunksConfig.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/ChunksConfig.java
index c8b05848f997..16c6b1191f24 100644
--- a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/ChunksConfig.java
+++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/ChunksConfig.java
@@ -6,67 +6,19 @@
import com.baeldung.taskletsvschunks.model.Line;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
-import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
-import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
-import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
-import org.springframework.batch.core.launch.JobLauncher;
-import org.springframework.batch.core.launch.support.SimpleJobLauncher;
+import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
-import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
+import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
-import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
-import org.springframework.batch.test.JobLauncherTestUtils;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
-import javax.sql.DataSource;
-
@Configuration
-@EnableBatchProcessing
public class ChunksConfig {
- @Autowired private JobBuilderFactory jobs;
-
- @Autowired private StepBuilderFactory steps;
-
- @Bean
- public JobLauncherTestUtils jobLauncherTestUtils() {
- return new JobLauncherTestUtils();
- }
-
- @Bean
- public JobRepository jobRepository() throws Exception {
- JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
- factory.setDataSource(dataSource());
- factory.setTransactionManager(transactionManager());
- return factory.getObject();
- }
-
- @Bean
- public DataSource dataSource() {
- DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setDriverClassName("org.sqlite.JDBC");
- dataSource.setUrl("jdbc:sqlite:repository.sqlite");
- return dataSource;
- }
-
- @Bean
- public PlatformTransactionManager transactionManager() {
- return new ResourcelessTransactionManager();
- }
-
- @Bean
- public JobLauncher jobLauncher() throws Exception {
- SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
- jobLauncher.setJobRepository(jobRepository());
- return jobLauncher;
- }
-
@Bean
public ItemReader itemReader() {
return new LineReader();
@@ -82,20 +34,19 @@ public ItemWriter itemWriter() {
return new LinesWriter();
}
- @Bean
- protected Step processLines(ItemReader reader, ItemProcessor processor, ItemWriter writer) {
- return steps.get("processLines"). chunk(2)
+ @Bean(name = "processLines")
+ protected Step processLines(JobRepository jobRepository, PlatformTransactionManager transactionManager, ItemReader reader, ItemProcessor processor, ItemWriter writer) {
+ return new StepBuilder("processLines", jobRepository). chunk(2, transactionManager)
.reader(reader)
.processor(processor)
.writer(writer)
.build();
}
- @Bean
- public Job job() {
- return jobs
- .get("chunksJob")
- .start(processLines(itemReader(), itemProcessor(), itemWriter()))
+ @Bean(name = "chunksJob")
+ public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
+ return new JobBuilder("chunksJob", jobRepository)
+ .start(processLines(jobRepository, transactionManager, itemReader(), itemProcessor(), itemWriter()))
.build();
}
diff --git a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/TaskletsConfig.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/TaskletsConfig.java
index 5f2f49928cc3..ab9d506229ba 100644
--- a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/TaskletsConfig.java
+++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/TaskletsConfig.java
@@ -5,64 +5,16 @@
import com.baeldung.taskletsvschunks.tasklets.LinesWriter;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
-import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
-import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
-import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
-import org.springframework.batch.core.launch.JobLauncher;
-import org.springframework.batch.core.launch.support.SimpleJobLauncher;
+import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
-import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
-import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
-import org.springframework.batch.test.JobLauncherTestUtils;
-import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
-import javax.sql.DataSource;
-
@Configuration
-@EnableBatchProcessing
public class TaskletsConfig {
- @Autowired private JobBuilderFactory jobs;
-
- @Autowired private StepBuilderFactory steps;
-
- @Bean
- public JobLauncherTestUtils jobLauncherTestUtils() {
- return new JobLauncherTestUtils();
- }
-
- @Bean
- public JobRepository jobRepository() throws Exception {
- JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
- factory.setDataSource(dataSource());
- factory.setTransactionManager(transactionManager());
- return factory.getObject();
- }
-
- @Bean
- public DataSource dataSource() {
- DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setDriverClassName("org.sqlite.JDBC");
- dataSource.setUrl("jdbc:sqlite:repository.sqlite");
- return dataSource;
- }
-
- @Bean
- public PlatformTransactionManager transactionManager() {
- return new ResourcelessTransactionManager();
- }
-
- @Bean
- public JobLauncher jobLauncher() throws Exception {
- SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
- jobLauncher.setJobRepository(jobRepository());
- return jobLauncher;
- }
-
@Bean
public LinesReader linesReader() {
return new LinesReader();
@@ -79,36 +31,32 @@ public LinesWriter linesWriter() {
}
@Bean
- protected Step readLines() {
- return steps
- .get("readLines")
- .tasklet(linesReader())
+ protected Step readLines(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
+ return new StepBuilder("readLines", jobRepository)
+ .tasklet(linesReader(), transactionManager)
.build();
}
@Bean
- protected Step processLines() {
- return steps
- .get("processLines")
- .tasklet(linesProcessor())
+ protected Step processLines(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
+ return new StepBuilder("processLines", jobRepository)
+ .tasklet(linesProcessor(), transactionManager)
.build();
}
@Bean
- protected Step writeLines() {
- return steps
- .get("writeLines")
- .tasklet(linesWriter())
+ protected Step writeLines(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
+ return new StepBuilder("writeLines", jobRepository)
+ .tasklet(linesWriter(), transactionManager)
.build();
}
@Bean
- public Job job() {
- return jobs
- .get("taskletsJob")
- .start(readLines())
- .next(processLines())
- .next(writeLines())
+ public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
+ return new JobBuilder("taskletsJob", jobRepository)
+ .start(readLines(jobRepository, transactionManager))
+ .next(processLines(jobRepository, transactionManager))
+ .next(writeLines(jobRepository, transactionManager))
.build();
}
diff --git a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesReader.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesReader.java
index b1f58be4a4be..70f1a1b05d69 100644
--- a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesReader.java
+++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesReader.java
@@ -24,7 +24,7 @@ public class LinesReader implements Tasklet, StepExecutionListener {
@Override
public void beforeStep(StepExecution stepExecution) {
- lines = new ArrayList();
+ lines = new ArrayList<>();
fu = new FileUtils("taskletsvschunks/input/tasklets-vs-chunks.csv");
logger.debug("Lines Reader initialized.");
}
diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java
index c977d6ecabf3..8a8f62ae3127 100644
--- a/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java
+++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java
@@ -15,7 +15,7 @@ public static void main(String[] args) {
}
@Override
- public void run(String... args) throws Exception {
+ public void run(String... args) {
logger.info("Running conditional flow application...");
}
}
diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java
index 906a6e1d28a5..4954d9ffcdf2 100644
--- a/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java
+++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java
@@ -6,39 +6,49 @@
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
-import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
-import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
+import org.springframework.batch.core.job.builder.JobBuilder;
+import org.springframework.batch.core.launch.JobLauncher;
+import org.springframework.batch.core.launch.support.TaskExecutorJobLauncher;
+import org.springframework.batch.core.repository.JobRepository;
+import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
+import org.springframework.batch.core.step.builder.StepBuilder;
+import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
+import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
+import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
+import org.springframework.transaction.PlatformTransactionManager;
import static org.baeldung.conditionalflow.NumberInfoDecider.NOTIFY;
+import javax.sql.DataSource;
+
@Configuration
@EnableBatchProcessing
public class NumberInfoConfig {
@Bean
@Qualifier("NotificationStep")
- public Step notificationStep(StepBuilderFactory sbf) {
- return sbf.get("Notify step")
- .tasklet(new NotifierTasklet())
+ public Step notificationStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
+ return new StepBuilder("Notify step", jobRepository)
+ .tasklet(new NotifierTasklet(), transactionManager)
.build();
}
- public Step numberGeneratorStep(StepBuilderFactory sbf, int[] values, String prepend) {
- return sbf.get("Number generator")
- . chunk(1)
+ public Step numberGeneratorStep(JobRepository jobRepositories, PlatformTransactionManager transactionManager, int[] values, String prepend) {
+ return new StepBuilder("Number generator", jobRepositories)
+ . chunk(1, transactionManager)
.reader(new NumberInfoGenerator(values))
.processor(new NumberInfoClassifier())
.writer(new PrependingStdoutWriter<>(prepend))
.build();
}
- public Step numberGeneratorStepDecider(StepBuilderFactory sbf, int[] values, String prepend) {
- return sbf.get("Number generator decider")
- . chunk(1)
+ public Step numberGeneratorStepDecider(JobRepository jobRepositories, PlatformTransactionManager transactionManager, int[] values, String prepend) {
+ return new StepBuilder("Number generator decider", jobRepositories)
+ . chunk(1, transactionManager)
.reader(new NumberInfoGenerator(values))
.processor(new NumberInfoClassifierWithDecider())
.writer(new PrependingStdoutWriter<>(prepend))
@@ -47,10 +57,10 @@ public Step numberGeneratorStepDecider(StepBuilderFactory sbf, int[] values, Str
@Bean
@Qualifier("first_job")
- public Job numberGeneratorNonNotifierJob(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) {
+ public Job numberGeneratorNonNotifierJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("NotificationStep") Step notificationStep) {
int[] nonNotifierData = { -1, -2, -3 };
- Step step = numberGeneratorStep(stepBuilderFactory, nonNotifierData, "First Dataset Processor");
- return jobBuilderFactory.get("Number generator - first dataset")
+ Step step = numberGeneratorStep(jobRepository, transactionManager, nonNotifierData, "First Dataset Processor");
+ return new JobBuilder("Number generator - first dataset", jobRepository)
.start(step)
.on(NOTIFY)
.to(notificationStep)
@@ -63,10 +73,10 @@ public Job numberGeneratorNonNotifierJob(JobBuilderFactory jobBuilderFactory, St
@Bean
@Qualifier("second_job")
- public Job numberGeneratorNotifierJob(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) {
+ public Job numberGeneratorNotifierJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("NotificationStep") Step notificationStep) {
int[] billableData = { 11, -2, -3 };
- Step dataProviderStep = numberGeneratorStep(stepBuilderFactory, billableData, "Second Dataset Processor");
- return jobBuilderFactory.get("Number generator - second dataset")
+ Step dataProviderStep = numberGeneratorStep(jobRepository, transactionManager, billableData, "Second Dataset Processor");
+ return new JobBuilder("Number generator - second dataset", jobRepository)
.start(dataProviderStep)
.on(NOTIFY)
.to(notificationStep)
@@ -77,10 +87,10 @@ public Job numberGeneratorNotifierJob(JobBuilderFactory jobBuilderFactory, StepB
@Bean
@Qualifier("third_job")
@Primary
- public Job numberGeneratorNotifierJobWithDecider(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) {
+ public Job numberGeneratorNotifierJobWithDecider(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("NotificationStep") Step notificationStep) {
int[] billableData = { 11, -2, -3 };
- Step dataProviderStep = numberGeneratorStepDecider(stepBuilderFactory, billableData, "Third Dataset Processor");
- return jobBuilderFactory.get("Number generator - third dataset")
+ Step dataProviderStep = numberGeneratorStepDecider(jobRepository, transactionManager, billableData, "Third Dataset Processor");
+ return new JobBuilder("Number generator - third dataset", jobRepository)
.start(dataProviderStep)
.next(new NumberInfoDecider())
.on(NOTIFY)
@@ -88,4 +98,39 @@ public Job numberGeneratorNotifierJobWithDecider(JobBuilderFactory jobBuilderFac
.end()
.build();
}
+
+ @Bean(name = "jobRepository")
+ public JobRepository getJobRepository() throws Exception {
+ JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
+ factory.setDataSource(dataSource());
+ factory.setTransactionManager(getTransactionManager());
+ // JobRepositoryFactoryBean's methods Throws Generic Exception,
+ // it would have been better to have a specific one
+ factory.afterPropertiesSet();
+ return factory.getObject();
+ }
+
+ @Bean(name = "dataSource")
+ public DataSource dataSource() {
+ EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
+ return builder.setType(EmbeddedDatabaseType.H2)
+ .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql")
+ .addScript("classpath:org/springframework/batch/core/schema-h2.sql")
+ .build();
+ }
+
+ @Bean(name = "transactionManager")
+ public PlatformTransactionManager getTransactionManager() {
+ return new ResourcelessTransactionManager();
+ }
+
+ @Bean(name = "jobLauncher")
+ public JobLauncher getJobLauncher() throws Exception {
+ TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher();
+ // SimpleJobLauncher's methods Throws Generic Exception,
+ // it would have been better to have a specific one
+ jobLauncher.setJobRepository(getJobRepository());
+ jobLauncher.afterPropertiesSet();
+ return jobLauncher;
+ }
}
diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java
index 0d1db66fe95e..99ec151cba9c 100644
--- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java
+++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java
@@ -7,9 +7,8 @@
public class NotifierTasklet implements Tasklet {
@Override
- public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
- System.err.println("[" + chunkContext.getStepContext()
- .getJobName() + "] contains interesting data!!");
+ public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) {
+ System.err.println("[" + chunkContext.getStepContext().getJobName() + "] contains interesting data!!");
return RepeatStatus.FINISHED;
}
}
diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java
index fdb28263e74a..71d88e3f0ae5 100644
--- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java
+++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java
@@ -29,7 +29,7 @@ public void afterProcess(NumberInfo item, Integer result) {
}
@Override
- public Integer process(NumberInfo numberInfo) throws Exception {
- return Integer.valueOf(numberInfo.getNumber());
+ public Integer process(NumberInfo numberInfo) {
+ return numberInfo.getNumber();
}
}
diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java
index 4a8b7f19637b..26a225d715de 100644
--- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java
+++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java
@@ -7,7 +7,7 @@
public class NumberInfoClassifierWithDecider extends ItemListenerSupport implements ItemProcessor {
@Override
- public Integer process(NumberInfo numberInfo) throws Exception {
+ public Integer process(NumberInfo numberInfo) {
return Integer.valueOf(numberInfo.getNumber());
}
}
diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java
index 9ffea1e79821..abadb78e9306 100644
--- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java
+++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java
@@ -1,7 +1,6 @@
package org.baeldung.conditionalflow.step;
-import java.util.List;
-
+import org.springframework.batch.item.Chunk;
import org.springframework.batch.item.ItemWriter;
public class PrependingStdoutWriter implements ItemWriter {
@@ -12,8 +11,8 @@ public PrependingStdoutWriter(String prependText) {
}
@Override
- public void write(List extends T> list) {
- for (T listItem : list) {
+ public void write(Chunk extends T> chunk) {
+ for (T listItem : chunk) {
System.out.println(prependText + " " + listItem.toString());
}
}
diff --git a/spring-batch/src/main/resources/output/output1.xml b/spring-batch/src/main/resources/output/output1.xml
index 838d04882a50..78bc7349e8da 100644
--- a/spring-batch/src/main/resources/output/output1.xml
+++ b/spring-batch/src/main/resources/output/output1.xml
@@ -1,21 +1,21 @@
-
- 10000.0
- 2015-10-31 00:00:00
- 1234
- devendra
-
-
- 12321.0
- 2015-12-03 00:00:00
- 2134
- john
-
-
- 23411.0
- 2015-02-02 00:00:00
- 2134
- robin
-
+
+ 10000.0
+ 2015-10-31 00:00:00
+ 1234
+ devendra
+
+
+ 12321.0
+ 2015-12-03 00:00:00
+ 2134
+ john
+
+
+ 23411.0
+ 2015-02-02 00:00:00
+ 2134
+ robin
+
\ No newline at end of file
diff --git a/spring-batch/src/main/resources/output/output2.xml b/spring-batch/src/main/resources/output/output2.xml
index 838d04882a50..78bc7349e8da 100644
--- a/spring-batch/src/main/resources/output/output2.xml
+++ b/spring-batch/src/main/resources/output/output2.xml
@@ -1,21 +1,21 @@
-
- 10000.0
- 2015-10-31 00:00:00
- 1234
- devendra
-
-
- 12321.0
- 2015-12-03 00:00:00
- 2134
- john
-
-
- 23411.0
- 2015-02-02 00:00:00
- 2134
- robin
-
+
+ 10000.0
+ 2015-10-31 00:00:00
+ 1234
+ devendra
+
+
+ 12321.0
+ 2015-12-03 00:00:00
+ 2134
+ john
+
+
+ 23411.0
+ 2015-02-02 00:00:00
+ 2134
+ robin
+
\ No newline at end of file
diff --git a/spring-batch/src/main/resources/output/output3.xml b/spring-batch/src/main/resources/output/output3.xml
index 838d04882a50..78bc7349e8da 100644
--- a/spring-batch/src/main/resources/output/output3.xml
+++ b/spring-batch/src/main/resources/output/output3.xml
@@ -1,21 +1,21 @@
-
- 10000.0
- 2015-10-31 00:00:00
- 1234
- devendra
-
-
- 12321.0
- 2015-12-03 00:00:00
- 2134
- john
-
-
- 23411.0
- 2015-02-02 00:00:00
- 2134
- robin
-
+
+ 10000.0
+ 2015-10-31 00:00:00
+ 1234
+ devendra
+
+
+ 12321.0
+ 2015-12-03 00:00:00
+ 2134
+ john
+
+
+ 23411.0
+ 2015-02-02 00:00:00
+ 2134
+ robin
+
\ No newline at end of file
diff --git a/spring-batch/src/main/resources/output/output4.xml b/spring-batch/src/main/resources/output/output4.xml
index 838d04882a50..78bc7349e8da 100644
--- a/spring-batch/src/main/resources/output/output4.xml
+++ b/spring-batch/src/main/resources/output/output4.xml
@@ -1,21 +1,21 @@
-
- 10000.0
- 2015-10-31 00:00:00
- 1234
- devendra
-
-
- 12321.0
- 2015-12-03 00:00:00
- 2134
- john
-
-
- 23411.0
- 2015-02-02 00:00:00
- 2134
- robin
-
+
+ 10000.0
+ 2015-10-31 00:00:00
+ 1234
+ devendra
+
+
+ 12321.0
+ 2015-12-03 00:00:00
+ 2134
+ john
+
+
+ 23411.0
+ 2015-02-02 00:00:00
+ 2134
+ robin
+
\ No newline at end of file
diff --git a/spring-batch/src/main/resources/output/output5.xml b/spring-batch/src/main/resources/output/output5.xml
index 838d04882a50..78bc7349e8da 100644
--- a/spring-batch/src/main/resources/output/output5.xml
+++ b/spring-batch/src/main/resources/output/output5.xml
@@ -1,21 +1,21 @@
-
- 10000.0
- 2015-10-31 00:00:00
- 1234
- devendra
-
-
- 12321.0
- 2015-12-03 00:00:00
- 2134
- john
-
-
- 23411.0
- 2015-02-02 00:00:00
- 2134
- robin
-
+
+ 10000.0
+ 2015-10-31 00:00:00
+ 1234
+ devendra
+
+
+ 12321.0
+ 2015-12-03 00:00:00
+ 2134
+ john
+
+
+ 23411.0
+ 2015-02-02 00:00:00
+ 2134
+ robin
+
\ No newline at end of file
diff --git a/spring-batch/src/main/resources/spring-batch-intro.xml b/spring-batch/src/main/resources/spring-batch-intro.xml
index 2a7c1e7c4a0d..bb11ea0efdd9 100644
--- a/spring-batch/src/main/resources/spring-batch-intro.xml
+++ b/spring-batch/src/main/resources/spring-batch-intro.xml
@@ -17,7 +17,7 @@
+ value="username,userid,transactiondate,amount" />
@@ -33,11 +33,11 @@
-
+
-
+
com.baeldung.batch.model.Transaction
diff --git a/spring-batch/src/main/resources/spring.xml b/spring-batch/src/main/resources/spring.xml
index dea261c5e612..fc7e86794130 100644
--- a/spring-batch/src/main/resources/spring.xml
+++ b/spring-batch/src/main/resources/spring.xml
@@ -9,8 +9,8 @@
-
-
+
+
@@ -18,8 +18,8 @@
-
+ location="org/springframework/batch/core/schema-drop-h2.sql" />
+
@@ -31,7 +31,6 @@
class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
-
{
- assertThat(stepExecution.getWriteCount(), is(8));
+ assertEquals(8L, stepExecution.getWriteCount());
});
}
diff --git a/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java
index 4655117b856e..311bd828cbd4 100644
--- a/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java
+++ b/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java
@@ -1,22 +1,21 @@
package com.baeldung.batchtesting;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.springframework.batch.test.AssertFile.assertFileEquals;
-import java.util.Arrays;
+import java.util.List;
-import com.baeldung.batchtesting.SpringBatchConfiguration;
import com.baeldung.batchtesting.model.Book;
import com.baeldung.batchtesting.model.BookRecord;
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.StepExecution;
+import org.springframework.batch.item.Chunk;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.json.JsonFileItemWriter;
-import org.springframework.batch.test.AssertFile;
import org.springframework.batch.test.JobRepositoryTestUtils;
import org.springframework.batch.test.MetaDataInstanceFactory;
import org.springframework.batch.test.StepScopeTestUtils;
@@ -24,21 +23,12 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.core.io.FileSystemResource;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.TestExecutionListeners;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
-import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
-@RunWith(SpringRunner.class)
@SpringBatchTest
@EnableAutoConfiguration
@ContextConfiguration(classes = { SpringBatchConfiguration.class })
-@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class })
-@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class SpringBatchStepScopeIntegrationTest {
private static final String TEST_OUTPUT = "src/test/resources/output/actual-output.json";
@@ -62,7 +52,7 @@ private JobParameters defaultJobParameters() {
return paramsBuilder.toJobParameters();
}
- @After
+ @AfterEach
public void cleanUp() {
jobRepositoryTestUtils.removeJobExecutions();
}
@@ -80,11 +70,11 @@ public void givenMockedStep_whenReaderCalled_thenSuccess() throws Exception {
while ((bookRecord = itemReader.read()) != null) {
// then
- assertThat(bookRecord.getBookName(), is("Foundation"));
- assertThat(bookRecord.getBookAuthor(), is("Asimov I."));
- assertThat(bookRecord.getBookISBN(), is("ISBN 12839"));
- assertThat(bookRecord.getBookFormat(), is("hardcover"));
- assertThat(bookRecord.getPublishingYear(), is("2018"));
+ assertEquals("Foundation", bookRecord.getBookName());
+ assertEquals("Asimov I.", bookRecord.getBookAuthor());
+ assertEquals("ISBN 12839", bookRecord.getBookISBN());
+ assertEquals("hardcover", bookRecord.getBookFormat());
+ assertEquals("2018", bookRecord.getPublishingYear());
}
itemReader.close();
return null;
@@ -106,12 +96,12 @@ public void givenMockedStep_whenWriterCalled_thenSuccess() throws Exception {
StepScopeTestUtils.doInStepScope(stepExecution, () -> {
jsonItemWriter.open(stepExecution.getExecutionContext());
- jsonItemWriter.write(Arrays.asList(demoBook));
+ jsonItemWriter.write(new Chunk<>(List.of(demoBook)));
jsonItemWriter.close();
return null;
});
// then
- AssertFile.assertFileEquals(expectedResult, actualResult);
+ assertFileEquals(expectedResult, actualResult);
}
}
diff --git a/spring-batch/src/test/java/com/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java
index 1132e4d5e26a..109342076b2b 100644
--- a/spring-batch/src/test/java/com/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java
+++ b/spring-batch/src/test/java/com/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java
@@ -1,25 +1,29 @@
package com.baeldung.taskletsvschunks.chunks;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
import com.baeldung.taskletsvschunks.config.ChunksConfig;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+
+import org.junit.jupiter.api.Test;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.test.JobLauncherTestUtils;
+import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = ChunksConfig.class)
+@SpringBatchTest
+@EnableAutoConfiguration
+@ContextConfiguration(classes = ChunksConfig.class)
public class ChunksIntegrationTest {
- @Autowired private JobLauncherTestUtils jobLauncherTestUtils;
+ @Autowired
+ private JobLauncherTestUtils jobLauncherTestUtils;
@Test
public void givenChunksJob_WhenJobEnds_ThenStatusCompleted() throws Exception {
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
- Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
+ assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
}
\ No newline at end of file
diff --git a/spring-batch/src/test/java/com/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java
index 2e1ad031aa33..103b1a209654 100644
--- a/spring-batch/src/test/java/com/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java
+++ b/spring-batch/src/test/java/com/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java
@@ -1,25 +1,29 @@
package com.baeldung.taskletsvschunks.tasklets;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
import com.baeldung.taskletsvschunks.config.TaskletsConfig;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+
+import org.junit.jupiter.api.Test;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.test.JobLauncherTestUtils;
+import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-@RunWith(SpringJUnit4ClassRunner.class)
+@SpringBatchTest
+@EnableAutoConfiguration
@ContextConfiguration(classes = TaskletsConfig.class)
public class TaskletsIntegrationTest {
- @Autowired private JobLauncherTestUtils jobLauncherTestUtils;
+ @Autowired
+ private JobLauncherTestUtils jobLauncherTestUtils;
@Test
public void givenTaskletsJob_WhenJobEnds_ThenStatusCompleted() throws Exception {
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
- Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
+ assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
}
\ No newline at end of file
diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java
index e73cb17494f3..a50ad0455ce3 100644
--- a/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java
+++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java
@@ -1,8 +1,10 @@
package org.baeldung.conditionalflow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
import org.baeldung.conditionalflow.config.NumberInfoConfig;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.StepExecution;
@@ -10,26 +12,16 @@
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
-import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.TestExecutionListeners;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
-import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import java.util.Collection;
import java.util.Iterator;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(SpringRunner.class)
@SpringBatchTest
@EnableAutoConfiguration
@ContextConfiguration(classes = { NumberInfoConfig.class })
-@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class })
-@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class DeciderJobIntegrationTest {
+
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@@ -39,8 +31,7 @@ public void givenNumberGeneratorDecider_whenDeciderRuns_thenStatusIsNotify() thr
Collection actualStepExecutions = jobExecution.getStepExecutions();
ExitStatus actualJobExitStatus = jobExecution.getExitStatus();
- assertEquals("COMPLETED", actualJobExitStatus.getExitCode()
- .toString());
+ assertEquals("COMPLETED", actualJobExitStatus.getExitCode());
assertEquals(2, actualStepExecutions.size());
boolean notifyStepDidRun = false;
Iterator iterator = actualStepExecutions.iterator();
diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java
index dc396b38da55..bdecee5621cb 100644
--- a/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java
+++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java
@@ -5,10 +5,10 @@
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
-import org.junit.runner.RunWith;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
-@RunWith(SpringJUnit4ClassRunner.class)
+@ExtendWith(SpringExtension.class)
class NumberInfoUnitTest {
@Test
diff --git a/spring-batch/src/test/resources/output/actual-output.json b/spring-batch/src/test/resources/output/actual-output.json
index 1fd6cfcf378c..32ad8b7ead0e 100644
--- a/spring-batch/src/test/resources/output/actual-output.json
+++ b/spring-batch/src/test/resources/output/actual-output.json
@@ -1,3 +1,10 @@
[
- {"author":"Grisham J.","name":"The Firm"}
+ {"author":"Asimov I.","name":"Foundation"},
+ {"author":"Strugatski A.","name":"Roadside Picnic"},
+ {"author":"Murakami H.","name":"Norwegian Wood"},
+ {"author":"Brown D.","name":"Davinci Code"},
+ {"author":"Dick K. P.","name":"Ubik"},
+ {"author":"King S.","name":"JFK"},
+ {"author":"Sagan C.","name":"Contact"},
+ {"author":"Huxley A.","name":"Brave New World"}
]
diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml
index 6d542f40ddb2..d46612393ded 100644
--- a/spring-boot-modules/pom.xml
+++ b/spring-boot-modules/pom.xml
@@ -63,10 +63,6 @@
spring-boot-nashorn
spring-boot-parent
spring-boot-performance
- spring-boot-properties
- spring-boot-properties-2
- spring-boot-properties-3
- spring-boot-properties-migrator-demo
spring-boot-property-exp
spring-boot-request-params
spring-boot-runtime
@@ -84,15 +80,20 @@
spring-boot-data-2
spring-boot-validation
spring-boot-data-3
- spring-caching
+ spring-caching
spring-caching-2
spring-boot-redis
spring-boot-cassandre
spring-boot-react
- spring-boot-3
+
spring-boot-3-native
spring-boot-3-observation
spring-boot-3-test-pitfalls
+ spring-boot-resilience4j
+ spring-boot-properties
+ spring-boot-properties-2
+ spring-boot-properties-3
+ spring-boot-properties-migrator-demo
diff --git a/spring-boot-modules/spring-boot-3-native/pom.xml b/spring-boot-modules/spring-boot-3-native/pom.xml
index 5382b8413cb8..2bbc11afd206 100644
--- a/spring-boot-modules/spring-boot-3-native/pom.xml
+++ b/spring-boot-modules/spring-boot-3-native/pom.xml
@@ -56,17 +56,22 @@
-agentlib:native-image-agent=config-output-dir=target/native-image
-
- true
-
+
+
+ process-aot
+
+ process-aot
+
+
+
-->
-
-
-
+
+
+
-
-
+
+
diff --git a/spring-boot-modules/spring-boot-3-observation/README.md b/spring-boot-modules/spring-boot-3-observation/README.md
index edfb23ce2b1c..6d8c02af67b7 100644
--- a/spring-boot-modules/spring-boot-3-observation/README.md
+++ b/spring-boot-modules/spring-boot-3-observation/README.md
@@ -1,2 +1,3 @@
## Relevant Articles
- [Observability with Spring Boot 3](https://www.baeldung.com/spring-boot-3-observability)
+- [Intercept SQL Logging with P6Spy](https://www.baeldung.com/java-p6spy-intercept-sql-logging)
diff --git a/spring-boot-modules/spring-boot-3-observation/pom.xml b/spring-boot-modules/spring-boot-3-observation/pom.xml
index ed613ee98ea6..f69ce699bc9c 100644
--- a/spring-boot-modules/spring-boot-3-observation/pom.xml
+++ b/spring-boot-modules/spring-boot-3-observation/pom.xml
@@ -1,7 +1,7 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
spring-boot-3-observation
0.0.1-SNAPSHOT
@@ -54,6 +54,25 @@
org.springframework.boot
spring-boot-starter-aop
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+ org.springframework.boot
+ spring-boot-starter-jdbc
+
+
+
+ com.github.gavlyukovskiy
+ p6spy-spring-boot-starter
+ 1.9.0
+
+
+ com.h2database
+ h2
+ runtime
+
org.springframework.boot
spring-boot-devtools
@@ -63,4 +82,8 @@
+
+ com.baeldung.samples.SimpleObservationApplication
+
+
diff --git a/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/SampleP6SpyApplication.java b/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/SampleP6SpyApplication.java
new file mode 100644
index 000000000000..000ffea9c9f4
--- /dev/null
+++ b/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/SampleP6SpyApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.p6spy;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class SampleP6SpyApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SampleP6SpyApplication.class, args);
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/controllers/JDBCController.java b/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/controllers/JDBCController.java
new file mode 100644
index 000000000000..d09e83916552
--- /dev/null
+++ b/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/controllers/JDBCController.java
@@ -0,0 +1,54 @@
+package com.baeldung.p6spy.controllers;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.sql.DataSource;
+import java.sql.Connection;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+@RestController
+@RequestMapping("jdbc")
+public class JDBCController {
+
+ @Autowired
+ private DataSource dataSource;
+
+ @RequestMapping("/commit")
+ public List
-
+
2.2
3.1.7
diff --git a/spring-boot-modules/spring-boot-gradle-2/.gitignore b/spring-boot-modules/spring-boot-gradle-2/.gitignore
new file mode 100644
index 000000000000..c2065bc26202
--- /dev/null
+++ b/spring-boot-modules/spring-boot-gradle-2/.gitignore
@@ -0,0 +1,37 @@
+HELP.md
+.gradle
+build/
+!gradle/wrapper/gradle-wrapper.jar
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+bin/
+!**/src/main/**/bin/
+!**/src/test/**/bin/
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+out/
+!**/src/main/**/out/
+!**/src/test/**/out/
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+
+### VS Code ###
+.vscode/
diff --git a/spring-boot-modules/spring-boot-gradle-2/build.gradle b/spring-boot-modules/spring-boot-gradle-2/build.gradle
new file mode 100644
index 000000000000..abfbca31230a
--- /dev/null
+++ b/spring-boot-modules/spring-boot-gradle-2/build.gradle
@@ -0,0 +1,34 @@
+plugins {
+ id 'java'
+ id 'org.springframework.boot' version '3.0.6'
+ id 'io.spring.dependency-management' version '1.1.0'
+}
+
+group = 'com.baeldung'
+version = '0.0.1-SNAPSHOT'
+sourceCompatibility = '17'
+
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ implementation 'org.springframework.boot:spring-boot-starter-web'
+ testImplementation 'org.springframework.boot:spring-boot-starter-test'
+}
+
+tasks.named('test') {
+ useJUnitPlatform()
+}
+
+tasks.named("bootJar"){
+ launchScript{
+ enabled = true
+ }
+ archiveFileName = "bael-6094.${archiveExtension.get()}"
+}
+
+
+tasks.named("bootBuildImage") {
+ imageName = 'bael-6094:latest'
+}
diff --git a/spring-boot-modules/spring-boot-gradle-2/gradle/wrapper/gradle-wrapper.jar b/spring-boot-modules/spring-boot-gradle-2/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000000..943f0cbfa754
Binary files /dev/null and b/spring-boot-modules/spring-boot-gradle-2/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/spring-boot-modules/spring-boot-gradle-2/gradle/wrapper/gradle-wrapper.properties b/spring-boot-modules/spring-boot-gradle-2/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000000..37aef8d3f0c9
--- /dev/null
+++ b/spring-boot-modules/spring-boot-gradle-2/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
+networkTimeout=10000
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/spring-boot-modules/spring-boot-gradle-2/gradlew b/spring-boot-modules/spring-boot-gradle-2/gradlew
new file mode 100644
index 000000000000..65dcd68d65c8
--- /dev/null
+++ b/spring-boot-modules/spring-boot-gradle-2/gradlew
@@ -0,0 +1,244 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+# Collect all arguments for the java command;
+# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
+# shell script including quotes and variable substitutions, so put them in
+# double quotes to make sure that they get re-expanded; and
+# * put everything else in single quotes, so that it's not re-expanded.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/spring-boot-modules/spring-boot-gradle-2/gradlew.bat b/spring-boot-modules/spring-boot-gradle-2/gradlew.bat
new file mode 100644
index 000000000000..93e3f59f135d
--- /dev/null
+++ b/spring-boot-modules/spring-boot-gradle-2/gradlew.bat
@@ -0,0 +1,92 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/spring-boot-modules/spring-boot-gradle-2/settings.gradle b/spring-boot-modules/spring-boot-gradle-2/settings.gradle
new file mode 100644
index 000000000000..16004624dd41
--- /dev/null
+++ b/spring-boot-modules/spring-boot-gradle-2/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = 'spring-boot-gradle-2'
diff --git a/spring-boot-modules/spring-boot-gradle-2/src/main/java/com/baeldung/gradle/SpringBootGradle2Application.java b/spring-boot-modules/spring-boot-gradle-2/src/main/java/com/baeldung/gradle/SpringBootGradle2Application.java
new file mode 100644
index 000000000000..9d5be0bcbcc3
--- /dev/null
+++ b/spring-boot-modules/spring-boot-gradle-2/src/main/java/com/baeldung/gradle/SpringBootGradle2Application.java
@@ -0,0 +1,21 @@
+package com.baeldung.gradle;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@SpringBootApplication
+@RestController
+public class SpringBootGradle2Application {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SpringBootGradle2Application.class, args);
+ }
+
+ @GetMapping("/hello")
+ public String hello() {
+ return "Hello World!";
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-gradle-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-gradle-2/src/main/resources/application.properties
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/spring-boot-modules/spring-boot-gradle-2/src/main/resources/application.properties
@@ -0,0 +1 @@
+
diff --git a/spring-boot-modules/spring-boot-gradle-2/src/test/java/com/baeldung/gradle/SpringBootGradle2ApplicationTests.java b/spring-boot-modules/spring-boot-gradle-2/src/test/java/com/baeldung/gradle/SpringBootGradle2ApplicationTests.java
new file mode 100644
index 000000000000..dd3031c1d5e1
--- /dev/null
+++ b/spring-boot-modules/spring-boot-gradle-2/src/test/java/com/baeldung/gradle/SpringBootGradle2ApplicationTests.java
@@ -0,0 +1,33 @@
+package com.baeldung.gradle;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
+import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
+
+//@SpringBootTest
+//class {
+//
+// @Test
+// void contextLoads() {
+// }
+//
+//}
+
+@SpringBootTest
+@AutoConfigureMockMvc
+public class SpringBootGradle2ApplicationTests {
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @Test
+ public void givenHelloEndPoint_whenCallingHello_ThenGettingHelloWorld() throws Exception {
+ mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
+ .andExpect(MockMvcResultMatchers.status().isOk())
+ .andExpect(MockMvcResultMatchers.content().string("Hello World!"));
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-graphql/pom.xml b/spring-boot-modules/spring-boot-graphql/pom.xml
index bb475679adeb..628babbd3f33 100644
--- a/spring-boot-modules/spring-boot-graphql/pom.xml
+++ b/spring-boot-modules/spring-boot-graphql/pom.xml
@@ -1,7 +1,7 @@
+ 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">
4.0.0
spring-boot-graphql
spring-boot-graphql
diff --git a/spring-boot-modules/spring-boot-keycloak-2/README.md b/spring-boot-modules/spring-boot-keycloak-2/README.md
index d372132a6a78..e4f8b1904b17 100644
--- a/spring-boot-modules/spring-boot-keycloak-2/README.md
+++ b/spring-boot-modules/spring-boot-keycloak-2/README.md
@@ -4,3 +4,4 @@ This module contains articles about Keycloak in Spring Boot projects.
## Relevant articles:
- [Disabling Keycloak Security in Spring Boot](https://www.baeldung.com/spring-keycloak-security-disable)
+- [Search Users With Keycloak in Java](https://www.baeldung.com/java-keycloak-search-users)
diff --git a/spring-boot-modules/spring-boot-keycloak-2/pom.xml b/spring-boot-modules/spring-boot-keycloak-2/pom.xml
index 572986e8c4e3..c5bb97fb211d 100644
--- a/spring-boot-modules/spring-boot-keycloak-2/pom.xml
+++ b/spring-boot-modules/spring-boot-keycloak-2/pom.xml
@@ -16,9 +16,9 @@
0.0.1-SNAPSHOT
../../parent-boot-2
-
+
- 21.0.1
+ 21.0.1
@@ -49,8 +49,8 @@
org.keycloak
keycloak-admin-client
${keycloak.version}
-
-
+
+
org.keycloak
keycloak-core
diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml
index 688b45d6d01c..a4d6e18fd51b 100644
--- a/spring-boot-modules/spring-boot-keycloak/pom.xml
+++ b/spring-boot-modules/spring-boot-keycloak/pom.xml
@@ -101,11 +101,11 @@
-
-
+
+
com.baeldung.keycloak.SpringBoot
- 4.0.0
- 2.5.0
+ 4.0.0
+ 2.5.0
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-2/README.md b/spring-boot-modules/spring-boot-libraries-2/README.md
index 0da16a820460..5c6b93469da9 100644
--- a/spring-boot-modules/spring-boot-libraries-2/README.md
+++ b/spring-boot-modules/spring-boot-libraries-2/README.md
@@ -9,4 +9,6 @@ This module contains articles about various Spring Boot libraries
- [An Introduction to Kong](https://www.baeldung.com/kong)
- [Scanning Java Annotations At Runtime](https://www.baeldung.com/java-scan-annotations-runtime)
- [Guide to Resilience4j With Spring Boot](https://www.baeldung.com/spring-boot-resilience4j)
-More articles: [[prev -->]](/spring-boot-modules/spring-boot-libraries)
+- [Using OpenAI ChatGPT APIs in Spring Boot](https://www.baeldung.com/spring-boot-chatgpt-api-openai)
+- [Introduction to Spring Modulith](https://www.baeldung.com/spring-modulith)
+- More articles: [[prev -->]](/spring-boot-modules/spring-boot-libraries)
diff --git a/spring-boot-modules/spring-boot-libraries-2/pom.xml b/spring-boot-modules/spring-boot-libraries-2/pom.xml
index 4409db06725f..6d9401f4bc2c 100644
--- a/spring-boot-modules/spring-boot-libraries-2/pom.xml
+++ b/spring-boot-modules/spring-boot-libraries-2/pom.xml
@@ -11,6 +11,18 @@
1.0.0-SNAPSHOT
+
+
+
+ org.springframework.experimental
+ spring-modulith-bom
+ 0.5.1
+ import
+ pom
+
+
+
+
org.springframework.boot
@@ -87,6 +99,15 @@
2.34.0
test
+
+ org.springframework.experimental
+ spring-modulith-api
+
+
+ org.springframework.experimental
+ spring-modulith-starter-test
+ test
+
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/Application.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/Application.java
new file mode 100644
index 000000000000..a8c3e48661c0
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/Application.java
@@ -0,0 +1,21 @@
+package com.baeldung.modulith;
+
+import com.baeldung.modulith.product.ProductService;
+import com.baeldung.modulith.product.internal.Product;
+import org.jobrunr.autoconfigure.JobRunrAutoConfiguration;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.scheduling.annotation.EnableAsync;
+
+@EnableAsync
+@SpringBootApplication
+@EnableAutoConfiguration(exclude = { JobRunrAutoConfiguration.class})
+public class Application {
+
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args)
+ .getBean(ProductService.class)
+ .create(new Product("baeldung", "course", 10));
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/notification/NotificationDTO.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/notification/NotificationDTO.java
new file mode 100644
index 000000000000..a8fb346daa2f
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/notification/NotificationDTO.java
@@ -0,0 +1,39 @@
+package com.baeldung.modulith.notification;
+
+import java.util.Date;
+
+public class NotificationDTO {
+ private Date date;
+ private String format;
+ private String productName;
+
+ public NotificationDTO(Date date, String format, String productName) {
+ this.date = date;
+ this.format = format;
+ this.productName = productName;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ public String getFormat() {
+ return format;
+ }
+
+ public void setFormat(String format) {
+ this.format = format;
+ }
+
+ public String getProductName() {
+ return productName;
+ }
+
+ public void setProductName(String productName) {
+ this.productName = productName;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/notification/NotificationService.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/notification/NotificationService.java
new file mode 100644
index 000000000000..7789798bbe5e
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/notification/NotificationService.java
@@ -0,0 +1,42 @@
+package com.baeldung.modulith.notification;
+
+import com.baeldung.modulith.notification.internal.Notification;
+import com.baeldung.modulith.notification.internal.NotificationType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.modulith.ApplicationModuleListener;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Service;
+
+@Service
+public class NotificationService {
+
+ private static final Logger LOG = LoggerFactory.getLogger(NotificationService.class);
+
+ public void createNotification(NotificationDTO notificationDTO) {
+ Notification notification = toEntity(notificationDTO);
+ LOG.info("Received notification by module dependency for product {} in date {} by {}.", notification.getProductName()
+ , notification.getDate(), notification.getFormat());
+ }
+
+ @Async
+ @ApplicationModuleListener
+ public void notificationEvent(NotificationDTO event) {
+ Notification notification = toEntity(event);
+ LOG.info("Received notification by event for product {} in date {} by {}.", notification.getProductName()
+ , notification.getDate(), notification.getFormat());
+ }
+
+ private Notification toEntity(NotificationDTO notificationDTO) {
+ Notification notification = new Notification();
+ notification.setDate(notificationDTO.getDate());
+ if (notificationDTO.getFormat().equals("SMS")) {
+ notification.setFormat(NotificationType.SMS);
+ }
+ if (notificationDTO.getFormat().equals("EMAIL")) {
+ notification.setFormat(NotificationType.EMAIL);
+ }
+ notification.setProductName(notificationDTO.getProductName());
+ return notification;
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/notification/internal/Notification.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/notification/internal/Notification.java
new file mode 100644
index 000000000000..0b1ce85d26f0
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/notification/internal/Notification.java
@@ -0,0 +1,37 @@
+package com.baeldung.modulith.notification.internal;
+
+import java.util.Date;
+
+public class Notification {
+ private Date date;
+ private NotificationType format;
+ private String productName;
+
+ public Notification() {
+
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ public NotificationType getFormat() {
+ return format;
+ }
+
+ public void setFormat(NotificationType format) {
+ this.format = format;
+ }
+
+ public String getProductName() {
+ return productName;
+ }
+
+ public void setProductName(String productName) {
+ this.productName = productName;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/notification/internal/NotificationType.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/notification/internal/NotificationType.java
new file mode 100644
index 000000000000..45870e52b9e7
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/notification/internal/NotificationType.java
@@ -0,0 +1,5 @@
+package com.baeldung.modulith.notification.internal;
+
+public enum NotificationType {
+ EMAIL, SMS
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/product/ProductService.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/product/ProductService.java
new file mode 100644
index 000000000000..46d87fc53989
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/product/ProductService.java
@@ -0,0 +1,26 @@
+package com.baeldung.modulith.product;
+
+import com.baeldung.modulith.notification.NotificationDTO;
+import com.baeldung.modulith.notification.NotificationService;
+import com.baeldung.modulith.product.internal.Product;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.stereotype.Service;
+
+import java.util.Date;
+
+@Service
+public class ProductService {
+
+ private final ApplicationEventPublisher events;
+ private final NotificationService notificationService;
+
+ public ProductService(ApplicationEventPublisher events, NotificationService notificationService) {
+ this.events = events;
+ this.notificationService = notificationService;
+ }
+
+ public void create(Product product) {
+ notificationService.createNotification(new NotificationDTO(new Date(), "SMS", product.getName()));
+ events.publishEvent(new NotificationDTO(new Date(), "SMS", product.getName()));
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/product/internal/Product.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/product/internal/Product.java
new file mode 100644
index 000000000000..d989906b63f2
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/modulith/product/internal/Product.java
@@ -0,0 +1,38 @@
+package com.baeldung.modulith.product.internal;
+
+public class Product {
+
+ private String name;
+ private String description;
+ private int price;
+
+ public Product(String name, String description, int price) {
+ this.name = name;
+ this.description = description;
+ this.price = price;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public void setPrice(int price) {
+ this.price = price;
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/config/OpenAIRestTemplateConfig.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/config/OpenAIRestTemplateConfig.java
new file mode 100644
index 000000000000..b832ee4264c7
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/config/OpenAIRestTemplateConfig.java
@@ -0,0 +1,25 @@
+package com.baeldung.openapi.config;
+
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.client.RestTemplate;
+
+@Configuration
+public class OpenAIRestTemplateConfig {
+
+ @Value("${openai.api.key}")
+ private String openaiApiKey;
+
+ @Bean
+ @Qualifier("openaiRestTemplate")
+ public RestTemplate openaiRestTemplate() {
+ RestTemplate restTemplate = new RestTemplate();
+ restTemplate.getInterceptors().add((request, body, execution) -> {
+ request.getHeaders().add("Authorization", "Bearer " + openaiApiKey);
+ return execution.execute(request, body);
+ });
+ return restTemplate;
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/controller/ChatController.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/controller/ChatController.java
new file mode 100644
index 000000000000..129d23358218
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/controller/ChatController.java
@@ -0,0 +1,48 @@
+package com.baeldung.openapi.controller;
+
+import com.baeldung.openapi.dto.ChatRequest;
+import com.baeldung.openapi.dto.ChatResponse;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.RestTemplate;
+
+@RestController
+public class ChatController {
+
+ @Qualifier("openaiRestTemplate")
+ @Autowired
+ private RestTemplate restTemplate;
+
+ @Value("${openai.model}")
+ private String model;
+
+ @Value("${openai.api.url}")
+ private String apiUrl;
+
+ /**
+ * Creates a chat request and sends it to the OpenAI API
+ * Returns the first message from the API response
+ *
+ * @param prompt the prompt to send to the API
+ * @return first message from the API response
+ */
+ @GetMapping("/chat")
+ public String chat(@RequestParam String prompt) {
+ ChatRequest request = new ChatRequest(model, prompt);
+
+ ChatResponse response = restTemplate.postForObject(
+ apiUrl,
+ request,
+ ChatResponse.class);
+
+ if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
+ return "No response";
+ }
+
+ return response.getChoices().get(0).getMessage().getContent();
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/dto/ChatRequest.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/dto/ChatRequest.java
new file mode 100644
index 000000000000..1e32b937ce55
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/dto/ChatRequest.java
@@ -0,0 +1,32 @@
+package com.baeldung.openapi.dto;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ChatRequest {
+ private String model;
+ private List messages;
+
+ public ChatRequest(String model, String prompt) {
+ this.model = model;
+
+ this.messages = new ArrayList<>();
+ this.messages.add(new Message("user", prompt));
+ }
+
+ public String getModel() {
+ return model;
+ }
+
+ public void setModel(String model) {
+ this.model = model;
+ }
+
+ public List getMessages() {
+ return messages;
+ }
+
+ public void setMessages(List messages) {
+ this.messages = messages;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/dto/ChatResponse.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/dto/ChatResponse.java
new file mode 100644
index 000000000000..937e2d87dbda
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/dto/ChatResponse.java
@@ -0,0 +1,38 @@
+package com.baeldung.openapi.dto;
+
+import java.util.List;
+
+public class ChatResponse {
+
+ private List choices;
+
+ public static class Choice {
+
+ private int index;
+ private Message message;
+
+ public int getIndex() {
+ return index;
+ }
+
+ public void setIndex(int index) {
+ this.index = index;
+ }
+
+ public Message getMessage() {
+ return message;
+ }
+
+ public void setMessage(Message message) {
+ this.message = message;
+ }
+ }
+
+ public List getChoices() {
+ return choices;
+ }
+
+ public void setChoices(List choices) {
+ this.choices = choices;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/dto/Message.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/dto/Message.java
new file mode 100644
index 000000000000..242cf4e89fc2
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/openapi/dto/Message.java
@@ -0,0 +1,31 @@
+package com.baeldung.openapi.dto;
+
+public class Message {
+
+ private String role;
+ private String content;
+
+ Message(String role, String content) {
+ this.role = role;
+ this.content = content;
+ }
+
+ Message() {
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+
+ public String getContent() {
+ return content;
+ }
+
+ public void setContent(String content) {
+ this.content = content;
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-libraries-2/src/main/resources/application.properties
index a18eda349ac8..47b2973fca66 100644
--- a/spring-boot-modules/spring-boot-libraries-2/src/main/resources/application.properties
+++ b/spring-boot-modules/spring-boot-libraries-2/src/main/resources/application.properties
@@ -47,4 +47,8 @@ resilience4j.ratelimiter.instances.rateLimiterApi.limit-refresh-period=60s
resilience4j.ratelimiter.instances.rateLimiterApi.timeout-duration=0s
resilience4j.ratelimiter.instances.rateLimiterApi.allow-health-indicator-to-fail=true
resilience4j.ratelimiter.instances.rateLimiterApi.subscribe-for-events=true
-resilience4j.ratelimiter.instances.rateLimiterApi.event-consumer-buffer-size=50
\ No newline at end of file
+resilience4j.ratelimiter.instances.rateLimiterApi.event-consumer-buffer-size=50
+
+openai.model=gpt-3.5-turbo
+openai.api.url=https://api.openai.com/v1/chat/completions
+openai.api.key=your-api-key
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-2/src/test/java/com/baeldung/modulith/ApplicationModularityUnitTest.java b/spring-boot-modules/spring-boot-libraries-2/src/test/java/com/baeldung/modulith/ApplicationModularityUnitTest.java
new file mode 100644
index 000000000000..40d644b1e04b
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-2/src/test/java/com/baeldung/modulith/ApplicationModularityUnitTest.java
@@ -0,0 +1,27 @@
+package com.baeldung.modulith;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.modulith.core.ApplicationModules;
+import org.springframework.modulith.docs.Documenter;
+
+class ApplicationModularityUnitTest {
+
+ ApplicationModules modules = ApplicationModules.of(Application.class);
+
+ @Test
+ void verifiesModularStructure() {
+ modules.verify();
+ }
+
+ @Test
+ void createModuleDocumentation() {
+ new Documenter(modules)
+ .writeDocumentation()
+ .writeIndividualModulesAsPlantUml();
+ }
+
+ @Test
+ void createApplicationModuleModel() {
+ modules.forEach(System.out::println);
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-logging-logback/pom.xml b/spring-boot-modules/spring-boot-logging-logback/pom.xml
index deb591c9f05d..68ef231ed92c 100644
--- a/spring-boot-modules/spring-boot-logging-logback/pom.xml
+++ b/spring-boot-modules/spring-boot-logging-logback/pom.xml
@@ -1,7 +1,7 @@
+ 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">
4.0.0
spring-boot-logging-logback
spring-boot-logging-logback
diff --git a/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/controller/AuthorsController.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/controller/AuthorsController.java
new file mode 100644
index 000000000000..019bd5ad9d48
--- /dev/null
+++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/controller/AuthorsController.java
@@ -0,0 +1,34 @@
+package com.baeldung.springboot.swagger.controller;
+
+import java.util.List;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.baeldung.springboot.swagger.model.Author;
+import com.baeldung.springboot.swagger.service.AuthorService;
+import com.baeldung.springboot.swagger.views.Views;
+import com.fasterxml.jackson.annotation.JsonView;
+
+@RestController
+@RequestMapping("/authors")
+public class AuthorsController {
+
+ @Autowired
+ AuthorService authorService;
+
+ @JsonView(Views.Public.class)
+ @GetMapping
+ public List getAllAuthors() {
+ return authorService.getAllAuthors();
+ }
+
+ @PostMapping
+ public void addAuthor(@RequestBody @JsonView(Views.Public.class) Author author){
+ authorService.addAuthors(author);
+ }
+}
diff --git a/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/model/Author.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/model/Author.java
new file mode 100644
index 000000000000..2e3099805921
--- /dev/null
+++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/model/Author.java
@@ -0,0 +1,28 @@
+package com.baeldung.springboot.swagger.model;
+
+import com.baeldung.springboot.swagger.views.Views;
+import com.fasterxml.jackson.annotation.JsonView;
+
+public class Author {
+
+ @JsonView(Views.Private.class)
+ private Integer id;
+
+ @JsonView(Views.Public.class)
+ private String name;
+
+ @JsonView(Views.Public.class)
+ private String email;
+
+ public Author() {
+ }
+
+ public Author(String name, String email) {
+ this.name = name;
+ this.email = email;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/service/AuthorService.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/service/AuthorService.java
new file mode 100644
index 000000000000..bf1f637889a3
--- /dev/null
+++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/service/AuthorService.java
@@ -0,0 +1,23 @@
+package com.baeldung.springboot.swagger.service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.springframework.stereotype.Service;
+
+import com.baeldung.springboot.swagger.model.Author;
+
+@Service
+public class AuthorService {
+ private List authors = new ArrayList<>();
+
+ public List getAllAuthors(){
+ return authors;
+ }
+
+ public void addAuthors(Author author){
+ author.setId(authors.size()+1);
+ authors.add(author);
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/views/Views.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/views/Views.java
new file mode 100644
index 000000000000..df638a564712
--- /dev/null
+++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/views/Views.java
@@ -0,0 +1,9 @@
+package com.baeldung.springboot.swagger.views;
+
+public class Views {
+ public static class Public {
+ }
+
+ public static class Private {
+ }
+}
diff --git a/spring-boot-modules/spring-boot-properties-2/pom.xml b/spring-boot-modules/spring-boot-properties-2/pom.xml
index 442cb24c7abb..4b1daca34d8e 100644
--- a/spring-boot-modules/spring-boot-properties-2/pom.xml
+++ b/spring-boot-modules/spring-boot-properties-2/pom.xml
@@ -10,9 +10,10 @@
Spring Boot Properties Module
- com.baeldung.spring-boot-modules
- spring-boot-modules
- 1.0.0-SNAPSHOT
+ com.baeldung
+ parent-boot-3
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-3
@@ -24,6 +25,15 @@
org.springframework.boot
spring-boot-starter-web
+
+ commons-lang
+ commons-lang
+ 2.6
+
+
+ com.baeldung.properties.yaml.YamlApplication
+
+
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/ValuesApp.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/ValuesApp.java
index 67547199a689..282ce4658e8e 100644
--- a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/ValuesApp.java
+++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/ValuesApp.java
@@ -7,11 +7,12 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
-import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import jakarta.annotation.PostConstruct;
+
@Configuration
@PropertySource(name = "myProperties", value = "values.properties")
public class ValuesApp {
diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/defaults/ValuesWithDefaultsApp.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/defaults/ValuesWithDefaultsApp.java
index 2a2b535be7a6..f1720d2fb3d4 100644
--- a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/defaults/ValuesWithDefaultsApp.java
+++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/defaults/ValuesWithDefaultsApp.java
@@ -1,6 +1,6 @@
package com.baeldung.properties.value.defaults;
-import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@@ -8,10 +8,11 @@
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.Assert;
-import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
+import jakarta.annotation.PostConstruct;
+
/**
* Demonstrates setting defaults for @Value annotation. Note that there are no properties
* defined in the specified property source. We also assume that the user here
@@ -60,10 +61,10 @@ public void afterInitialize() {
// arrays
List stringListValues = Arrays.asList("one", "two", "three");
- Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues), "unexpected value for stringArrayWithDefaults");
+ Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues), "unexpected value for stringArrayWithDefaults");
List intListValues = Arrays.asList(1, 2, 3);
- Assert.isTrue(Arrays.asList(ArrayUtils.toObject(intArrayWithDefaults)).containsAll(intListValues), "unexpected value for intArrayWithDefaults");
+ Assert.isTrue(Arrays.asList(ArrayUtils.toObject(intArrayWithDefaults)).containsAll(intListValues), "unexpected value for intArrayWithDefaults");
// SpEL
Assert.isTrue(spelWithDefaultValue.equals("my default system property value"), "unexpected value for spelWithDefaultValue");
diff --git a/spring-boot-modules/spring-boot-properties-3/README.md b/spring-boot-modules/spring-boot-properties-3/README.md
index 37b63abb844c..4bc4a2325f2f 100644
--- a/spring-boot-modules/spring-boot-properties-3/README.md
+++ b/spring-boot-modules/spring-boot-properties-3/README.md
@@ -11,4 +11,5 @@
- [IntelliJ – Cannot Resolve Spring Boot Configuration Properties Error](https://www.baeldung.com/intellij-resolve-spring-boot-configuration-properties)
- [Log Properties in a Spring Boot Application](https://www.baeldung.com/spring-boot-log-properties)
- [Using Environment Variables in Spring Boot’s application.properties](https://www.baeldung.com/spring-boot-properties-env-variables)
+- [Loading Multiple YAML Configuration Files in Spring Boot](https://www.baeldung.com/spring-boot-load-multiple-yaml-configuration-files)
- More articles: [[<-- prev]](../spring-boot-properties-2)
diff --git a/spring-boot-modules/spring-boot-properties-3/pom.xml b/spring-boot-modules/spring-boot-properties-3/pom.xml
index 3de85c7175e6..ed6e08add0bf 100644
--- a/spring-boot-modules/spring-boot-properties-3/pom.xml
+++ b/spring-boot-modules/spring-boot-properties-3/pom.xml
@@ -9,9 +9,10 @@
Spring Boot Properties Module
- com.baeldung.spring-boot-modules
- spring-boot-modules
- 1.0.0-SNAPSHOT
+ com.baeldung
+ parent-boot-3
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-3
@@ -31,7 +32,6 @@
org.springframework.boot
spring-boot-starter-web
- RELEASE
@@ -44,4 +44,8 @@
+
+ com.baeldung.boot.properties.DemoApplication
+
+
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/error/KebabCasingDemoApplication.java b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/error/KebabCasingDemoApplication.java
new file mode 100644
index 000000000000..772580c8162e
--- /dev/null
+++ b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/error/KebabCasingDemoApplication.java
@@ -0,0 +1,12 @@
+package com.baeldung.error;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class KebabCasingDemoApplication {
+ public static void main(String[] args) {
+ SpringApplication.run(KebabCasingDemoApplication.class, args);
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/error/configuration/MainConfiguration.java b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/error/configuration/MainConfiguration.java
new file mode 100644
index 000000000000..a61c64cfbe52
--- /dev/null
+++ b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/error/configuration/MainConfiguration.java
@@ -0,0 +1,18 @@
+package com.baeldung.error.configuration;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ConfigurationProperties(prefix = "customProperties")
+public class MainConfiguration {
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/log/EnvironmentPropertiesPrinter.java b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/log/EnvironmentPropertiesPrinter.java
index 321593b31bc8..26f6867296f4 100644
--- a/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/log/EnvironmentPropertiesPrinter.java
+++ b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/log/EnvironmentPropertiesPrinter.java
@@ -5,7 +5,7 @@
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
-import javax.annotation.PostConstruct;
+import jakarta.annotation.PostConstruct;
@Component
public class EnvironmentPropertiesPrinter {
diff --git a/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/multipleyaml/MultipleYamlApplication.java b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/multipleyaml/MultipleYamlApplication.java
new file mode 100644
index 000000000000..9dc754b24b2e
--- /dev/null
+++ b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/multipleyaml/MultipleYamlApplication.java
@@ -0,0 +1,27 @@
+package com.baeldung.properties.multipleyaml;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.CommandLineRunner;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class MultipleYamlApplication implements CommandLineRunner {
+
+ @Autowired
+ private MultipleYamlConfiguration config;
+
+ public static void main(String[] args) {
+ SpringApplication springApp = new SpringApplication(MultipleYamlApplication.class);
+
+ // Code from first example, uncomment to use multiple profiles
+ // springApp.setAdditionalProfiles("students", "teachers");
+
+ springApp.run(args);
+ }
+
+ public void run(String... args) throws Exception {
+ System.out.println("Students: " + config.getStudents());
+ System.out.println("Teachers: " + config.getTeachers());
+ }
+}
diff --git a/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/multipleyaml/MultipleYamlConfiguration.java b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/multipleyaml/MultipleYamlConfiguration.java
new file mode 100644
index 000000000000..c46a321e2411
--- /dev/null
+++ b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/multipleyaml/MultipleYamlConfiguration.java
@@ -0,0 +1,35 @@
+package com.baeldung.properties.multipleyaml;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+
+import java.util.List;
+
+@Configuration
+@ConfigurationProperties
+@PropertySources({
+ @PropertySource(value = "classpath:application-teachers.yml", factory = MultipleYamlPropertySourceFactory.class),
+ @PropertySource(value = "classpath:application-students.yml", factory = MultipleYamlPropertySourceFactory.class)})
+public class MultipleYamlConfiguration {
+
+ List teachers;
+ List students;
+
+ public void setTeachers(List teachers) {
+ this.teachers = teachers;
+ }
+
+ public void setStudents(List students) {
+ this.students = students;
+ }
+
+ public List getTeachers() {
+ return teachers;
+ }
+
+ public List getStudents() {
+ return students;
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/multipleyaml/MultipleYamlPropertySourceFactory.java b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/multipleyaml/MultipleYamlPropertySourceFactory.java
new file mode 100644
index 000000000000..c09bd3c8b9fd
--- /dev/null
+++ b/spring-boot-modules/spring-boot-properties-3/src/main/java/com/baeldung/properties/multipleyaml/MultipleYamlPropertySourceFactory.java
@@ -0,0 +1,23 @@
+package com.baeldung.properties.multipleyaml;
+
+import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
+import org.springframework.core.env.PropertiesPropertySource;
+import org.springframework.core.env.PropertySource;
+import org.springframework.core.io.support.EncodedResource;
+import org.springframework.core.io.support.PropertySourceFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+
+public class MultipleYamlPropertySourceFactory implements PropertySourceFactory {
+
+ @Override
+ public PropertySource> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
+ YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
+ factory.setResources(encodedResource.getResource());
+
+ Properties properties = factory.getObject();
+
+ return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
+ }
+}
diff --git a/spring-boot-modules/spring-boot-properties-3/src/main/resources/application-students.yml b/spring-boot-modules/spring-boot-properties-3/src/main/resources/application-students.yml
new file mode 100644
index 000000000000..f4aaf8ae4dc4
--- /dev/null
+++ b/spring-boot-modules/spring-boot-properties-3/src/main/resources/application-students.yml
@@ -0,0 +1,3 @@
+students:
+ - Jane
+ - Michael
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-properties-3/src/main/resources/application-teachers.yml b/spring-boot-modules/spring-boot-properties-3/src/main/resources/application-teachers.yml
new file mode 100644
index 000000000000..f0d208016443
--- /dev/null
+++ b/spring-boot-modules/spring-boot-properties-3/src/main/resources/application-teachers.yml
@@ -0,0 +1,3 @@
+teachers:
+ - Margo
+ - Javier
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-properties-3/src/main/resources/application.properties b/spring-boot-modules/spring-boot-properties-3/src/main/resources/application.properties
index 541183a18641..225ebb05b61e 100644
--- a/spring-boot-modules/spring-boot-properties-3/src/main/resources/application.properties
+++ b/spring-boot-modules/spring-boot-properties-3/src/main/resources/application.properties
@@ -31,4 +31,13 @@ bael.property=prodValue
environment.name=${OS}
java.home.and.environment=${JAVA_HOME}+${OS}
not.existing.system.property=${thispropertydoesnotexist}
-baeldung.presentation=${HELLO_BAELDUNG}. Java is installed in the folder: ${JAVA_HOME}
\ No newline at end of file
+baeldung.presentation=${HELLO_BAELDUNG}. Java is installed in the folder: ${JAVA_HOME}
+#---
+#camelCasing
+#customProperties.name="Baeldung"
+#PascalCasing
+#CustomProperties.name="Baeldung"
+#SnakingCasing
+#custom_properties.name="Baeldung"
+#KebabCasing
+custom-properties.name="Baeldung"
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-properties-3/src/main/resources/application.yml b/spring-boot-modules/spring-boot-properties-3/src/main/resources/application.yml
index 2e28da5ad385..2c44065028bd 100644
--- a/spring-boot-modules/spring-boot-properties-3/src/main/resources/application.yml
+++ b/spring-boot-modules/spring-boot-properties-3/src/main/resources/application.yml
@@ -2,6 +2,10 @@ bael:
root-level-property: defaultRootLevelValue
spring:
profiles:
+# Multiple profiles for MultipleYamlApplication first example
+# include:
+# - teachers
+# - students
group:
multidocument-integration: multidocument-integration-extension
---
diff --git a/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml b/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml
index 95dc06b155c3..21ed0f59f4f1 100644
--- a/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml
+++ b/spring-boot-modules/spring-boot-properties-migrator-demo/pom.xml
@@ -7,10 +7,10 @@
1.0-SNAPSHOT
- com.baeldung.spring-boot-modules
- spring-boot-modules
- 1.0.0-SNAPSHOT
- ../pom.xml
+ com.baeldung
+ parent-boot-3
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-3
@@ -49,8 +49,8 @@
- 8
- 8
+ 17
+ 17
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-properties/pom.xml b/spring-boot-modules/spring-boot-properties/pom.xml
index 378864a1dfcd..bf5f514725ee 100644
--- a/spring-boot-modules/spring-boot-properties/pom.xml
+++ b/spring-boot-modules/spring-boot-properties/pom.xml
@@ -10,9 +10,10 @@
Spring Boot Properties Module
- com.baeldung.spring-boot-modules
- spring-boot-modules
- 1.0.0-SNAPSHOT
+ com.baeldung
+ parent-boot-3
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-3
@@ -74,6 +75,25 @@
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+ build-info
+
+ build-info
+
+
+
+ ${java.version}
+ ${project.description}
+ 123
+
+
+
+
+
org.apache.maven.plugins
maven-resources-plugin
@@ -122,7 +142,7 @@
- 2021.0.3
+ 2022.0.1
1.10
@
diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ConfigProperties.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ConfigProperties.java
index 47df7848851f..faf567839814 100644
--- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ConfigProperties.java
+++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ConfigProperties.java
@@ -3,10 +3,10 @@
import java.util.List;
import java.util.Map;
-import javax.validation.constraints.Max;
-import javax.validation.constraints.Min;
-import javax.validation.constraints.NotBlank;
-import javax.validation.constraints.Pattern;
+import jakarta.validation.constraints.Max;
+import jakarta.validation.constraints.Min;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.springframework.boot.context.properties.ConfigurationProperties;
diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ImmutableCredentials.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ImmutableCredentials.java
index a58e4143e50f..72c45afbb24f 100644
--- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ImmutableCredentials.java
+++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ImmutableCredentials.java
@@ -1,10 +1,8 @@
package com.baeldung.configurationproperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
-import org.springframework.boot.context.properties.ConstructorBinding;
@ConfigurationProperties(prefix = "mail.credentials")
-@ConstructorBinding
public class ImmutableCredentials {
private final String authMethod;
diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java
index 2cb27e184448..9ed27f412ca1 100644
--- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java
+++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/buildproperties/BuildInfoServiceIntegrationTest.java
@@ -4,12 +4,9 @@
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
-import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.test.context.junit4.SpringRunner;
-@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
class BuildInfoServiceIntegrationTest {
diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/buildproperties/BuildPropertiesUnitTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/buildproperties/BuildPropertiesUnitTest.java
new file mode 100644
index 000000000000..bb8ec78cc15b
--- /dev/null
+++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/buildproperties/BuildPropertiesUnitTest.java
@@ -0,0 +1,30 @@
+package com.baeldung.buildproperties;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.info.BuildProperties;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+@SpringBootTest
+@ExtendWith(SpringExtension.class)
+public class BuildPropertiesUnitTest {
+ @Autowired
+ private BuildProperties buildProperties;
+
+ @Test
+ void givenBuildPropertiesBean_WhenFetchDefaultBuildProperties_ThenGetValidValues() {
+ Assertions.assertEquals("spring-boot-properties", buildProperties.getArtifact());
+ Assertions.assertEquals("com.baeldung", buildProperties.getGroup());
+ Assertions.assertEquals("0.0.1-SNAPSHOT", buildProperties.getVersion());
+ }
+
+ @Test
+ void givenBuildPropertiesBean_WhenFetchCustomBuildProprties_ThenGetValidValues() {
+ Assertions.assertEquals("123", buildProperties.get("custom.value"));
+ Assertions.assertNotNull(buildProperties.get("java.version"));
+ Assertions.assertEquals("Spring Boot Properties Module", buildProperties.get("description"));
+ }
+}
diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadManualTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadManualTest.java
index 88e22af4ba73..ecb547a0a060 100644
--- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadManualTest.java
+++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadManualTest.java
@@ -1,28 +1,27 @@
package com.baeldung.properties.reloading;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
import com.baeldung.properties.reloading.beans.ConfigurationPropertiesRefreshConfigBean;
import com.baeldung.properties.reloading.beans.EnvironmentConfigBean;
import com.baeldung.properties.reloading.beans.PropertiesConfigBean;
import com.baeldung.properties.reloading.beans.ValueRefreshConfigBean;
import java.io.FileOutputStream;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
-@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringBootPropertiesTestApplication.class)
public class PropertiesReloadManualTest {
@@ -50,7 +49,7 @@ public class PropertiesReloadManualTest {
ValueRefreshConfigBean singletonValueRefreshConfigBean;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
mvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
@@ -61,7 +60,7 @@ public void setUp() throws Exception {
callRefresh();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
createConfig("extra.properties", "application.theme.color", "blue");
createConfig("extra2.properties", "application.theme.background", "red");
@@ -69,76 +68,76 @@ public void tearDown() throws Exception {
@Test
public void givenEnvironmentReader_whenColorChanged_thenExpectChangeValue() throws Exception {
- Assert.assertEquals("blue", environmentConfigBean.getColor());
+ assertEquals("blue", environmentConfigBean.getColor());
createConfig("extra.properties", "application.theme.color", "red");
Thread.sleep(refreshDelay);
- Assert.assertEquals("red", environmentConfigBean.getColor());
+ assertEquals("red", environmentConfigBean.getColor());
}
@Test
public void givenEnvironmentReader_whenBackgroundChanged_thenExpectChangeValue() throws Exception {
- Assert.assertEquals("red", environmentConfigBean.getBackgroundColor());
+ assertEquals("red", environmentConfigBean.getBackgroundColor());
createConfig("extra2.properties", "application.theme.background", "blue");
Thread.sleep(refreshDelay);
- Assert.assertEquals("blue", environmentConfigBean.getBackgroundColor());
+ assertEquals("blue", environmentConfigBean.getBackgroundColor());
}
@Test
public void givenPropertiesReader_whenColorChanged_thenExpectChangeValue() throws Exception {
- Assert.assertEquals("blue", propertiesConfigBean.getColor());
+ assertEquals("blue", propertiesConfigBean.getColor());
createConfig("extra.properties", "application.theme.color", "red");
Thread.sleep(refreshDelay);
- Assert.assertEquals("red", propertiesConfigBean.getColor());
+ assertEquals("red", propertiesConfigBean.getColor());
}
@Test
public void givenRefreshScopedValueReader_whenColorChangedAndRefreshCalled_thenExpectChangeValue() throws Exception {
- Assert.assertEquals("blue", valueRefreshConfigBean.getColor());
+ assertEquals("blue", valueRefreshConfigBean.getColor());
createConfig("extra.properties", "application.theme.color", "red");
Thread.sleep(refreshDelay);
- Assert.assertEquals("blue", valueRefreshConfigBean.getColor());
+ assertEquals("blue", valueRefreshConfigBean.getColor());
callRefresh();
- Assert.assertEquals("red", valueRefreshConfigBean.getColor());
+ assertEquals("red", valueRefreshConfigBean.getColor());
}
@Test
public void givenSingletonRefreshScopedValueReader_whenColorChangedAndRefreshCalled_thenExpectOldValue() throws Exception {
- Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor());
+ assertEquals("blue", singletonValueRefreshConfigBean.getColor());
createConfig("extra.properties", "application.theme.color", "red");
Thread.sleep(refreshDelay);
- Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor());
+ assertEquals("blue", singletonValueRefreshConfigBean.getColor());
callRefresh();
- Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor());
+ assertEquals("blue", singletonValueRefreshConfigBean.getColor());
}
@Test
public void givenRefreshScopedConfigurationPropertiesReader_whenColorChangedAndRefreshCalled_thenExpectChangeValue() throws Exception {
- Assert.assertEquals("blue", configurationPropertiesRefreshConfigBean.getColor());
+ assertEquals("blue", configurationPropertiesRefreshConfigBean.getColor());
createConfig("extra.properties", "application.theme.color", "red");
Thread.sleep(refreshDelay);
- Assert.assertEquals("blue", configurationPropertiesRefreshConfigBean.getColor());
+ assertEquals("blue", configurationPropertiesRefreshConfigBean.getColor());
callRefresh();
- Assert.assertEquals("red", configurationPropertiesRefreshConfigBean.getColor());
+ assertEquals("red", configurationPropertiesRefreshConfigBean.getColor());
}
public void callRefresh() throws Exception {
@@ -148,7 +147,7 @@ public void callRefresh() throws Exception {
.accept(MediaType.APPLICATION_JSON_VALUE))
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
- Assert.assertEquals(response.getStatus(), 200);
+ assertEquals(200, response.getStatus());
}
public void createConfig(String file, String key, String value) throws Exception {
diff --git a/spring-boot-modules/spring-boot-redis/pom.xml b/spring-boot-modules/spring-boot-redis/pom.xml
index 42aa1321d5f0..4467e38dbe68 100644
--- a/spring-boot-modules/spring-boot-redis/pom.xml
+++ b/spring-boot-modules/spring-boot-redis/pom.xml
@@ -1,21 +1,20 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
- org.springframework.boot
- spring-boot-starter-parent
- 3.0.2
-
-
com.baelding
spring-boot-redis
0.0.1-SNAPSHOT
spring-boot-redis
Demo project for Spring Boot with Spring Data Redis
-
- 15
-
+
+
+ com.baeldung
+ parent-boot-3
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-3
+
+
org.springframework.boot
@@ -38,6 +37,12 @@
it.ozimov
embedded-redis
+
+
+ org.slf4j
+ slf4j-simple
+
+
0.7.3
test
@@ -66,4 +71,8 @@
+
+ 15
+
+
diff --git a/spring-boot-modules/spring-boot-resilience4j/README.md b/spring-boot-modules/spring-boot-resilience4j/README.md
new file mode 100644
index 000000000000..e6c73674ceee
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/README.md
@@ -0,0 +1,3 @@
+### Relevant Articles:
+
+- [Resilience4j Events Endpoints](https://www.baeldung.com/resilience4j-events-endpoints)
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-resilience4j/pom.xml b/spring-boot-modules/spring-boot-resilience4j/pom.xml
new file mode 100644
index 000000000000..609bc7fc4955
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/pom.xml
@@ -0,0 +1,53 @@
+
+
+ 4.0.0
+ com.example
+ spring-boot-resilience4j
+ 0.0.1-SNAPSHOT
+ spring-boot-resilience4j
+
+
+ com.baeldung.spring-boot-modules
+ spring-boot-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-aop
+
+
+ org.springframework.boot
+ spring-boot-starter-actuator
+
+
+ io.github.resilience4j
+ resilience4j-spring-boot2
+ 2.0.2
+
+
+ com.fasterxml.jackson.datatype
+ jackson-datatype-jsr310
+ 2.14.2
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ com.github.tomakehurst
+ wiremock-jre8
+ 2.35.0
+ test
+
+
+
+
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ApiExceptionHandler.java b/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ApiExceptionHandler.java
new file mode 100644
index 000000000000..4e14d5c532e4
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ApiExceptionHandler.java
@@ -0,0 +1,29 @@
+package com.baeldung.resilience4j.eventendpoints;
+
+import io.github.resilience4j.bulkhead.BulkheadFullException;
+import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
+import io.github.resilience4j.ratelimiter.RequestNotPermitted;
+import java.util.concurrent.TimeoutException;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseStatus;
+
+@ControllerAdvice
+public class ApiExceptionHandler {
+ @ExceptionHandler({CallNotPermittedException.class})
+ @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
+ public void handleCallNotPermittedException() {}
+
+ @ExceptionHandler({TimeoutException.class})
+ @ResponseStatus(HttpStatus.REQUEST_TIMEOUT)
+ public void handleTimeoutException() {}
+
+ @ExceptionHandler({BulkheadFullException.class})
+ @ResponseStatus(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED)
+ public void handleBulkheadFullException() {}
+
+ @ExceptionHandler({RequestNotPermitted.class})
+ @ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
+ public void handleRequestNotPermitted() {}
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ExternalAPICaller.java b/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ExternalAPICaller.java
new file mode 100644
index 000000000000..a860e7e3ccb0
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ExternalAPICaller.java
@@ -0,0 +1,28 @@
+package com.baeldung.resilience4j.eventendpoints;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.RestTemplate;
+
+@Component
+public class ExternalAPICaller {
+ private final RestTemplate restTemplate;
+
+ @Autowired
+ public ExternalAPICaller(RestTemplate restTemplate) {
+ this.restTemplate = restTemplate;
+ }
+
+ public String callApi() {
+ return restTemplate.getForObject("/api/external", String.class);
+ }
+
+ public String callApiWithDelay() {
+ String result = restTemplate.getForObject("/api/external", String.class);
+ try {
+ Thread.sleep(5000);
+ } catch (InterruptedException ignore) {
+ }
+ return result;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ExternalApiCallerConfig.java b/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ExternalApiCallerConfig.java
new file mode 100644
index 000000000000..7145e588776b
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ExternalApiCallerConfig.java
@@ -0,0 +1,14 @@
+package com.baeldung.resilience4j.eventendpoints;
+
+import org.springframework.boot.web.client.RestTemplateBuilder;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.client.RestTemplate;
+
+@Configuration
+public class ExternalApiCallerConfig {
+ @Bean
+ public RestTemplate restTemplate() {
+ return new RestTemplateBuilder().rootUri("http://localhost:9090").build();
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ResilientApp.java b/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ResilientApp.java
new file mode 100644
index 000000000000..35b999a9de44
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ResilientApp.java
@@ -0,0 +1,12 @@
+package com.baeldung.resilience4j.eventendpoints;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication()
+public class ResilientApp {
+
+ public static void main(String[] args) {
+ SpringApplication.run(ResilientApp.class, args);
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ResilientAppController.java b/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ResilientAppController.java
new file mode 100644
index 000000000000..ccd0108c2ffc
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/main/java/com/baeldung/resilience4j/eventendpoints/ResilientAppController.java
@@ -0,0 +1,58 @@
+package com.baeldung.resilience4j.eventendpoints;
+
+import io.github.resilience4j.bulkhead.annotation.Bulkhead;
+import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
+import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
+import io.github.resilience4j.retry.annotation.Retry;
+import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
+import java.util.concurrent.CompletableFuture;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/api/")
+public class ResilientAppController {
+
+ private final ExternalAPICaller externalAPICaller;
+
+ @Autowired
+ public ResilientAppController(ExternalAPICaller externalApi) {
+ this.externalAPICaller = externalApi;
+ }
+
+ @GetMapping("/circuit-breaker")
+ @CircuitBreaker(name = "externalService")
+ public String circuitBreakerApi() {
+ return externalAPICaller.callApi();
+ }
+
+ @GetMapping("/retry")
+ @Retry(name = "externalService", fallbackMethod = "fallbackAfterRetry")
+ public String retryApi() {
+ return externalAPICaller.callApi();
+ }
+
+ @GetMapping("/bulkhead")
+ @Bulkhead(name = "externalService")
+ public String bulkheadApi() {
+ return externalAPICaller.callApi();
+ }
+
+ @GetMapping("/rate-limiter")
+ @RateLimiter(name = "externalService")
+ public String rateLimitApi() {
+ return externalAPICaller.callApi();
+ }
+
+ @GetMapping("/time-limiter")
+ @TimeLimiter(name = "externalService")
+ public CompletableFuture timeLimiterApi() {
+ return CompletableFuture.supplyAsync(externalAPICaller::callApiWithDelay);
+ }
+
+ public String fallbackAfterRetry(Exception ex) {
+ return "all retries have exhausted";
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/main/resources/application.yml b/spring-boot-modules/spring-boot-resilience4j/src/main/resources/application.yml
new file mode 100644
index 000000000000..81904f56d98e
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/main/resources/application.yml
@@ -0,0 +1,60 @@
+management:
+ endpoints:
+ web:
+ exposure:
+ include: '*'
+
+resilience4j.circuitbreaker:
+ configs:
+ default:
+ registerHealthIndicator: true
+ slidingWindowSize: 10
+ minimumNumberOfCalls: 5
+ permittedNumberOfCallsInHalfOpenState: 3
+ automaticTransitionFromOpenToHalfOpenEnabled: true
+ waitDurationInOpenState: 5s
+ failureRateThreshold: 50
+ eventConsumerBufferSize: 50
+ instances:
+ externalService:
+ baseConfig: default
+
+resilience4j.retry:
+ configs:
+ default:
+ maxAttempts: 3
+ waitDuration: 100
+ instances:
+ externalService:
+ baseConfig: default
+
+resilience4j.timelimiter:
+ configs:
+ default:
+ cancelRunningFuture: true
+ timeoutDuration: 2s
+ instances:
+ externalService:
+ baseConfig: default
+
+resilience4j.bulkhead:
+ configs:
+ default:
+ max-concurrent-calls: 3
+ max-wait-duration: 1
+ instances:
+ externalService:
+ baseConfig: default
+
+resilience4j.ratelimiter:
+ configs:
+ default:
+ limit-for-period: 5
+ limit-refresh-period: 60s
+ timeout-duration: 0s
+ allow-health-indicator-to-fail: true
+ subscribe-for-events: true
+ event-consumer-buffer-size: 50
+ instances:
+ externalService:
+ baseConfig: default
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/ResilientAppControllerIntegrationTest.java b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/ResilientAppControllerIntegrationTest.java
new file mode 100644
index 000000000000..d1951218de20
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/ResilientAppControllerIntegrationTest.java
@@ -0,0 +1,319 @@
+package com.baeldung.resilience4j.eventendpoints;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.*;
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.springframework.http.HttpStatus.*;
+
+import com.baeldung.resilience4j.eventendpoints.model.*;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.datatype.jsr310.JSR310Module;
+import com.github.tomakehurst.wiremock.client.WireMock;
+import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
+import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
+import java.net.URI;
+import java.nio.charset.Charset;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.*;
+import java.util.stream.IntStream;
+import org.apache.commons.io.IOUtils;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.boot.test.web.server.LocalServerPort;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class ResilientAppControllerIntegrationTest {
+
+ private final Logger LOGGER = LoggerFactory.getLogger(getClass());
+
+ @Autowired private TestRestTemplate restTemplate;
+
+ @LocalServerPort private Integer port;
+
+ private static final ObjectMapper objectMapper =
+ new ObjectMapper().registerModule(new JSR310Module());
+
+ @RegisterExtension
+ static WireMockExtension EXTERNAL_SERVICE =
+ WireMockExtension.newInstance()
+ .options(WireMockConfiguration.wireMockConfig().port(9090))
+ .build();
+
+ @Test
+ void testCircuitBreakerEvents() throws Exception {
+ EXTERNAL_SERVICE.stubFor(WireMock.get("/api/external").willReturn(serverError()));
+
+ IntStream.rangeClosed(1, 5)
+ .forEach(
+ i -> {
+ ResponseEntity response =
+ restTemplate.getForEntity("/api/circuit-breaker", String.class);
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
+ });
+
+ // Fetch the events generated by the above calls
+ List circuitBreakerEvents = getCircuitBreakerEvents();
+ assertThat(circuitBreakerEvents.size()).isEqualTo(7);
+
+ // The first 5 events are the error events corresponding to the above server error responses
+ IntStream.rangeClosed(0, 4)
+ .forEach(
+ i -> {
+ assertThat(circuitBreakerEvents.get(i).getCircuitBreakerName())
+ .isEqualTo("externalService");
+ assertThat(circuitBreakerEvents.get(i).getType()).isEqualTo("ERROR");
+ assertThat(circuitBreakerEvents.get(i).getCreationTime()).isNotNull();
+ assertThat(circuitBreakerEvents.get(i).getErrorMessage()).isNotNull();
+ assertThat(circuitBreakerEvents.get(i).getDurationInMs()).isNotNull();
+ assertThat(circuitBreakerEvents.get(i).getStateTransition()).isNull();
+ });
+
+ // Following event signals the configured failure rate exceeded
+ CircuitBreakerEvent failureRateExceededEvent = circuitBreakerEvents.get(5);
+ assertThat(failureRateExceededEvent.getCircuitBreakerName()).isEqualTo("externalService");
+ assertThat(failureRateExceededEvent.getType()).isEqualTo("FAILURE_RATE_EXCEEDED");
+ assertThat(failureRateExceededEvent.getCreationTime()).isNotNull();
+ assertThat(failureRateExceededEvent.getErrorMessage()).isNull();
+ assertThat(failureRateExceededEvent.getDurationInMs()).isNull();
+ assertThat(failureRateExceededEvent.getStateTransition()).isNull();
+
+ // Following event signals the state transition from CLOSED TO OPEN
+ CircuitBreakerEvent stateTransitionEvent = circuitBreakerEvents.get(6);
+ assertThat(stateTransitionEvent.getCircuitBreakerName()).isEqualTo("externalService");
+ assertThat(stateTransitionEvent.getType()).isEqualTo("STATE_TRANSITION");
+ assertThat(stateTransitionEvent.getCreationTime()).isNotNull();
+ assertThat(stateTransitionEvent.getErrorMessage()).isNull();
+ assertThat(stateTransitionEvent.getDurationInMs()).isNull();
+ assertThat(stateTransitionEvent.getStateTransition()).isEqualTo("CLOSED_TO_OPEN");
+
+ IntStream.rangeClosed(1, 5)
+ .forEach(
+ i -> {
+ ResponseEntity response =
+ restTemplate.getForEntity("/api/circuit-breaker", String.class);
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
+ });
+
+ /// Fetch the events generated by the above calls
+ List updatedCircuitBreakerEvents = getCircuitBreakerEvents();
+ assertThat(updatedCircuitBreakerEvents.size()).isEqualTo(12);
+
+ // Newly added events will be of type NOT_PERMITTED since the Circuit Breaker is in OPEN state
+ IntStream.rangeClosed(7, 11)
+ .forEach(
+ i -> {
+ assertThat(updatedCircuitBreakerEvents.get(i).getCircuitBreakerName())
+ .isEqualTo("externalService");
+ assertThat(updatedCircuitBreakerEvents.get(i).getType()).isEqualTo("NOT_PERMITTED");
+ assertThat(updatedCircuitBreakerEvents.get(i).getCreationTime()).isNotNull();
+ assertThat(updatedCircuitBreakerEvents.get(i).getErrorMessage()).isNull();
+ assertThat(updatedCircuitBreakerEvents.get(i).getDurationInMs()).isNull();
+ assertThat(updatedCircuitBreakerEvents.get(i).getStateTransition()).isNull();
+ });
+
+ EXTERNAL_SERVICE.verify(5, getRequestedFor(urlEqualTo("/api/external")));
+ }
+
+ private List getCircuitBreakerEvents() throws Exception {
+ String jsonEventsList =
+ IOUtils.toString(
+ new URI("http://localhost:" + port + "/actuator/circuitbreakerevents"),
+ Charset.forName("UTF-8"));
+ CircuitBreakerEvents circuitBreakerEvents =
+ objectMapper.readValue(jsonEventsList, CircuitBreakerEvents.class);
+ return circuitBreakerEvents.getCircuitBreakerEvents();
+ }
+
+ @Test
+ void testRetryEvents() throws Exception {
+ EXTERNAL_SERVICE.stubFor(WireMock.get("/api/external").willReturn(ok()));
+ ResponseEntity response1 = restTemplate.getForEntity("/api/retry", String.class);
+ EXTERNAL_SERVICE.verify(1, getRequestedFor(urlEqualTo("/api/external")));
+
+ EXTERNAL_SERVICE.resetRequests();
+
+ EXTERNAL_SERVICE.stubFor(WireMock.get("/api/external").willReturn(serverError()));
+ ResponseEntity response2 = restTemplate.getForEntity("/api/retry", String.class);
+ assertThat(response2.getBody()).isEqualTo("all retries have exhausted");
+ EXTERNAL_SERVICE.verify(3, getRequestedFor(urlEqualTo("/api/external")));
+
+ List retryEvents = getRetryEvents();
+ assertThat(retryEvents.size()).isEqualTo(3);
+
+ // First 2 events should be retry events
+ IntStream.rangeClosed(0, 1)
+ .forEach(
+ i -> {
+ assertThat(retryEvents.get(i).getRetryName()).isEqualTo("externalService");
+ assertThat(retryEvents.get(i).getType()).isEqualTo("RETRY");
+ assertThat(retryEvents.get(i).getCreationTime()).isNotNull();
+ assertThat(retryEvents.get(i).getErrorMessage()).isNotNull();
+ assertThat(retryEvents.get(i).getNumberOfAttempts()).isEqualTo(i + 1);
+ });
+
+ // Last event should be an error event because the configured num of retries is reached
+ RetryEvent errorRetryEvent = retryEvents.get(2);
+ assertThat(errorRetryEvent.getRetryName()).isEqualTo("externalService");
+ assertThat(errorRetryEvent.getType()).isEqualTo("ERROR");
+ assertThat(errorRetryEvent.getCreationTime()).isNotNull();
+ assertThat(errorRetryEvent.getErrorMessage()).isNotNull();
+ assertThat(errorRetryEvent.getNumberOfAttempts()).isEqualTo(3);
+ }
+
+ private List getRetryEvents() throws Exception {
+ String jsonEventsList =
+ IOUtils.toString(
+ new URI("http://localhost:" + port + "/actuator/retryevents"),
+ Charset.forName("UTF-8"));
+ RetryEvents retryEvents = objectMapper.readValue(jsonEventsList, RetryEvents.class);
+ return retryEvents.getRetryEvents();
+ }
+
+ @Test
+ void testTimeLimiterEvents() throws Exception {
+ EXTERNAL_SERVICE.stubFor(WireMock.get("/api/external").willReturn(ok()));
+ ResponseEntity response = restTemplate.getForEntity("/api/time-limiter", String.class);
+
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.REQUEST_TIMEOUT);
+ EXTERNAL_SERVICE.verify(1, getRequestedFor(urlEqualTo("/api/external")));
+
+ List timeLimiterEvents = getTimeLimiterEvents();
+ assertThat(timeLimiterEvents.size()).isEqualTo(1);
+ TimeLimiterEvent timeoutEvent = timeLimiterEvents.get(0);
+ assertThat(timeoutEvent.getTimeLimiterName()).isEqualTo("externalService");
+ assertThat(timeoutEvent.getType()).isEqualTo("TIMEOUT");
+ assertThat(timeoutEvent.getCreationTime()).isNotNull();
+ }
+
+ private List getTimeLimiterEvents() throws Exception {
+ String jsonEventsList =
+ IOUtils.toString(
+ new URI("http://localhost:" + port + "/actuator/timelimiterevents"),
+ Charset.forName("UTF-8"));
+ TimeLimiterEvents timeLimiterEvents =
+ objectMapper.readValue(jsonEventsList, TimeLimiterEvents.class);
+ return timeLimiterEvents.getTimeLimiterEvents();
+ }
+
+ @Test
+ void testBulkheadEvents() throws Exception {
+ EXTERNAL_SERVICE.stubFor(WireMock.get("/api/external").willReturn(ok()));
+ Map responseStatusCount = new ConcurrentHashMap<>();
+ ExecutorService executorService = Executors.newFixedThreadPool(5);
+ CountDownLatch latch = new CountDownLatch(5);
+
+ IntStream.rangeClosed(1, 5)
+ .forEach(
+ i ->
+ executorService.execute(
+ () -> {
+ ResponseEntity response =
+ restTemplate.getForEntity("/api/bulkhead", String.class);
+ int statusCode = response.getStatusCodeValue();
+ responseStatusCount.merge(statusCode, 1, Integer::sum);
+ latch.countDown();
+ }));
+ latch.await();
+ executorService.shutdown();
+
+ assertEquals(2, responseStatusCount.keySet().size());
+ LOGGER.info("Response statuses: " + responseStatusCount.keySet());
+ assertTrue(responseStatusCount.containsKey(BANDWIDTH_LIMIT_EXCEEDED.value()));
+ assertTrue(responseStatusCount.containsKey(OK.value()));
+ EXTERNAL_SERVICE.verify(3, getRequestedFor(urlEqualTo("/api/external")));
+
+ List bulkheadEvents = getBulkheadEvents();
+
+ // Based on the configuration, the first 3 calls should be permitted, so we should see the
+ // CALL_PERMITTED events
+ IntStream.rangeClosed(0, 2)
+ .forEach(
+ i -> {
+ assertThat(bulkheadEvents.get(i).getBulkheadName()).isEqualTo("externalService");
+ assertThat(bulkheadEvents.get(i).getType()).isEqualTo("CALL_PERMITTED");
+ assertThat(bulkheadEvents.get(i).getCreationTime()).isNotNull();
+ });
+
+ // For the other 2 calls made we should see the CALL_REJECTED events
+ IntStream.rangeClosed(3, 4)
+ .forEach(
+ i -> {
+ assertThat(bulkheadEvents.get(i).getBulkheadName()).isEqualTo("externalService");
+ assertThat(bulkheadEvents.get(i).getType()).isEqualTo("CALL_REJECTED");
+ assertThat(bulkheadEvents.get(i).getCreationTime()).isNotNull();
+ });
+ }
+
+ private List getBulkheadEvents() throws Exception {
+ String jsonEventsList =
+ IOUtils.toString(
+ new URI("http://localhost:" + port + "/actuator/bulkheadevents"),
+ Charset.forName("UTF-8"));
+ BulkheadEvents bulkheadEvents = objectMapper.readValue(jsonEventsList, BulkheadEvents.class);
+ return bulkheadEvents.getBulkheadEvents();
+ }
+
+ @Test
+ void testRateLimiterEvents() throws Exception {
+ EXTERNAL_SERVICE.stubFor(WireMock.get("/api/external").willReturn(ok()));
+ Map responseStatusCount = new ConcurrentHashMap<>();
+
+ IntStream.rangeClosed(1, 50)
+ .forEach(
+ i -> {
+ ResponseEntity response =
+ restTemplate.getForEntity("/api/rate-limiter", String.class);
+ int statusCode = response.getStatusCodeValue();
+ responseStatusCount.put(
+ statusCode, responseStatusCount.getOrDefault(statusCode, 0) + 1);
+ });
+
+ assertEquals(2, responseStatusCount.keySet().size());
+ assertTrue(responseStatusCount.containsKey(TOO_MANY_REQUESTS.value()));
+ assertTrue(responseStatusCount.containsKey(OK.value()));
+ EXTERNAL_SERVICE.verify(5, getRequestedFor(urlEqualTo("/api/external")));
+
+ List rateLimiterEvents = getRateLimiterEvents();
+ assertThat(rateLimiterEvents.size()).isEqualTo(50);
+
+ // First allowed calls in the rate limit is 5, so we should see for those SUCCESSFUL_ACQUIRE
+ // events
+ IntStream.rangeClosed(0, 4)
+ .forEach(
+ i -> {
+ assertThat(rateLimiterEvents.get(i).getRateLimiterName())
+ .isEqualTo("externalService");
+ assertThat(rateLimiterEvents.get(i).getType()).isEqualTo("SUCCESSFUL_ACQUIRE");
+ assertThat(rateLimiterEvents.get(i).getCreationTime()).isNotNull();
+ });
+
+ // the rest should be FAILED_ACQUIRE events since the rate limiter kicks in
+ IntStream.rangeClosed(5, rateLimiterEvents.size() - 1)
+ .forEach(
+ i -> {
+ assertThat(rateLimiterEvents.get(i).getRateLimiterName())
+ .isEqualTo("externalService");
+ assertThat(rateLimiterEvents.get(i).getType()).isEqualTo("FAILED_ACQUIRE");
+ assertThat(rateLimiterEvents.get(i).getCreationTime()).isNotNull();
+ });
+ }
+
+ private List getRateLimiterEvents() throws Exception {
+ String jsonEventsList =
+ IOUtils.toString(
+ new URI("http://localhost:" + port + "/actuator/ratelimiterevents"),
+ Charset.forName("UTF-8"));
+ RateLimiterEvents rateLimiterEvents =
+ objectMapper.readValue(jsonEventsList, RateLimiterEvents.class);
+ return rateLimiterEvents.getRateLimiterEvents();
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/BulkheadEvent.java b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/BulkheadEvent.java
new file mode 100644
index 000000000000..6d25006bbb67
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/BulkheadEvent.java
@@ -0,0 +1,50 @@
+package com.baeldung.resilience4j.eventendpoints.model;
+
+import java.time.ZonedDateTime;
+import java.util.Objects;
+
+public class BulkheadEvent {
+
+ private String bulkheadName;
+ private String type;
+ private ZonedDateTime creationTime;
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ BulkheadEvent that = (BulkheadEvent) o;
+ return Objects.equals(bulkheadName, that.bulkheadName)
+ && Objects.equals(type, that.type)
+ && Objects.equals(creationTime, that.creationTime);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(bulkheadName, type, creationTime);
+ }
+
+ public String getBulkheadName() {
+ return bulkheadName;
+ }
+
+ public void setBulkheadName(String bulkheadName) {
+ this.bulkheadName = bulkheadName;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public ZonedDateTime getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(ZonedDateTime creationTime) {
+ this.creationTime = creationTime;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/BulkheadEvents.java b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/BulkheadEvents.java
new file mode 100644
index 000000000000..7d8b6b2a5f23
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/BulkheadEvents.java
@@ -0,0 +1,16 @@
+package com.baeldung.resilience4j.eventendpoints.model;
+
+import java.util.List;
+
+public class BulkheadEvents {
+
+ private List bulkheadEvents;
+
+ public List getBulkheadEvents() {
+ return bulkheadEvents;
+ }
+
+ public void setBulkheadEvents(List bulkheadEvents) {
+ this.bulkheadEvents = bulkheadEvents;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/CircuitBreakerEvent.java b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/CircuitBreakerEvent.java
new file mode 100644
index 000000000000..0a07c9b4955a
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/CircuitBreakerEvent.java
@@ -0,0 +1,81 @@
+package com.baeldung.resilience4j.eventendpoints.model;
+
+import java.time.ZonedDateTime;
+import java.util.Objects;
+
+public class CircuitBreakerEvent {
+
+ private String circuitBreakerName;
+ private String type;
+ private ZonedDateTime creationTime;
+ private String errorMessage;
+ private Integer durationInMs;
+ private String stateTransition;
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ CircuitBreakerEvent that = (CircuitBreakerEvent) o;
+ return Objects.equals(circuitBreakerName, that.circuitBreakerName)
+ && Objects.equals(type, that.type)
+ && Objects.equals(creationTime, that.creationTime)
+ && Objects.equals(errorMessage, that.errorMessage)
+ && Objects.equals(durationInMs, that.durationInMs)
+ && Objects.equals(stateTransition, that.stateTransition);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(
+ circuitBreakerName, type, creationTime, errorMessage, durationInMs, stateTransition);
+ }
+
+ public String getCircuitBreakerName() {
+ return circuitBreakerName;
+ }
+
+ public void setCircuitBreakerName(String circuitBreakerName) {
+ this.circuitBreakerName = circuitBreakerName;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public ZonedDateTime getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(ZonedDateTime creationTime) {
+ this.creationTime = creationTime;
+ }
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public Integer getDurationInMs() {
+ return durationInMs;
+ }
+
+ public void setDurationInMs(Integer durationInMs) {
+ this.durationInMs = durationInMs;
+ }
+
+ public String getStateTransition() {
+ return stateTransition;
+ }
+
+ public void setStateTransition(String stateTransition) {
+ this.stateTransition = stateTransition;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/CircuitBreakerEvents.java b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/CircuitBreakerEvents.java
new file mode 100644
index 000000000000..c3ec741d051e
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/CircuitBreakerEvents.java
@@ -0,0 +1,16 @@
+package com.baeldung.resilience4j.eventendpoints.model;
+
+import java.util.List;
+
+public class CircuitBreakerEvents {
+
+ private List circuitBreakerEvents;
+
+ public List getCircuitBreakerEvents() {
+ return circuitBreakerEvents;
+ }
+
+ public void setCircuitBreakerEvents(List circuitBreakerEvents) {
+ this.circuitBreakerEvents = circuitBreakerEvents;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/RateLimiterEvent.java b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/RateLimiterEvent.java
new file mode 100644
index 000000000000..ccc0f5a9b37b
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/RateLimiterEvent.java
@@ -0,0 +1,50 @@
+package com.baeldung.resilience4j.eventendpoints.model;
+
+import java.time.ZonedDateTime;
+import java.util.Objects;
+
+public class RateLimiterEvent {
+
+ private String rateLimiterName;
+ private String type;
+ private ZonedDateTime creationTime;
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ RateLimiterEvent that = (RateLimiterEvent) o;
+ return Objects.equals(rateLimiterName, that.rateLimiterName)
+ && Objects.equals(type, that.type)
+ && Objects.equals(creationTime, that.creationTime);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(rateLimiterName, type, creationTime);
+ }
+
+ public String getRateLimiterName() {
+ return rateLimiterName;
+ }
+
+ public void setRateLimiterName(String rateLimiterName) {
+ this.rateLimiterName = rateLimiterName;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public ZonedDateTime getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(ZonedDateTime creationTime) {
+ this.creationTime = creationTime;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/RateLimiterEvents.java b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/RateLimiterEvents.java
new file mode 100644
index 000000000000..c0cfcdf0d728
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/RateLimiterEvents.java
@@ -0,0 +1,16 @@
+package com.baeldung.resilience4j.eventendpoints.model;
+
+import java.util.List;
+
+public class RateLimiterEvents {
+
+ private List rateLimiterEvents;
+
+ public List getRateLimiterEvents() {
+ return rateLimiterEvents;
+ }
+
+ public void setRateLimiterEvents(List rateLimiterEvents) {
+ this.rateLimiterEvents = rateLimiterEvents;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/RetryEvent.java b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/RetryEvent.java
new file mode 100644
index 000000000000..a17d45c679ae
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/RetryEvent.java
@@ -0,0 +1,70 @@
+package com.baeldung.resilience4j.eventendpoints.model;
+
+import java.time.ZonedDateTime;
+import java.util.Objects;
+
+public class RetryEvent {
+
+ private String retryName;
+ private String type;
+ private ZonedDateTime creationTime;
+ private String errorMessage;
+ private Integer numberOfAttempts;
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ RetryEvent that = (RetryEvent) o;
+ return Objects.equals(retryName, that.retryName)
+ && Objects.equals(type, that.type)
+ && Objects.equals(creationTime, that.creationTime)
+ && Objects.equals(errorMessage, that.errorMessage)
+ && Objects.equals(numberOfAttempts, that.numberOfAttempts);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(retryName, type, creationTime, errorMessage, numberOfAttempts);
+ }
+
+ public String getRetryName() {
+ return retryName;
+ }
+
+ public void setRetryName(String retryName) {
+ this.retryName = retryName;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public ZonedDateTime getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(ZonedDateTime creationTime) {
+ this.creationTime = creationTime;
+ }
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public Integer getNumberOfAttempts() {
+ return numberOfAttempts;
+ }
+
+ public void setNumberOfAttempts(Integer numberOfAttempts) {
+ this.numberOfAttempts = numberOfAttempts;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/RetryEvents.java b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/RetryEvents.java
new file mode 100644
index 000000000000..e5bb73ff0cef
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/RetryEvents.java
@@ -0,0 +1,16 @@
+package com.baeldung.resilience4j.eventendpoints.model;
+
+import java.util.List;
+
+public class RetryEvents {
+
+ private List retryEvents;
+
+ public List getRetryEvents() {
+ return retryEvents;
+ }
+
+ public void setRetryEvents(List retryEvents) {
+ this.retryEvents = retryEvents;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/TimeLimiterEvent.java b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/TimeLimiterEvent.java
new file mode 100644
index 000000000000..07f891c40104
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/TimeLimiterEvent.java
@@ -0,0 +1,50 @@
+package com.baeldung.resilience4j.eventendpoints.model;
+
+import java.time.ZonedDateTime;
+import java.util.Objects;
+
+public class TimeLimiterEvent {
+
+ private String timeLimiterName;
+ private String type;
+ private ZonedDateTime creationTime;
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ TimeLimiterEvent that = (TimeLimiterEvent) o;
+ return Objects.equals(timeLimiterName, that.timeLimiterName)
+ && Objects.equals(type, that.type)
+ && Objects.equals(creationTime, that.creationTime);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(timeLimiterName, type, creationTime);
+ }
+
+ public String getTimeLimiterName() {
+ return timeLimiterName;
+ }
+
+ public void setTimeLimiterName(String timeLimiterName) {
+ this.timeLimiterName = timeLimiterName;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public ZonedDateTime getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(ZonedDateTime creationTime) {
+ this.creationTime = creationTime;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/TimeLimiterEvents.java b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/TimeLimiterEvents.java
new file mode 100644
index 000000000000..739ff91916bd
--- /dev/null
+++ b/spring-boot-modules/spring-boot-resilience4j/src/test/java/com/baeldung/resilience4j/eventendpoints/model/TimeLimiterEvents.java
@@ -0,0 +1,16 @@
+package com.baeldung.resilience4j.eventendpoints.model;
+
+import java.util.List;
+
+public class TimeLimiterEvents {
+
+ private List timeLimiterEvents;
+
+ public List getTimeLimiterEvents() {
+ return timeLimiterEvents;
+ }
+
+ public void setTimeLimiterEvents(List timeLimiterEvents) {
+ this.timeLimiterEvents = timeLimiterEvents;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-springdoc/pom.xml b/spring-boot-modules/spring-boot-springdoc/pom.xml
index 8cd94179cf2d..e21efc35d268 100644
--- a/spring-boot-modules/spring-boot-springdoc/pom.xml
+++ b/spring-boot-modules/spring-boot-springdoc/pom.xml
@@ -146,7 +146,7 @@
org.springdoc
springdoc-openapi-maven-plugin
- 1.4
+ ${springdoc-openapi-maven-plugin.version}
integration-test
@@ -167,9 +167,10 @@
- 1.6.8
+ 1.7.0
1.5.6
${project.build.directory}/generated-snippets
+ 1.4
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml b/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml
index de2c8c68c46c..3b1a4ca988b4 100644
--- a/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml
+++ b/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml
@@ -10,20 +10,14 @@
Module For Spring Boot Swagger UI with Keycloak
- com.baeldung.spring-boot-modules
- spring-boot-modules
- 1.0.0-SNAPSHOT
+ com.baeldung
+ parent-boot-3
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-3
-
- org.keycloak.bom
- keycloak-adapter-bom
- ${keycloak.version}
- pom
- import
-
org.apache.logging.log4j
log4j-bom
@@ -40,20 +34,24 @@
spring-boot-starter-web
- io.springfox
- springfox-boot-starter
- ${springfox.version}
-
-
-
- org.keycloak
- keycloak-spring-boot-starter
+ org.springframework.boot
+ spring-boot-starter-oauth2-resource-server
org.springframework.boot
spring-boot-starter-security
+
+ org.springdoc
+ springdoc-openapi-starter-webmvc-ui
+ ${springdoc.version}
+
+
+ javax.annotation
+ javax.annotation-api
+ ${javax.version}
+
@@ -66,10 +64,9 @@
- 2.4.5
- 3.0.0
- 15.0.2
+ 2.1.0
2.17.1
+ 1.3.2
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/GlobalSecurityConfig.java b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/GlobalSecurityConfig.java
index 985cbf7d063f..5c24368ce6a4 100644
--- a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/GlobalSecurityConfig.java
+++ b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/GlobalSecurityConfig.java
@@ -1,59 +1,40 @@
package com.baeldung.swaggerkeycloak;
-import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
-import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
-import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
-import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
-import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
-import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.core.session.SessionRegistryImpl;
+import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
-@KeycloakConfiguration
+@Configuration
+@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
-public class GlobalSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
+public class GlobalSecurityConfig {
- @Override
+ @Bean
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
- // otherwise, we'll get an error 'permitAll only works with HttpSecurity.authorizeRequests()'
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- super.configure(http);
- http
- .csrf().disable()
- .authorizeRequests()
- // we can set up authorization here alternatively to @Secured methods
- .antMatchers(HttpMethod.OPTIONS).permitAll()
- .antMatchers("/api/**").authenticated()
- // force authentication for all requests (and use global method security)
- .anyRequest().permitAll();
+ @Bean
+ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
+ http.csrf()
+ .disable()
+ .authorizeRequests()
+ .requestMatchers(HttpMethod.OPTIONS)
+ .permitAll()
+ .requestMatchers("/api/**")
+ .authenticated()
+ .anyRequest()
+ .permitAll();
+ http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
+ return http.build();
}
- /*
- * re-configure Spring Security to use
- * registers the KeycloakAuthenticationProvider with the authentication manager
- */
- @Autowired
- void configureGlobal(AuthenticationManagerBuilder auth) {
- KeycloakAuthenticationProvider provider = keycloakAuthenticationProvider();
- provider.setGrantedAuthoritiesMapper(authoritiesMapper());
- auth.authenticationProvider(provider);
- }
-
- GrantedAuthoritiesMapper authoritiesMapper() {
- SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
- mapper.setPrefix("ROLE_"); // Spring Security adds a prefix to the authority/role names (we use the default here)
- mapper.setConvertToUpperCase(true); // convert names to uppercase
- mapper.setDefaultAuthority("ROLE_ANONYMOUS"); // set a default authority
- return mapper;
- }
-
-}
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/KeycloakConfigResolverConfig.java b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/KeycloakConfigResolverConfig.java
deleted file mode 100644
index bca764a17d5b..000000000000
--- a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/KeycloakConfigResolverConfig.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.baeldung.swaggerkeycloak;
-
-import org.keycloak.adapters.KeycloakConfigResolver;
-import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-@Configuration
-public class KeycloakConfigResolverConfig {
-
- /*
- * re-configure keycloak adapter for Spring Boot environment,
- * i.e. to read config from application.yml
- * (otherwise, we need a keycloak.json file)
- */
- @Bean
- public KeycloakConfigResolver configResolver() {
- return new KeycloakSpringBootConfigResolver();
- }
-
-
-
-}
diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/OpenAPISecurityConfig.java b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/OpenAPISecurityConfig.java
index d3ab26e1eecc..8d75a1a88544 100644
--- a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/OpenAPISecurityConfig.java
+++ b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/OpenAPISecurityConfig.java
@@ -1,22 +1,17 @@
package com.baeldung.swaggerkeycloak;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import org.springframework.http.HttpMethod;
-import springfox.documentation.builders.OAuth2SchemeBuilder;
-import springfox.documentation.service.AuthorizationScope;
-import springfox.documentation.service.SecurityReference;
-import springfox.documentation.service.SecurityScheme;
-import springfox.documentation.spi.service.contexts.SecurityContext;
-import springfox.documentation.spring.web.plugins.Docket;
-import springfox.documentation.swagger.web.SecurityConfiguration;
-import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
+import io.swagger.v3.oas.models.Components;
+import io.swagger.v3.oas.models.OpenAPI;
+import io.swagger.v3.oas.models.info.Info;
+import io.swagger.v3.oas.models.security.OAuthFlow;
+import io.swagger.v3.oas.models.security.OAuthFlows;
+import io.swagger.v3.oas.models.security.Scopes;
+import io.swagger.v3.oas.models.security.SecurityRequirement;
+import io.swagger.v3.oas.models.security.SecurityScheme;
@Configuration
public class OpenAPISecurityConfig {
@@ -25,59 +20,35 @@ public class OpenAPISecurityConfig {
String authServerUrl;
@Value("${keycloak.realm}")
String realm;
- @Value("${keycloak.resource}")
- private String clientId;
- @Value("${keycloak.credentials.secret}")
- private String clientSecret;
- @Autowired
- void addSecurity(Docket docket) {
- docket
- .securitySchemes(Collections.singletonList(authenticationScheme()))
- .securityContexts(Collections.singletonList(securityContext()));
- }
-
- private SecurityScheme authenticationScheme() {
- return new OAuth2SchemeBuilder("implicit")
- .name("my_oAuth_security_schema")
- .authorizationUrl(authServerUrl + "/realms/" + realm)
- .scopes(authorizationScopes())
- .build();
- }
+ private static final String OAUTH_SCHEME_NAME = "my_oAuth_security_schema";
- private List authorizationScopes() {
- return Arrays.asList(
- new AuthorizationScope("read_access", "read data"),
- new AuthorizationScope("write_access", "modify data")
- );
+ @Bean
+ public OpenAPI openAPI() {
+ return new OpenAPI().components(new Components()
+ .addSecuritySchemes(OAUTH_SCHEME_NAME, createOAuthScheme()))
+ .addSecurityItem(new SecurityRequirement().addList(OAUTH_SCHEME_NAME))
+ .info(new Info().title("Todos Management Service")
+ .description("A service providing todos.")
+ .version("1.0"));
}
- private SecurityContext securityContext() {
- return SecurityContext.
- builder().
- securityReferences(readAccessAuth())
- .operationSelector(operationContext -> HttpMethod.GET.equals(operationContext.httpMethod()))
- .build();
+ private SecurityScheme createOAuthScheme() {
+ OAuthFlows flows = createOAuthFlows();
+ return new SecurityScheme().type(SecurityScheme.Type.OAUTH2)
+ .flows(flows);
}
- private List readAccessAuth() {
- AuthorizationScope[] authorizationScopes = new AuthorizationScope[] { authorizationScopes().get(0) };
- return Collections.singletonList(
- new SecurityReference("my_oAuth_security_schema", authorizationScopes)
- );
+ private OAuthFlows createOAuthFlows() {
+ OAuthFlow flow = createAuthorizationCodeFlow();
+ return new OAuthFlows().implicit(flow);
}
- @Bean
- public SecurityConfiguration security() {
- return SecurityConfigurationBuilder.builder()
- .clientId(clientId)
- .clientSecret(clientSecret)
- .realm(realm)
- .appName(clientId)
- .scopeSeparator(",")
- .additionalQueryStringParams(null)
- .useBasicAuthenticationWithAccessCodeGrant(false)
- .build();
+ private OAuthFlow createAuthorizationCodeFlow() {
+ return new OAuthFlow()
+ .authorizationUrl(authServerUrl + "/realms/" + realm + "/protocol/openid-connect/auth")
+ .scopes(new Scopes().addString("read_access", "read data")
+ .addString("write_access", "modify data"));
}
}
diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/SwaggerUIConfig.java b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/SwaggerUIConfig.java
deleted file mode 100644
index 1207fe5b9e49..000000000000
--- a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/SwaggerUIConfig.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package com.baeldung.swaggerkeycloak;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import springfox.documentation.builders.ApiInfoBuilder;
-import springfox.documentation.builders.PathSelectors;
-import springfox.documentation.oas.annotations.EnableOpenApi;
-import springfox.documentation.service.ApiInfo;
-import springfox.documentation.spi.DocumentationType;
-import springfox.documentation.spring.web.plugins.Docket;
-
-import static springfox.documentation.builders.RequestHandlerSelectors.basePackage;
-
-@EnableOpenApi
-@Configuration
-class SwaggerUIConfig {
-
- @Bean
- Docket api() {
- return new Docket(DocumentationType.OAS_30)
- .useDefaultResponseMessages(false)
- .select()
- .apis(basePackage(TodosApplication.class.getPackage().getName()))
- .paths(PathSelectors.any())
- .build()
- .apiInfo(apiInfo());
- }
-
- private ApiInfo apiInfo() {
- return new ApiInfoBuilder().title("Todos Management Service")
- .description("A service providing todos.")
- .version("1.0")
- .build();
- }
-
-}
diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/TodosController.java b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/TodosController.java
index 6b70072ce3f8..6d48a0c67df8 100644
--- a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/TodosController.java
+++ b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/TodosController.java
@@ -1,14 +1,15 @@
package com.baeldung.swaggerkeycloak;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.responses.ApiResponse;
+import io.swagger.v3.oas.annotations.responses.ApiResponses;
+
import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.util.Collection;
@@ -28,13 +29,10 @@ public void initData() {
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
- @ApiOperation("Read all todos")
- @ApiResponses({
- @ApiResponse(code = 200, message = "The todos were found and returned.")
- })
+ @Operation(description = "Read all todos")
+ @ApiResponses({ @ApiResponse(responseCode = "200", description = "The todos were found and returned.") })
@PreAuthorize("hasAuthority('SCOPE_read_access')")
public Collection readAll() {
return todos.values();
}
-
}
diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/META-INF/resources/webjars/springfox-swagger-ui/favicon-16x16.png b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/META-INF/resources/webjars/springfox-swagger-ui/favicon-16x16.png
deleted file mode 100644
index 8b194e617af1..000000000000
Binary files a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/META-INF/resources/webjars/springfox-swagger-ui/favicon-16x16.png and /dev/null differ
diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/META-INF/resources/webjars/springfox-swagger-ui/favicon-32x32.png b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/META-INF/resources/webjars/springfox-swagger-ui/favicon-32x32.png
deleted file mode 100644
index 249737fe4455..000000000000
Binary files a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/META-INF/resources/webjars/springfox-swagger-ui/favicon-32x32.png and /dev/null differ
diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/META-INF/resources/webjars/springfox-swagger-ui/oauth2-redirect.html b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/META-INF/resources/webjars/springfox-swagger-ui/oauth2-redirect.html
deleted file mode 100644
index 64b171f7de50..000000000000
--- a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/META-INF/resources/webjars/springfox-swagger-ui/oauth2-redirect.html
+++ /dev/null
@@ -1,75 +0,0 @@
-
-
-
- Swagger UI: OAuth2 Redirect
-
-
-
-
-
diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/META-INF/resources/webjars/springfox-swagger-ui/swagger-ui-bundle.js b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/META-INF/resources/webjars/springfox-swagger-ui/swagger-ui-bundle.js
deleted file mode 100644
index c6fa628eae15..000000000000
--- a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/META-INF/resources/webjars/springfox-swagger-ui/swagger-ui-bundle.js
+++ /dev/null
@@ -1,3 +0,0 @@
-/*! For license information please see swagger-ui-bundle.js.LICENSE.txt */
-!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SwaggerUIBundle=t():e.SwaggerUIBundle=t()}(this,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="/dist",n(n.s=481)}([function(e,t,n){"use strict";e.exports=n(555)},function(e,t,n){e.exports=function(){"use strict";var e=Array.prototype.slice;function t(e,t){t&&(e.prototype=Object.create(t.prototype)),e.prototype.constructor=e}function n(e){return i(e)?e:J(e)}function r(e){return u(e)?e:K(e)}function o(e){return s(e)?e:Y(e)}function a(e){return i(e)&&!c(e)?e:G(e)}function i(e){return!(!e||!e[f])}function u(e){return!(!e||!e[p])}function s(e){return!(!e||!e[h])}function c(e){return u(e)||s(e)}function l(e){return!(!e||!e[d])}t(r,n),t(o,n),t(a,n),n.isIterable=i,n.isKeyed=u,n.isIndexed=s,n.isAssociative=c,n.isOrdered=l,n.Keyed=r,n.Indexed=o,n.Set=a;var f="@@__IMMUTABLE_ITERABLE__@@",p="@@__IMMUTABLE_KEYED__@@",h="@@__IMMUTABLE_INDEXED__@@",d="@@__IMMUTABLE_ORDERED__@@",m="delete",v=5,g=1<>>0;if(""+n!==t||4294967295===n)return NaN;t=n}return t<0?A(e)+t:t}function C(){return!0}function j(e,t,n){return(0===e||void 0!==n&&e<=-n)&&(void 0===t||void 0!==n&&t>=n)}function T(e,t){return N(e,t,0)}function I(e,t){return N(e,t,t)}function N(e,t,n){return void 0===e?n:e<0?Math.max(0,t+e):void 0===t?e:Math.min(t,e)}var P=0,M=1,R=2,D="function"==typeof Symbol&&Symbol.iterator,L="@@iterator",B=D||L;function F(e){this.next=e}function z(e,t,n,r){var o=0===e?t:1===e?n:[t,n];return r?r.value=o:r={value:o,done:!1},r}function q(){return{value:void 0,done:!0}}function U(e){return!!H(e)}function V(e){return e&&"function"==typeof e.next}function W(e){var t=H(e);return t&&t.call(e)}function H(e){var t=e&&(D&&e[D]||e[L]);if("function"==typeof t)return t}function $(e){return e&&"number"==typeof e.length}function J(e){return null==e?ie():i(e)?e.toSeq():ce(e)}function K(e){return null==e?ie().toKeyedSeq():i(e)?u(e)?e.toSeq():e.fromEntrySeq():ue(e)}function Y(e){return null==e?ie():i(e)?u(e)?e.entrySeq():e.toIndexedSeq():se(e)}function G(e){return(null==e?ie():i(e)?u(e)?e.entrySeq():e:se(e)).toSetSeq()}F.prototype.toString=function(){return"[Iterator]"},F.KEYS=P,F.VALUES=M,F.ENTRIES=R,F.prototype.inspect=F.prototype.toSource=function(){return this.toString()},F.prototype[B]=function(){return this},t(J,n),J.of=function(){return J(arguments)},J.prototype.toSeq=function(){return this},J.prototype.toString=function(){return this.__toString("Seq {","}")},J.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},J.prototype.__iterate=function(e,t){return fe(this,e,t,!0)},J.prototype.__iterator=function(e,t){return pe(this,e,t,!0)},t(K,J),K.prototype.toKeyedSeq=function(){return this},t(Y,J),Y.of=function(){return Y(arguments)},Y.prototype.toIndexedSeq=function(){return this},Y.prototype.toString=function(){return this.__toString("Seq [","]")},Y.prototype.__iterate=function(e,t){return fe(this,e,t,!1)},Y.prototype.__iterator=function(e,t){return pe(this,e,t,!1)},t(G,J),G.of=function(){return G(arguments)},G.prototype.toSetSeq=function(){return this},J.isSeq=ae,J.Keyed=K,J.Set=G,J.Indexed=Y;var Q,Z,X,ee="@@__IMMUTABLE_SEQ__@@";function te(e){this._array=e,this.size=e.length}function ne(e){var t=Object.keys(e);this._object=e,this._keys=t,this.size=t.length}function re(e){this._iterable=e,this.size=e.length||e.size}function oe(e){this._iterator=e,this._iteratorCache=[]}function ae(e){return!(!e||!e[ee])}function ie(){return Q||(Q=new te([]))}function ue(e){var t=Array.isArray(e)?new te(e).fromEntrySeq():V(e)?new oe(e).fromEntrySeq():U(e)?new re(e).fromEntrySeq():"object"==typeof e?new ne(e):void 0;if(!t)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+e);return t}function se(e){var t=le(e);if(!t)throw new TypeError("Expected Array or iterable object of values: "+e);return t}function ce(e){var t=le(e)||"object"==typeof e&&new ne(e);if(!t)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+e);return t}function le(e){return $(e)?new te(e):V(e)?new oe(e):U(e)?new re(e):void 0}function fe(e,t,n,r){var o=e._cache;if(o){for(var a=o.length-1,i=0;i<=a;i++){var u=o[n?a-i:i];if(!1===t(u[1],r?u[0]:i,e))return i+1}return i}return e.__iterateUncached(t,n)}function pe(e,t,n,r){var o=e._cache;if(o){var a=o.length-1,i=0;return new F((function(){var e=o[n?a-i:i];return i++>a?q():z(t,r?e[0]:i-1,e[1])}))}return e.__iteratorUncached(t,n)}function he(e,t){return t?de(t,e,"",{"":e}):me(e)}function de(e,t,n,r){return Array.isArray(t)?e.call(r,n,Y(t).map((function(n,r){return de(e,n,r,t)}))):ve(t)?e.call(r,n,K(t).map((function(n,r){return de(e,n,r,t)}))):t}function me(e){return Array.isArray(e)?Y(e).map(me).toList():ve(e)?K(e).map(me).toMap():e}function ve(e){return e&&(e.constructor===Object||void 0===e.constructor)}function ge(e,t){if(e===t||e!=e&&t!=t)return!0;if(!e||!t)return!1;if("function"==typeof e.valueOf&&"function"==typeof t.valueOf){if((e=e.valueOf())===(t=t.valueOf())||e!=e&&t!=t)return!0;if(!e||!t)return!1}return!("function"!=typeof e.equals||"function"!=typeof t.equals||!e.equals(t))}function ye(e,t){if(e===t)return!0;if(!i(t)||void 0!==e.size&&void 0!==t.size&&e.size!==t.size||void 0!==e.__hash&&void 0!==t.__hash&&e.__hash!==t.__hash||u(e)!==u(t)||s(e)!==s(t)||l(e)!==l(t))return!1;if(0===e.size&&0===t.size)return!0;var n=!c(e);if(l(e)){var r=e.entries();return t.every((function(e,t){var o=r.next().value;return o&&ge(o[1],e)&&(n||ge(o[0],t))}))&&r.next().done}var o=!1;if(void 0===e.size)if(void 0===t.size)"function"==typeof e.cacheResult&&e.cacheResult();else{o=!0;var a=e;e=t,t=a}var f=!0,p=t.__iterate((function(t,r){if(n?!e.has(t):o?!ge(t,e.get(r,b)):!ge(e.get(r,b),t))return f=!1,!1}));return f&&e.size===p}function be(e,t){if(!(this instanceof be))return new be(e,t);if(this._value=e,this.size=void 0===t?1/0:Math.max(0,t),0===this.size){if(Z)return Z;Z=this}}function we(e,t){if(!e)throw new Error(t)}function xe(e,t,n){if(!(this instanceof xe))return new xe(e,t,n);if(we(0!==n,"Cannot step a Range by 0"),e=e||0,void 0===t&&(t=1/0),n=void 0===n?1:Math.abs(n),tr?q():z(e,o,n[t?r-o++:o++])}))},t(ne,K),ne.prototype.get=function(e,t){return void 0===t||this.has(e)?this._object[e]:t},ne.prototype.has=function(e){return this._object.hasOwnProperty(e)},ne.prototype.__iterate=function(e,t){for(var n=this._object,r=this._keys,o=r.length-1,a=0;a<=o;a++){var i=r[t?o-a:a];if(!1===e(n[i],i,this))return a+1}return a},ne.prototype.__iterator=function(e,t){var n=this._object,r=this._keys,o=r.length-1,a=0;return new F((function(){var i=r[t?o-a:a];return a++>o?q():z(e,i,n[i])}))},ne.prototype[d]=!0,t(re,Y),re.prototype.__iterateUncached=function(e,t){if(t)return this.cacheResult().__iterate(e,t);var n=W(this._iterable),r=0;if(V(n))for(var o;!(o=n.next()).done&&!1!==e(o.value,r++,this););return r},re.prototype.__iteratorUncached=function(e,t){if(t)return this.cacheResult().__iterator(e,t);var n=W(this._iterable);if(!V(n))return new F(q);var r=0;return new F((function(){var t=n.next();return t.done?t:z(e,r++,t.value)}))},t(oe,Y),oe.prototype.__iterateUncached=function(e,t){if(t)return this.cacheResult().__iterate(e,t);for(var n,r=this._iterator,o=this._iteratorCache,a=0;a=r.length){var t=n.next();if(t.done)return t;r[o]=t.value}return z(e,o,r[o++])}))},t(be,Y),be.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},be.prototype.get=function(e,t){return this.has(e)?this._value:t},be.prototype.includes=function(e){return ge(this._value,e)},be.prototype.slice=function(e,t){var n=this.size;return j(e,t,n)?this:new be(this._value,I(t,n)-T(e,n))},be.prototype.reverse=function(){return this},be.prototype.indexOf=function(e){return ge(this._value,e)?0:-1},be.prototype.lastIndexOf=function(e){return ge(this._value,e)?this.size:-1},be.prototype.__iterate=function(e,t){for(var n=0;n=0&&t=0&&nn?q():z(e,a++,i)}))},xe.prototype.equals=function(e){return e instanceof xe?this._start===e._start&&this._end===e._end&&this._step===e._step:ye(this,e)},t(_e,n),t(Ee,_e),t(Se,_e),t(ke,_e),_e.Keyed=Ee,_e.Indexed=Se,_e.Set=ke;var Ae="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function(e,t){var n=65535&(e|=0),r=65535&(t|=0);return n*r+((e>>>16)*r+n*(t>>>16)<<16>>>0)|0};function Oe(e){return e>>>1&1073741824|3221225471&e}function Ce(e){if(!1===e||null==e)return 0;if("function"==typeof e.valueOf&&(!1===(e=e.valueOf())||null==e))return 0;if(!0===e)return 1;var t=typeof e;if("number"===t){if(e!=e||e===1/0)return 0;var n=0|e;for(n!==e&&(n^=4294967295*e);e>4294967295;)n^=e/=4294967295;return Oe(n)}if("string"===t)return e.length>Fe?je(e):Te(e);if("function"==typeof e.hashCode)return e.hashCode();if("object"===t)return Ie(e);if("function"==typeof e.toString)return Te(e.toString());throw new Error("Value type "+t+" cannot be hashed.")}function je(e){var t=Ue[e];return void 0===t&&(t=Te(e),qe===ze&&(qe=0,Ue={}),qe++,Ue[e]=t),t}function Te(e){for(var t=0,n=0;n0)switch(e.nodeType){case 1:return e.uniqueID;case 9:return e.documentElement&&e.documentElement.uniqueID}}var Re,De="function"==typeof WeakMap;De&&(Re=new WeakMap);var Le=0,Be="__immutablehash__";"function"==typeof Symbol&&(Be=Symbol(Be));var Fe=16,ze=255,qe=0,Ue={};function Ve(e){we(e!==1/0,"Cannot perform this action with an infinite size.")}function We(e){return null==e?ot():He(e)&&!l(e)?e:ot().withMutations((function(t){var n=r(e);Ve(n.size),n.forEach((function(e,n){return t.set(n,e)}))}))}function He(e){return!(!e||!e[Je])}t(We,Ee),We.of=function(){var t=e.call(arguments,0);return ot().withMutations((function(e){for(var n=0;n=t.length)throw new Error("Missing value for key: "+t[n]);e.set(t[n],t[n+1])}}))},We.prototype.toString=function(){return this.__toString("Map {","}")},We.prototype.get=function(e,t){return this._root?this._root.get(0,void 0,e,t):t},We.prototype.set=function(e,t){return at(this,e,t)},We.prototype.setIn=function(e,t){return this.updateIn(e,b,(function(){return t}))},We.prototype.remove=function(e){return at(this,e,b)},We.prototype.deleteIn=function(e){return this.updateIn(e,(function(){return b}))},We.prototype.update=function(e,t,n){return 1===arguments.length?e(this):this.updateIn([e],t,n)},We.prototype.updateIn=function(e,t,n){n||(n=t,t=void 0);var r=vt(this,_n(e),t,n);return r===b?void 0:r},We.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):ot()},We.prototype.merge=function(){return pt(this,void 0,arguments)},We.prototype.mergeWith=function(t){return pt(this,t,e.call(arguments,1))},We.prototype.mergeIn=function(t){var n=e.call(arguments,1);return this.updateIn(t,ot(),(function(e){return"function"==typeof e.merge?e.merge.apply(e,n):n[n.length-1]}))},We.prototype.mergeDeep=function(){return pt(this,ht,arguments)},We.prototype.mergeDeepWith=function(t){var n=e.call(arguments,1);return pt(this,dt(t),n)},We.prototype.mergeDeepIn=function(t){var n=e.call(arguments,1);return this.updateIn(t,ot(),(function(e){return"function"==typeof e.mergeDeep?e.mergeDeep.apply(e,n):n[n.length-1]}))},We.prototype.sort=function(e){return Ut(fn(this,e))},We.prototype.sortBy=function(e,t){return Ut(fn(this,t,e))},We.prototype.withMutations=function(e){var t=this.asMutable();return e(t),t.wasAltered()?t.__ensureOwner(this.__ownerID):this},We.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new S)},We.prototype.asImmutable=function(){return this.__ensureOwner()},We.prototype.wasAltered=function(){return this.__altered},We.prototype.__iterator=function(e,t){return new et(this,e,t)},We.prototype.__iterate=function(e,t){var n=this,r=0;return this._root&&this._root.iterate((function(t){return r++,e(t[1],t[0],n)}),t),r},We.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?rt(this.size,this._root,e,this.__hash):(this.__ownerID=e,this.__altered=!1,this)},We.isMap=He;var $e,Je="@@__IMMUTABLE_MAP__@@",Ke=We.prototype;function Ye(e,t){this.ownerID=e,this.entries=t}function Ge(e,t,n){this.ownerID=e,this.bitmap=t,this.nodes=n}function Qe(e,t,n){this.ownerID=e,this.count=t,this.nodes=n}function Ze(e,t,n){this.ownerID=e,this.keyHash=t,this.entries=n}function Xe(e,t,n){this.ownerID=e,this.keyHash=t,this.entry=n}function et(e,t,n){this._type=t,this._reverse=n,this._stack=e._root&&nt(e._root)}function tt(e,t){return z(e,t[0],t[1])}function nt(e,t){return{node:e,index:0,__prev:t}}function rt(e,t,n,r){var o=Object.create(Ke);return o.size=e,o._root=t,o.__ownerID=n,o.__hash=r,o.__altered=!1,o}function ot(){return $e||($e=rt(0))}function at(e,t,n){var r,o;if(e._root){var a=_(w),i=_(x);if(r=it(e._root,e.__ownerID,0,void 0,t,n,a,i),!i.value)return e;o=e.size+(a.value?n===b?-1:1:0)}else{if(n===b)return e;o=1,r=new Ye(e.__ownerID,[[t,n]])}return e.__ownerID?(e.size=o,e._root=r,e.__hash=void 0,e.__altered=!0,e):r?rt(o,r):ot()}function it(e,t,n,r,o,a,i,u){return e?e.update(t,n,r,o,a,i,u):a===b?e:(E(u),E(i),new Xe(t,r,[o,a]))}function ut(e){return e.constructor===Xe||e.constructor===Ze}function st(e,t,n,r,o){if(e.keyHash===r)return new Ze(t,r,[e.entry,o]);var a,i=(0===n?e.keyHash:e.keyHash>>>n)&y,u=(0===n?r:r>>>n)&y;return new Ge(t,1<>>=1)i[u]=1&n?t[a++]:void 0;return i[r]=o,new Qe(e,a+1,i)}function pt(e,t,n){for(var o=[],a=0;a>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,e+=e>>8,127&(e+=e>>16)}function yt(e,t,n,r){var o=r?e:k(e);return o[t]=n,o}function bt(e,t,n,r){var o=e.length+1;if(r&&t+1===o)return e[t]=n,e;for(var a=new Array(o),i=0,u=0;u=xt)return ct(e,s,r,o);var p=e&&e===this.ownerID,h=p?s:k(s);return f?u?c===l-1?h.pop():h[c]=h.pop():h[c]=[r,o]:h.push([r,o]),p?(this.entries=h,this):new Ye(e,h)}},Ge.prototype.get=function(e,t,n,r){void 0===t&&(t=Ce(n));var o=1<<((0===e?t:t>>>e)&y),a=this.bitmap;return 0==(a&o)?r:this.nodes[gt(a&o-1)].get(e+v,t,n,r)},Ge.prototype.update=function(e,t,n,r,o,a,i){void 0===n&&(n=Ce(r));var u=(0===t?n:n>>>t)&y,s=1<=_t)return ft(e,p,c,u,d);if(l&&!d&&2===p.length&&ut(p[1^f]))return p[1^f];if(l&&d&&1===p.length&&ut(d))return d;var m=e&&e===this.ownerID,g=l?d?c:c^s:c|s,w=l?d?yt(p,f,d,m):wt(p,f,m):bt(p,f,d,m);return m?(this.bitmap=g,this.nodes=w,this):new Ge(e,g,w)},Qe.prototype.get=function(e,t,n,r){void 0===t&&(t=Ce(n));var o=(0===e?t:t>>>e)&y,a=this.nodes[o];return a?a.get(e+v,t,n,r):r},Qe.prototype.update=function(e,t,n,r,o,a,i){void 0===n&&(n=Ce(r));var u=(0===t?n:n>>>t)&y,s=o===b,c=this.nodes,l=c[u];if(s&&!l)return this;var f=it(l,e,t+v,n,r,o,a,i);if(f===l)return this;var p=this.count;if(l){if(!f&&--p0&&r=0&&e>>t&y;if(r>=this.array.length)return new Ct([],e);var o,a=0===r;if(t>0){var i=this.array[r];if((o=i&&i.removeBefore(e,t-v,n))===i&&a)return this}if(a&&!o)return this;var u=Lt(this,e);if(!a)for(var s=0;s>>t&y;if(o>=this.array.length)return this;if(t>0){var a=this.array[o];if((r=a&&a.removeAfter(e,t-v,n))===a&&o===this.array.length-1)return this}var i=Lt(this,e);return i.array.splice(o+1),r&&(i.array[o]=r),i};var jt,Tt,It={};function Nt(e,t){var n=e._origin,r=e._capacity,o=qt(r),a=e._tail;return i(e._root,e._level,0);function i(e,t,n){return 0===t?u(e,n):s(e,t,n)}function u(e,i){var u=i===o?a&&a.array:e&&e.array,s=i>n?0:n-i,c=r-i;return c>g&&(c=g),function(){if(s===c)return It;var e=t?--c:s++;return u&&u[e]}}function s(e,o,a){var u,s=e&&e.array,c=a>n?0:n-a>>o,l=1+(r-a>>o);return l>g&&(l=g),function(){for(;;){if(u){var e=u();if(e!==It)return e;u=null}if(c===l)return It;var n=t?--l:c++;u=i(s&&s[n],o-v,a+(n<=e.size||t<0)return e.withMutations((function(e){t<0?Ft(e,t).set(0,n):Ft(e,0,t+1).set(t,n)}));t+=e._origin;var r=e._tail,o=e._root,a=_(x);return t>=qt(e._capacity)?r=Dt(r,e.__ownerID,0,t,n,a):o=Dt(o,e.__ownerID,e._level,t,n,a),a.value?e.__ownerID?(e._root=o,e._tail=r,e.__hash=void 0,e.__altered=!0,e):Pt(e._origin,e._capacity,e._level,o,r):e}function Dt(e,t,n,r,o,a){var i,u=r>>>n&y,s=e&&u0){var c=e&&e.array[u],l=Dt(c,t,n-v,r,o,a);return l===c?e:((i=Lt(e,t)).array[u]=l,i)}return s&&e.array[u]===o?e:(E(a),i=Lt(e,t),void 0===o&&u===i.array.length-1?i.array.pop():i.array[u]=o,i)}function Lt(e,t){return t&&e&&t===e.ownerID?e:new Ct(e?e.array.slice():[],t)}function Bt(e,t){if(t>=qt(e._capacity))return e._tail;if(t<1<0;)n=n.array[t>>>r&y],r-=v;return n}}function Ft(e,t,n){void 0!==t&&(t|=0),void 0!==n&&(n|=0);var r=e.__ownerID||new S,o=e._origin,a=e._capacity,i=o+t,u=void 0===n?a:n<0?a+n:o+n;if(i===o&&u===a)return e;if(i>=u)return e.clear();for(var s=e._level,c=e._root,l=0;i+l<0;)c=new Ct(c&&c.array.length?[void 0,c]:[],r),l+=1<<(s+=v);l&&(i+=l,o+=l,u+=l,a+=l);for(var f=qt(a),p=qt(u);p>=1<f?new Ct([],r):h;if(h&&p>f&&iv;g-=v){var b=f>>>g&y;m=m.array[b]=Lt(m.array[b],r)}m.array[f>>>v&y]=h}if(u=p)i-=p,u-=p,s=v,c=null,d=d&&d.removeBefore(r,0,i);else if(i>o||p>>s&y;if(w!==p>>>s&y)break;w&&(l+=(1<o&&(c=c.removeBefore(r,s,i-l)),c&&pa&&(a=c.size),i(s)||(c=c.map((function(e){return he(e)}))),r.push(c)}return a>e.size&&(e=e.setSize(a)),mt(e,t,r)}function qt(e){return e>>v<=g&&i.size>=2*a.size?(r=(o=i.filter((function(e,t){return void 0!==e&&u!==t}))).toKeyedSeq().map((function(e){return e[0]})).flip().toMap(),e.__ownerID&&(r.__ownerID=o.__ownerID=e.__ownerID)):(r=a.remove(t),o=u===i.size-1?i.pop():i.set(u,void 0))}else if(s){if(n===i.get(u)[1])return e;r=a,o=i.set(u,[t,n])}else r=a.set(t,i.size),o=i.set(i.size,[t,n]);return e.__ownerID?(e.size=r.size,e._map=r,e._list=o,e.__hash=void 0,e):Wt(r,o)}function Jt(e,t){this._iter=e,this._useKeys=t,this.size=e.size}function Kt(e){this._iter=e,this.size=e.size}function Yt(e){this._iter=e,this.size=e.size}function Gt(e){this._iter=e,this.size=e.size}function Qt(e){var t=bn(e);return t._iter=e,t.size=e.size,t.flip=function(){return e},t.reverse=function(){var t=e.reverse.apply(this);return t.flip=function(){return e.reverse()},t},t.has=function(t){return e.includes(t)},t.includes=function(t){return e.has(t)},t.cacheResult=wn,t.__iterateUncached=function(t,n){var r=this;return e.__iterate((function(e,n){return!1!==t(n,e,r)}),n)},t.__iteratorUncached=function(t,n){if(t===R){var r=e.__iterator(t,n);return new F((function(){var e=r.next();if(!e.done){var t=e.value[0];e.value[0]=e.value[1],e.value[1]=t}return e}))}return e.__iterator(t===M?P:M,n)},t}function Zt(e,t,n){var r=bn(e);return r.size=e.size,r.has=function(t){return e.has(t)},r.get=function(r,o){var a=e.get(r,b);return a===b?o:t.call(n,a,r,e)},r.__iterateUncached=function(r,o){var a=this;return e.__iterate((function(e,o,i){return!1!==r(t.call(n,e,o,i),o,a)}),o)},r.__iteratorUncached=function(r,o){var a=e.__iterator(R,o);return new F((function(){var o=a.next();if(o.done)return o;var i=o.value,u=i[0];return z(r,u,t.call(n,i[1],u,e),o)}))},r}function Xt(e,t){var n=bn(e);return n._iter=e,n.size=e.size,n.reverse=function(){return e},e.flip&&(n.flip=function(){var t=Qt(e);return t.reverse=function(){return e.flip()},t}),n.get=function(n,r){return e.get(t?n:-1-n,r)},n.has=function(n){return e.has(t?n:-1-n)},n.includes=function(t){return e.includes(t)},n.cacheResult=wn,n.__iterate=function(t,n){var r=this;return e.__iterate((function(e,n){return t(e,n,r)}),!n)},n.__iterator=function(t,n){return e.__iterator(t,!n)},n}function en(e,t,n,r){var o=bn(e);return r&&(o.has=function(r){var o=e.get(r,b);return o!==b&&!!t.call(n,o,r,e)},o.get=function(r,o){var a=e.get(r,b);return a!==b&&t.call(n,a,r,e)?a:o}),o.__iterateUncached=function(o,a){var i=this,u=0;return e.__iterate((function(e,a,s){if(t.call(n,e,a,s))return u++,o(e,r?a:u-1,i)}),a),u},o.__iteratorUncached=function(o,a){var i=e.__iterator(R,a),u=0;return new F((function(){for(;;){var a=i.next();if(a.done)return a;var s=a.value,c=s[0],l=s[1];if(t.call(n,l,c,e))return z(o,r?c:u++,l,a)}}))},o}function tn(e,t,n){var r=We().asMutable();return e.__iterate((function(o,a){r.update(t.call(n,o,a,e),0,(function(e){return e+1}))})),r.asImmutable()}function nn(e,t,n){var r=u(e),o=(l(e)?Ut():We()).asMutable();e.__iterate((function(a,i){o.update(t.call(n,a,i,e),(function(e){return(e=e||[]).push(r?[i,a]:a),e}))}));var a=yn(e);return o.map((function(t){return mn(e,a(t))}))}function rn(e,t,n,r){var o=e.size;if(void 0!==t&&(t|=0),void 0!==n&&(n===1/0?n=o:n|=0),j(t,n,o))return e;var a=T(t,o),i=I(n,o);if(a!=a||i!=i)return rn(e.toSeq().cacheResult(),t,n,r);var u,s=i-a;s==s&&(u=s<0?0:s);var c=bn(e);return c.size=0===u?u:e.size&&u||void 0,!r&&ae(e)&&u>=0&&(c.get=function(t,n){return(t=O(this,t))>=0&&tu)return q();var e=o.next();return r||t===M?e:z(t,s-1,t===P?void 0:e.value[1],e)}))},c}function on(e,t,n){var r=bn(e);return r.__iterateUncached=function(r,o){var a=this;if(o)return this.cacheResult().__iterate(r,o);var i=0;return e.__iterate((function(e,o,u){return t.call(n,e,o,u)&&++i&&r(e,o,a)})),i},r.__iteratorUncached=function(r,o){var a=this;if(o)return this.cacheResult().__iterator(r,o);var i=e.__iterator(R,o),u=!0;return new F((function(){if(!u)return q();var e=i.next();if(e.done)return e;var o=e.value,s=o[0],c=o[1];return t.call(n,c,s,a)?r===R?e:z(r,s,c,e):(u=!1,q())}))},r}function an(e,t,n,r){var o=bn(e);return o.__iterateUncached=function(o,a){var i=this;if(a)return this.cacheResult().__iterate(o,a);var u=!0,s=0;return e.__iterate((function(e,a,c){if(!u||!(u=t.call(n,e,a,c)))return s++,o(e,r?a:s-1,i)})),s},o.__iteratorUncached=function(o,a){var i=this;if(a)return this.cacheResult().__iterator(o,a);var u=e.__iterator(R,a),s=!0,c=0;return new F((function(){var e,a,l;do{if((e=u.next()).done)return r||o===M?e:z(o,c++,o===P?void 0:e.value[1],e);var f=e.value;a=f[0],l=f[1],s&&(s=t.call(n,l,a,i))}while(s);return o===R?e:z(o,a,l,e)}))},o}function un(e,t){var n=u(e),o=[e].concat(t).map((function(e){return i(e)?n&&(e=r(e)):e=n?ue(e):se(Array.isArray(e)?e:[e]),e})).filter((function(e){return 0!==e.size}));if(0===o.length)return e;if(1===o.length){var a=o[0];if(a===e||n&&u(a)||s(e)&&s(a))return a}var c=new te(o);return n?c=c.toKeyedSeq():s(e)||(c=c.toSetSeq()),(c=c.flatten(!0)).size=o.reduce((function(e,t){if(void 0!==e){var n=t.size;if(void 0!==n)return e+n}}),0),c}function sn(e,t,n){var r=bn(e);return r.__iterateUncached=function(r,o){var a=0,u=!1;function s(e,c){var l=this;e.__iterate((function(e,o){return(!t||c0}function dn(e,t,r){var o=bn(e);return o.size=new te(r).map((function(e){return e.size})).min(),o.__iterate=function(e,t){for(var n,r=this.__iterator(M,t),o=0;!(n=r.next()).done&&!1!==e(n.value,o++,this););return o},o.__iteratorUncached=function(e,o){var a=r.map((function(e){return e=n(e),W(o?e.reverse():e)})),i=0,u=!1;return new F((function(){var n;return u||(n=a.map((function(e){return e.next()})),u=n.some((function(e){return e.done}))),u?q():z(e,i++,t.apply(null,n.map((function(e){return e.value}))))}))},o}function mn(e,t){return ae(e)?t:e.constructor(t)}function vn(e){if(e!==Object(e))throw new TypeError("Expected [K, V] tuple: "+e)}function gn(e){return Ve(e.size),A(e)}function yn(e){return u(e)?r:s(e)?o:a}function bn(e){return Object.create((u(e)?K:s(e)?Y:G).prototype)}function wn(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):J.prototype.cacheResult.call(this)}function xn(e,t){return e>t?1:e=0;n--)t={value:arguments[n],next:t};return this.__ownerID?(this.size=e,this._head=t,this.__hash=void 0,this.__altered=!0,this):Kn(e,t)},Vn.prototype.pushAll=function(e){if(0===(e=o(e)).size)return this;Ve(e.size);var t=this.size,n=this._head;return e.reverse().forEach((function(e){t++,n={value:e,next:n}})),this.__ownerID?(this.size=t,this._head=n,this.__hash=void 0,this.__altered=!0,this):Kn(t,n)},Vn.prototype.pop=function(){return this.slice(1)},Vn.prototype.unshift=function(){return this.push.apply(this,arguments)},Vn.prototype.unshiftAll=function(e){return this.pushAll(e)},Vn.prototype.shift=function(){return this.pop.apply(this,arguments)},Vn.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):Yn()},Vn.prototype.slice=function(e,t){if(j(e,t,this.size))return this;var n=T(e,this.size);if(I(t,this.size)!==this.size)return Se.prototype.slice.call(this,e,t);for(var r=this.size-n,o=this._head;n--;)o=o.next;return this.__ownerID?(this.size=r,this._head=o,this.__hash=void 0,this.__altered=!0,this):Kn(r,o)},Vn.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?Kn(this.size,this._head,e,this.__hash):(this.__ownerID=e,this.__altered=!1,this)},Vn.prototype.__iterate=function(e,t){if(t)return this.reverse().__iterate(e);for(var n=0,r=this._head;r&&!1!==e(r.value,n++,this);)r=r.next;return n},Vn.prototype.__iterator=function(e,t){if(t)return this.reverse().__iterator(e);var n=0,r=this._head;return new F((function(){if(r){var t=r.value;return r=r.next,z(e,n++,t)}return q()}))},Vn.isStack=Wn;var Hn,$n="@@__IMMUTABLE_STACK__@@",Jn=Vn.prototype;function Kn(e,t,n,r){var o=Object.create(Jn);return o.size=e,o._head=t,o.__ownerID=n,o.__hash=r,o.__altered=!1,o}function Yn(){return Hn||(Hn=Kn(0))}function Gn(e,t){var n=function(n){e.prototype[n]=t[n]};return Object.keys(t).forEach(n),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(t).forEach(n),e}Jn[$n]=!0,Jn.withMutations=Ke.withMutations,Jn.asMutable=Ke.asMutable,Jn.asImmutable=Ke.asImmutable,Jn.wasAltered=Ke.wasAltered,n.Iterator=F,Gn(n,{toArray:function(){Ve(this.size);var e=new Array(this.size||0);return this.valueSeq().__iterate((function(t,n){e[n]=t})),e},toIndexedSeq:function(){return new Kt(this)},toJS:function(){return this.toSeq().map((function(e){return e&&"function"==typeof e.toJS?e.toJS():e})).__toJS()},toJSON:function(){return this.toSeq().map((function(e){return e&&"function"==typeof e.toJSON?e.toJSON():e})).__toJS()},toKeyedSeq:function(){return new Jt(this,!0)},toMap:function(){return We(this.toKeyedSeq())},toObject:function(){Ve(this.size);var e={};return this.__iterate((function(t,n){e[n]=t})),e},toOrderedMap:function(){return Ut(this.toKeyedSeq())},toOrderedSet:function(){return Ln(u(this)?this.valueSeq():this)},toSet:function(){return jn(u(this)?this.valueSeq():this)},toSetSeq:function(){return new Yt(this)},toSeq:function(){return s(this)?this.toIndexedSeq():u(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return Vn(u(this)?this.valueSeq():this)},toList:function(){return St(u(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(e,t){return 0===this.size?e+t:e+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+t},concat:function(){return mn(this,un(this,e.call(arguments,0)))},includes:function(e){return this.some((function(t){return ge(t,e)}))},entries:function(){return this.__iterator(R)},every:function(e,t){Ve(this.size);var n=!0;return this.__iterate((function(r,o,a){if(!e.call(t,r,o,a))return n=!1,!1})),n},filter:function(e,t){return mn(this,en(this,e,t,!0))},find:function(e,t,n){var r=this.findEntry(e,t);return r?r[1]:n},forEach:function(e,t){return Ve(this.size),this.__iterate(t?e.bind(t):e)},join:function(e){Ve(this.size),e=void 0!==e?""+e:",";var t="",n=!0;return this.__iterate((function(r){n?n=!1:t+=e,t+=null!=r?r.toString():""})),t},keys:function(){return this.__iterator(P)},map:function(e,t){return mn(this,Zt(this,e,t))},reduce:function(e,t,n){var r,o;return Ve(this.size),arguments.length<2?o=!0:r=t,this.__iterate((function(t,a,i){o?(o=!1,r=t):r=e.call(n,r,t,a,i)})),r},reduceRight:function(e,t,n){var r=this.toKeyedSeq().reverse();return r.reduce.apply(r,arguments)},reverse:function(){return mn(this,Xt(this,!0))},slice:function(e,t){return mn(this,rn(this,e,t,!0))},some:function(e,t){return!this.every(tr(e),t)},sort:function(e){return mn(this,fn(this,e))},values:function(){return this.__iterator(M)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some((function(){return!0}))},count:function(e,t){return A(e?this.toSeq().filter(e,t):this)},countBy:function(e,t){return tn(this,e,t)},equals:function(e){return ye(this,e)},entrySeq:function(){var e=this;if(e._cache)return new te(e._cache);var t=e.toSeq().map(er).toIndexedSeq();return t.fromEntrySeq=function(){return e.toSeq()},t},filterNot:function(e,t){return this.filter(tr(e),t)},findEntry:function(e,t,n){var r=n;return this.__iterate((function(n,o,a){if(e.call(t,n,o,a))return r=[o,n],!1})),r},findKey:function(e,t){var n=this.findEntry(e,t);return n&&n[0]},findLast:function(e,t,n){return this.toKeyedSeq().reverse().find(e,t,n)},findLastEntry:function(e,t,n){return this.toKeyedSeq().reverse().findEntry(e,t,n)},findLastKey:function(e,t){return this.toKeyedSeq().reverse().findKey(e,t)},first:function(){return this.find(C)},flatMap:function(e,t){return mn(this,cn(this,e,t))},flatten:function(e){return mn(this,sn(this,e,!0))},fromEntrySeq:function(){return new Gt(this)},get:function(e,t){return this.find((function(t,n){return ge(n,e)}),void 0,t)},getIn:function(e,t){for(var n,r=this,o=_n(e);!(n=o.next()).done;){var a=n.value;if((r=r&&r.get?r.get(a,b):b)===b)return t}return r},groupBy:function(e,t){return nn(this,e,t)},has:function(e){return this.get(e,b)!==b},hasIn:function(e){return this.getIn(e,b)!==b},isSubset:function(e){return e="function"==typeof e.includes?e:n(e),this.every((function(t){return e.includes(t)}))},isSuperset:function(e){return(e="function"==typeof e.isSubset?e:n(e)).isSubset(this)},keyOf:function(e){return this.findKey((function(t){return ge(t,e)}))},keySeq:function(){return this.toSeq().map(Xn).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},lastKeyOf:function(e){return this.toKeyedSeq().reverse().keyOf(e)},max:function(e){return pn(this,e)},maxBy:function(e,t){return pn(this,t,e)},min:function(e){return pn(this,e?nr(e):ar)},minBy:function(e,t){return pn(this,t?nr(t):ar,e)},rest:function(){return this.slice(1)},skip:function(e){return this.slice(Math.max(0,e))},skipLast:function(e){return mn(this,this.toSeq().reverse().skip(e).reverse())},skipWhile:function(e,t){return mn(this,an(this,e,t,!0))},skipUntil:function(e,t){return this.skipWhile(tr(e),t)},sortBy:function(e,t){return mn(this,fn(this,t,e))},take:function(e){return this.slice(0,Math.max(0,e))},takeLast:function(e){return mn(this,this.toSeq().reverse().take(e).reverse())},takeWhile:function(e,t){return mn(this,on(this,e,t))},takeUntil:function(e,t){return this.takeWhile(tr(e),t)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=ir(this))}});var Qn=n.prototype;Qn[f]=!0,Qn[B]=Qn.values,Qn.__toJS=Qn.toArray,Qn.__toStringMapper=rr,Qn.inspect=Qn.toSource=function(){return this.toString()},Qn.chain=Qn.flatMap,Qn.contains=Qn.includes,Gn(r,{flip:function(){return mn(this,Qt(this))},mapEntries:function(e,t){var n=this,r=0;return mn(this,this.toSeq().map((function(o,a){return e.call(t,[a,o],r++,n)})).fromEntrySeq())},mapKeys:function(e,t){var n=this;return mn(this,this.toSeq().flip().map((function(r,o){return e.call(t,r,o,n)})).flip())}});var Zn=r.prototype;function Xn(e,t){return t}function er(e,t){return[t,e]}function tr(e){return function(){return!e.apply(this,arguments)}}function nr(e){return function(){return-e.apply(this,arguments)}}function rr(e){return"string"==typeof e?JSON.stringify(e):String(e)}function or(){return k(arguments)}function ar(e,t){return et?-1:0}function ir(e){if(e.size===1/0)return 0;var t=l(e),n=u(e),r=t?1:0;return ur(e.__iterate(n?t?function(e,t){r=31*r+sr(Ce(e),Ce(t))|0}:function(e,t){r=r+sr(Ce(e),Ce(t))|0}:t?function(e){r=31*r+Ce(e)|0}:function(e){r=r+Ce(e)|0}),r)}function ur(e,t){return t=Ae(t,3432918353),t=Ae(t<<15|t>>>-15,461845907),t=Ae(t<<13|t>>>-13,5),t=Ae((t=(t+3864292196|0)^e)^t>>>16,2246822507),t=Oe((t=Ae(t^t>>>13,3266489909))^t>>>16)}function sr(e,t){return e^t+2654435769+(e<<6)+(e>>2)|0}return Zn[p]=!0,Zn[B]=Qn.entries,Zn.__toJS=Qn.toObject,Zn.__toStringMapper=function(e,t){return JSON.stringify(t)+": "+rr(e)},Gn(o,{toKeyedSeq:function(){return new Jt(this,!1)},filter:function(e,t){return mn(this,en(this,e,t,!1))},findIndex:function(e,t){var n=this.findEntry(e,t);return n?n[0]:-1},indexOf:function(e){var t=this.keyOf(e);return void 0===t?-1:t},lastIndexOf:function(e){var t=this.lastKeyOf(e);return void 0===t?-1:t},reverse:function(){return mn(this,Xt(this,!1))},slice:function(e,t){return mn(this,rn(this,e,t,!1))},splice:function(e,t){var n=arguments.length;if(t=Math.max(0|t,0),0===n||2===n&&!t)return this;e=T(e,e<0?this.count():this.size);var r=this.slice(0,e);return mn(this,1===n?r:r.concat(k(arguments,2),this.slice(e+t)))},findLastIndex:function(e,t){var n=this.findLastEntry(e,t);return n?n[0]:-1},first:function(){return this.get(0)},flatten:function(e){return mn(this,sn(this,e,!1))},get:function(e,t){return(e=O(this,e))<0||this.size===1/0||void 0!==this.size&&e>this.size?t:this.find((function(t,n){return n===e}),void 0,t)},has:function(e){return(e=O(this,e))>=0&&(void 0!==this.size?this.size===1/0||e1)try{return decodeURIComponent(t[1])}catch(e){console.error(e)}return null}function Ne(e){return t=e.replace(/\.[^./]*$/,""),Y()(J()(t));var t}function Pe(e,t,n,r,a){if(!t)return[];var u=[],s=t.get("nullable"),c=t.get("required"),f=t.get("maximum"),h=t.get("minimum"),d=t.get("type"),m=t.get("format"),g=t.get("maxLength"),b=t.get("minLength"),x=t.get("uniqueItems"),_=t.get("maxItems"),E=t.get("minItems"),S=t.get("pattern"),k=n||!0===c,A=null!=e;if(s&&null===e||!d||!(k||A&&"array"===d||!(!k&&!A)))return[];var O="string"===d&&e,C="array"===d&&l()(e)&&e.length,j="array"===d&&W.a.List.isList(e)&&e.count(),T=[O,C,j,"array"===d&&"string"==typeof e&&e,"file"===d&&e instanceof ue.a.File,"boolean"===d&&(e||!1===e),"number"===d&&(e||0===e),"integer"===d&&(e||0===e),"object"===d&&"object"===i()(e)&&null!==e,"object"===d&&"string"==typeof e&&e],I=N()(T).call(T,(function(e){return!!e}));if(k&&!I&&!r)return u.push("Required field is not provided"),u;if("object"===d&&(null===a||"application/json"===a)){var P,M=e;if("string"==typeof e)try{M=JSON.parse(e)}catch(e){return u.push("Parameter string value must be valid JSON"),u}if(t&&t.has("required")&&Ee(c.isList)&&c.isList()&&y()(c).call(c,(function(e){void 0===M[e]&&u.push({propKey:e,error:"Required property not found"})})),t&&t.has("properties"))y()(P=t.get("properties")).call(P,(function(e,t){var n=Pe(M[t],e,!1,r,a);u.push.apply(u,o()(p()(n).call(n,(function(e){return{propKey:t,error:e}}))))}))}if(S){var R=function(e,t){if(!new RegExp(t).test(e))return"Value must follow pattern "+t}(e,S);R&&u.push(R)}if(E&&"array"===d){var D=function(e,t){var n;if(!e&&t>=1||e&&e.lengtht)return v()(n="Array must not contain more then ".concat(t," item")).call(n,1===t?"":"s")}(e,_);L&&u.push({needRemove:!0,error:L})}if(x&&"array"===d){var B=function(e,t){if(e&&("true"===t||!0===t)){var n=Object(V.fromJS)(e),r=n.toSet();if(e.length>r.size){var o=Object(V.Set)();if(y()(n).call(n,(function(e,t){w()(n).call(n,(function(t){return Ee(t.equals)?t.equals(e):t===e})).size>1&&(o=o.add(t))})),0!==o.size)return p()(o).call(o,(function(e){return{index:e,error:"No duplicates allowed."}})).toArray()}}}(e,x);B&&u.push.apply(u,o()(B))}if(g||0===g){var F=function(e,t){var n;if(e.length>t)return v()(n="Value must be no longer than ".concat(t," character")).call(n,1!==t?"s":"")}(e,g);F&&u.push(F)}if(b){var z=function(e,t){var n;if(e.lengtht)return"Value must be less than ".concat(t)}(e,f);q&&u.push(q)}if(h||0===h){var U=function(e,t){if(e2&&void 0!==arguments[2]?arguments[2]:{},r=n.isOAS3,o=void 0!==r&&r,a=n.bypassRequiredCheck,i=void 0!==a&&a,u=e.get("required"),s=Object(le.a)(e,{isOAS3:o}),c=s.schema,l=s.parameterContentMediaType;return Pe(t,c,u,i,l)},Re=function(e,t,n){if(e&&(!e.xml||!e.xml.name)){if(e.xml=e.xml||{},!e.$$ref)return e.type||e.items||e.properties||e.additionalProperties?'\n\x3c!-- XML example cannot be generated; root element name is undefined --\x3e':null;var r=e.$$ref.match(/\S*\/(\S+)$/);e.xml.name=r[1]}return Object(ie.memoizedCreateXMLExample)(e,t,n)},De=[{when:/json/,shouldStringifyTypes:["string"]}],Le=["object"],Be=function(e,t,n,r){var a=Object(ie.memoizedSampleFromSchema)(e,t,r),u=i()(a),s=S()(De).call(De,(function(e,t){var r;return t.when.test(n)?v()(r=[]).call(r,o()(e),o()(t.shouldStringifyTypes)):e}),Le);return te()(s,(function(e){return e===u}))?M()(a,null,2):a},Fe=function(e,t,n,r){var o,a=Be(e,t,n,r);try{"\n"===(o=me.a.dump(me.a.load(a),{lineWidth:-1}))[o.length-1]&&(o=T()(o).call(o,0,o.length-1))}catch(e){return console.error(e),"error: could not generate yaml example"}return o.replace(/\t/g," ")},ze=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;return e&&Ee(e.toJS)&&(e=e.toJS()),r&&Ee(r.toJS)&&(r=r.toJS()),/xml/.test(t)?Re(e,n,r):/(yaml|yml)/.test(t)?Fe(e,n,t,r):Be(e,n,t,r)},qe=function(){var e={},t=ue.a.location.search;if(!t)return{};if(""!=t){var n=t.substr(1).split("&");for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(r=n[r].split("="),e[decodeURIComponent(r[0])]=r[1]&&decodeURIComponent(r[1])||"")}return e},Ue=function(t){return(t instanceof e?t:e.from(t.toString(),"utf-8")).toString("base64")},Ve={operationsSorter:{alpha:function(e,t){return e.get("path").localeCompare(t.get("path"))},method:function(e,t){return e.get("method").localeCompare(t.get("method"))}},tagsSorter:{alpha:function(e,t){return e.localeCompare(t)}}},We=function(e){var t=[];for(var n in e){var r=e[n];void 0!==r&&""!==r&&t.push([n,"=",encodeURIComponent(r).replace(/%20/g,"+")].join(""))}return t.join("&")},He=function(e,t,n){return!!X()(n,(function(n){return re()(e[n],t[n])}))};function $e(e){return"string"!=typeof e||""===e?"":Object(H.sanitizeUrl)(e)}function Je(e){return!(!e||D()(e).call(e,"localhost")>=0||D()(e).call(e,"127.0.0.1")>=0||"none"===e)}function Ke(e){if(!W.a.OrderedMap.isOrderedMap(e))return null;if(!e.size)return null;var t=B()(e).call(e,(function(e,t){return z()(t).call(t,"2")&&_()(e.get("content")||{}).length>0})),n=e.get("default")||W.a.OrderedMap(),r=(n.get("content")||W.a.OrderedMap()).keySeq().toJS().length?n:null;return t||r}var Ye=function(e){return"string"==typeof e||e instanceof String?U()(e).call(e).replace(/\s/g,"%20"):""},Ge=function(e){return ce()(Ye(e).replace(/%20/g,"_"))},Qe=function(e){return w()(e).call(e,(function(e,t){return/^x-/.test(t)}))},Ze=function(e){return w()(e).call(e,(function(e,t){return/^pattern|maxLength|minLength|maximum|minimum/.test(t)}))};function Xe(e,t){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0};if("object"!==i()(e)||l()(e)||null===e||!t)return e;var o=A()({},e);return y()(n=_()(o)).call(n,(function(e){e===t&&r(o[e],e)?delete o[e]:o[e]=Xe(o[e],t,r)})),o}function et(e){if("string"==typeof e)return e;if(e&&e.toJS&&(e=e.toJS()),"object"===i()(e)&&null!==e)try{return M()(e,null,2)}catch(t){return String(e)}return null==e?"":e.toString()}function tt(e){return"number"==typeof e?e.toString():e}function nt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.returnAll,r=void 0!==n&&n,o=t.allowHashes,a=void 0===o||o;if(!W.a.Map.isMap(e))throw new Error("paramToIdentifier: received a non-Im.Map parameter as input");var i,u,s,c=e.get("name"),l=e.get("in"),f=[];e&&e.hashCode&&l&&c&&a&&f.push(v()(i=v()(u="".concat(l,".")).call(u,c,".hash-")).call(i,e.hashCode()));l&&c&&f.push(v()(s="".concat(l,".")).call(s,c));return f.push(c),r?f:f[0]||""}function rt(e,t){var n,r=nt(e,{returnAll:!0});return w()(n=p()(r).call(r,(function(e){return t[e]}))).call(n,(function(e){return void 0!==e}))[0]}function ot(){return it(pe()(32).toString("base64"))}function at(e){return it(de()("sha256").update(e).digest("base64"))}function it(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var ut=function(e){return!e||!(!ge(e)||!e.isEmpty())}}).call(this,n(132).Buffer)},function(e,t){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(226);function o(e,t){for(var n=0;n1?t-1:0),r=1;r1&&void 0!==arguments[1]?arguments[1]:r,n=null,a=null;return function(){return o(t,n,arguments)||(a=e.apply(null,arguments)),n=arguments,a}}))},function(e,t,n){(function(t){var n=function(e){return e&&e.Math==Math&&e};e.exports=n("object"==typeof globalThis&&globalThis)||n("object"==typeof window&&window)||n("object"==typeof self&&self)||n("object"==typeof t&&t)||function(){return this}()||Function("return this")()}).call(this,n(57))},function(e,t,n){e.exports=n(385)},function(e,t,n){var r=n(166),o=n(515);function a(t){return"function"==typeof r&&"symbol"==typeof o?(e.exports=a=function(e){return typeof e},e.exports.default=e.exports,e.exports.__esModule=!0):(e.exports=a=function(e){return e&&"function"==typeof r&&e.constructor===r&&e!==r.prototype?"symbol":typeof e},e.exports.default=e.exports,e.exports.__esModule=!0),a(t)}e.exports=a,e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){e.exports=n(351)},function(e,t,n){e.exports=n(349)},function(e,t,n){"use strict";var r=n(17),o=n(93),a=n(27),i=n(41),u=n(111).f,s=n(331),c=n(34),l=n(84),f=n(85),p=n(44),h=function(e){var t=function(n,r,a){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(n);case 2:return new e(n,r)}return new e(n,r,a)}return o(e,this,arguments)};return t.prototype=e.prototype,t};e.exports=function(e,t){var n,o,d,m,v,g,y,b,w=e.target,x=e.global,_=e.stat,E=e.proto,S=x?r:_?r[w]:(r[w]||{}).prototype,k=x?c:c[w]||f(c,w,{})[w],A=k.prototype;for(d in t)n=!s(x?d:w+(_?".":"#")+d,e.forced)&&S&&p(S,d),v=k[d],n&&(g=e.noTargetGet?(b=u(S,d))&&b.value:S[d]),m=n&&g?g:t[d],n&&typeof v==typeof m||(y=e.bind&&n?l(m,r):e.wrap&&n?h(m):E&&i(m)?a(m):m,(e.sham||m&&m.sham||v&&v.sham)&&f(y,"sham",!0),f(k,d,y),E&&(p(c,o=w+"Prototype")||f(c,o,{}),f(c[o],d,m),e.real&&A&&!A[d]&&f(A,d,m)))}},function(e,t,n){e.exports=n(381)},function(e,t,n){e.exports=n(352)},function(e,t,n){var r=n(420),o=n(421),a=n(800),i=n(802),u=n(807),s=n(809),c=n(814),l=n(226),f=n(3);function p(e,t){var n=r(e);if(o){var u=o(e);t&&(u=a(u).call(u,(function(t){return i(e,t).enumerable}))),n.push.apply(n,u)}return n}e.exports=function(e){for(var t=1;t>",i=function(){invariant(!1,"ImmutablePropTypes type checking code is stripped in production.")};i.isRequired=i;var u=function(){return i};function s(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":e instanceof o.Iterable?"Immutable."+e.toSource().split(" ")[0]:t}function c(e){function t(t,n,r,o,i,u){for(var s=arguments.length,c=Array(s>6?s-6:0),l=6;l4)}function l(e){var t=e.get("swagger");return"string"==typeof t&&i()(t).call(t,"2.0")}function f(e){return function(t,n){return function(r){return n&&n.specSelectors&&n.specSelectors.specJson?c(n.specSelectors.specJson())?s.a.createElement(e,o()({},r,n,{Ori:t})):s.a.createElement(t,r):(console.warn("OAS3 wrapper: couldn't get spec"),null)}}}},function(e,t,n){e.exports=n(535)},function(e,t,n){var r=n(17),o=n(212),a=n(44),i=n(171),u=n(210),s=n(329),c=o("wks"),l=r.Symbol,f=l&&l.for,p=s?l:l&&l.withoutSetter||i;e.exports=function(e){if(!a(c,e)||!u&&"string"!=typeof c[e]){var t="Symbol."+e;u&&a(l,e)?c[e]=l[e]:c[e]=s&&f?f(t):p(t)}return c[e]}},function(e,t,n){var r=n(242);e.exports=function(e,t,n){var o=null==e?void 0:r(e,t);return void 0===o?n:o}},function(e,t,n){e.exports=n(840)},function(e,t){e.exports=function(e){return"function"==typeof e}},function(e,t,n){var r=n(34);e.exports=function(e){return r[e+"Prototype"]}},function(e,t,n){var r=n(41);e.exports=function(e){return"object"==typeof e?null!==e:r(e)}},function(e,t,n){var r=n(27),o=n(62),a=r({}.hasOwnProperty);e.exports=Object.hasOwn||function(e,t){return a(o(e),t)}},function(e,t,n){var r=n(34),o=n(44),a=n(223),i=n(63).f;e.exports=function(e){var t=r.Symbol||(r.Symbol={});o(t,e)||i(t,e,{value:a.f(e)})}},function(e,t,n){"use strict";n.r(t),n.d(t,"UPDATE_SPEC",(function(){return ee})),n.d(t,"UPDATE_URL",(function(){return te})),n.d(t,"UPDATE_JSON",(function(){return ne})),n.d(t,"UPDATE_PARAM",(function(){return re})),n.d(t,"UPDATE_EMPTY_PARAM_INCLUSION",(function(){return oe})),n.d(t,"VALIDATE_PARAMS",(function(){return ae})),n.d(t,"SET_RESPONSE",(function(){return ie})),n.d(t,"SET_REQUEST",(function(){return ue})),n.d(t,"SET_MUTATED_REQUEST",(function(){return se})),n.d(t,"LOG_REQUEST",(function(){return ce})),n.d(t,"CLEAR_RESPONSE",(function(){return le})),n.d(t,"CLEAR_REQUEST",(function(){return fe})),n.d(t,"CLEAR_VALIDATE_PARAMS",(function(){return pe})),n.d(t,"UPDATE_OPERATION_META_VALUE",(function(){return he})),n.d(t,"UPDATE_RESOLVED",(function(){return de})),n.d(t,"UPDATE_RESOLVED_SUBTREE",(function(){return me})),n.d(t,"SET_SCHEME",(function(){return ve})),n.d(t,"updateSpec",(function(){return ge})),n.d(t,"updateResolved",(function(){return ye})),n.d(t,"updateUrl",(function(){return be})),n.d(t,"updateJsonSpec",(function(){return we})),n.d(t,"parseToJson",(function(){return xe})),n.d(t,"resolveSpec",(function(){return Ee})),n.d(t,"requestResolvedSubtree",(function(){return Ae})),n.d(t,"changeParam",(function(){return Oe})),n.d(t,"changeParamByIdentity",(function(){return Ce})),n.d(t,"updateResolvedSubtree",(function(){return je})),n.d(t,"invalidateResolvedSubtreeCache",(function(){return Te})),n.d(t,"validateParams",(function(){return Ie})),n.d(t,"updateEmptyParamInclusion",(function(){return Ne})),n.d(t,"clearValidateParams",(function(){return Pe})),n.d(t,"changeConsumesValue",(function(){return Me})),n.d(t,"changeProducesValue",(function(){return Re})),n.d(t,"setResponse",(function(){return De})),n.d(t,"setRequest",(function(){return Le})),n.d(t,"setMutatedRequest",(function(){return Be})),n.d(t,"logRequest",(function(){return Fe})),n.d(t,"executeRequest",(function(){return ze})),n.d(t,"execute",(function(){return qe})),n.d(t,"clearResponse",(function(){return Ue})),n.d(t,"clearRequest",(function(){return Ve})),n.d(t,"setScheme",(function(){return We}));var r=n(25),o=n.n(r),a=n(54),i=n.n(a),u=n(72),s=n.n(u),c=n(19),l=n.n(c),f=n(40),p=n.n(f),h=n(24),d=n.n(h),m=n(4),v=n.n(m),g=n(319),y=n.n(g),b=n(30),w=n.n(b),x=n(197),_=n.n(x),E=n(66),S=n.n(E),k=n(12),A=n.n(k),O=n(198),C=n.n(O),j=n(18),T=n.n(j),I=n(23),N=n.n(I),P=n(2),M=n.n(P),R=n(15),D=n.n(R),L=n(21),B=n.n(L),F=n(320),z=n.n(F),q=n(70),U=n(1),V=n(89),W=n.n(V),H=n(141),$=n(457),J=n.n($),K=n(458),Y=n.n(K),G=n(321),Q=n.n(G),Z=n(5),X=["path","method"],ee="spec_update_spec",te="spec_update_url",ne="spec_update_json",re="spec_update_param",oe="spec_update_empty_param_inclusion",ae="spec_validate_param",ie="spec_set_response",ue="spec_set_request",se="spec_set_mutated_request",ce="spec_log_request",le="spec_clear_response",fe="spec_clear_request",pe="spec_clear_validate_param",he="spec_update_operation_meta_value",de="spec_update_resolved",me="spec_update_resolved_subtree",ve="set_scheme";function ge(e){var t,n=(t=e,J()(t)?t:"").replace(/\t/g," ");if("string"==typeof e)return{type:ee,payload:n}}function ye(e){return{type:de,payload:e}}function be(e){return{type:te,payload:e}}function we(e){return{type:ne,payload:e}}var xe=function(e){return function(t){var n=t.specActions,r=t.specSelectors,o=t.errActions,a=r.specStr,i=null;try{e=e||a(),o.clear({source:"parser"}),i=q.a.load(e)}catch(e){return console.error(e),o.newSpecErr({source:"parser",level:"error",message:e.reason,line:e.mark&&e.mark.line?e.mark.line+1:void 0})}return i&&"object"===l()(i)?n.updateJsonSpec(i):{}}},_e=!1,Ee=function(e,t){return function(n){var r=n.specActions,o=n.specSelectors,a=n.errActions,i=n.fn,u=i.fetch,s=i.resolve,c=i.AST,l=void 0===c?{}:c,f=n.getConfigs;_e||(console.warn("specActions.resolveSpec is deprecated since v3.10.0 and will be removed in v4.0.0; use requestResolvedSubtree instead!"),_e=!0);var p=f(),h=p.modelPropertyMacro,m=p.parameterMacro,g=p.requestInterceptor,b=p.responseInterceptor;void 0===e&&(e=o.specJson()),void 0===t&&(t=o.url());var w=l.getLineNumberForPath?l.getLineNumberForPath:function(){},x=o.specStr();return s({fetch:u,spec:e,baseDoc:t,modelPropertyMacro:h,parameterMacro:m,requestInterceptor:g,responseInterceptor:b}).then((function(e){var t=e.spec,n=e.errors;if(a.clear({type:"thrown"}),d()(n)&&n.length>0){var o=v()(n).call(n,(function(e){return console.error(e),e.line=e.fullPath?w(x,e.fullPath):null,e.path=e.fullPath?e.fullPath.join("."):null,e.level="error",e.type="thrown",e.source="resolver",y()(e,"message",{enumerable:!0,value:e.message}),e}));a.newThrownErrBatch(o)}return r.updateResolved(t)}))}},Se=[],ke=Y()(s()(p.a.mark((function e(){var t,n,r,o,a,i,u,c,l,f,h,m,g,b,x,E,k,O;return p.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=Se.system){e.next=4;break}return console.error("debResolveSubtrees: don't have a system to operate on, aborting."),e.abrupt("return");case 4:if(n=t.errActions,r=t.errSelectors,o=t.fn,a=o.resolveSubtree,i=o.fetch,u=o.AST,c=void 0===u?{}:u,l=t.specSelectors,f=t.specActions,a){e.next=8;break}return console.error("Error: Swagger-Client did not provide a `resolveSubtree` method, doing nothing."),e.abrupt("return");case 8:return h=c.getLineNumberForPath?c.getLineNumberForPath:function(){},m=l.specStr(),g=t.getConfigs(),b=g.modelPropertyMacro,x=g.parameterMacro,E=g.requestInterceptor,k=g.responseInterceptor,e.prev=11,e.next=14,w()(Se).call(Se,function(){var e=s()(p.a.mark((function e(t,o){var u,c,f,g,w,O,j,T,I;return p.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t;case 2:return u=e.sent,c=u.resultMap,f=u.specWithCurrentSubtrees,e.next=7,a(f,o,{baseDoc:l.url(),modelPropertyMacro:b,parameterMacro:x,requestInterceptor:E,responseInterceptor:k});case 7:if(g=e.sent,w=g.errors,O=g.spec,r.allErrors().size&&n.clearBy((function(e){var t;return"thrown"!==e.get("type")||"resolver"!==e.get("source")||!_()(t=e.get("fullPath")).call(t,(function(e,t){return e===o[t]||void 0===o[t]}))})),d()(w)&&w.length>0&&(j=v()(w).call(w,(function(e){return e.line=e.fullPath?h(m,e.fullPath):null,e.path=e.fullPath?e.fullPath.join("."):null,e.level="error",e.type="thrown",e.source="resolver",y()(e,"message",{enumerable:!0,value:e.message}),e})),n.newThrownErrBatch(j)),!O||!l.isOAS3()||"components"!==o[0]||"securitySchemes"!==o[1]){e.next=15;break}return e.next=15,S.a.all(v()(T=A()(I=C()(O)).call(I,(function(e){return"openIdConnect"===e.type}))).call(T,function(){var e=s()(p.a.mark((function e(t){var n,r;return p.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n={url:t.openIdConnectUrl,requestInterceptor:E,responseInterceptor:k},e.prev=1,e.next=4,i(n);case 4:(r=e.sent)instanceof Error||r.status>=400?console.error(r.statusText+" "+n.url):t.openIdConnectData=JSON.parse(r.text),e.next=11;break;case 8:e.prev=8,e.t0=e.catch(1),console.error(e.t0);case 11:case"end":return e.stop()}}),e,null,[[1,8]])})));return function(t){return e.apply(this,arguments)}}()));case 15:return Q()(c,o,O),Q()(f,o,O),e.abrupt("return",{resultMap:c,specWithCurrentSubtrees:f});case 18:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}(),S.a.resolve({resultMap:(l.specResolvedSubtree([])||Object(U.Map)()).toJS(),specWithCurrentSubtrees:l.specJson().toJS()}));case 14:O=e.sent,delete Se.system,Se=[],e.next=22;break;case 19:e.prev=19,e.t0=e.catch(11),console.error(e.t0);case 22:f.updateResolvedSubtree([],O.resultMap);case 23:case"end":return e.stop()}}),e,null,[[11,19]])}))),35),Ae=function(e){return function(t){var n;T()(n=v()(Se).call(Se,(function(e){return e.join("@@")}))).call(n,e.join("@@"))>-1||(Se.push(e),Se.system=t,ke())}};function Oe(e,t,n,r,o){return{type:re,payload:{path:e,value:r,paramName:t,paramIn:n,isXml:o}}}function Ce(e,t,n,r){return{type:re,payload:{path:e,param:t,value:n,isXml:r}}}var je=function(e,t){return{type:me,payload:{path:e,value:t}}},Te=function(){return{type:me,payload:{path:[],value:Object(U.Map)()}}},Ie=function(e,t){return{type:ae,payload:{pathMethod:e,isOAS3:t}}},Ne=function(e,t,n,r){return{type:oe,payload:{pathMethod:e,paramName:t,paramIn:n,includeEmptyValue:r}}};function Pe(e){return{type:pe,payload:{pathMethod:e}}}function Me(e,t){return{type:he,payload:{path:e,value:t,key:"consumes_value"}}}function Re(e,t){return{type:he,payload:{path:e,value:t,key:"produces_value"}}}var De=function(e,t,n){return{payload:{path:e,method:t,res:n},type:ie}},Le=function(e,t,n){return{payload:{path:e,method:t,req:n},type:ue}},Be=function(e,t,n){return{payload:{path:e,method:t,req:n},type:se}},Fe=function(e){return{payload:e,type:ce}},ze=function(e){return function(t){var n,r,o=t.fn,a=t.specActions,i=t.specSelectors,u=t.getConfigs,c=t.oas3Selectors,l=e.pathName,f=e.method,h=e.operation,m=u(),g=m.requestInterceptor,y=m.responseInterceptor,b=h.toJS();h&&h.get("parameters")&&N()(n=A()(r=h.get("parameters")).call(r,(function(e){return e&&!0===e.get("allowEmptyValue")}))).call(n,(function(t){if(i.parameterInclusionSettingFor([l,f],t.get("name"),t.get("in"))){e.parameters=e.parameters||{};var n=Object(Z.B)(t,e.parameters);(!n||n&&0===n.size)&&(e.parameters[t.get("name")]="")}}));if(e.contextUrl=W()(i.url()).toString(),b&&b.operationId?e.operationId=b.operationId:b&&l&&f&&(e.operationId=o.opId(b,l,f)),i.isOAS3()){var w,x=M()(w="".concat(l,":")).call(w,f);e.server=c.selectedServer(x)||c.selectedServer();var _=c.serverVariables({server:e.server,namespace:x}).toJS(),E=c.serverVariables({server:e.server}).toJS();e.serverVariables=D()(_).length?_:E,e.requestContentType=c.requestContentType(l,f),e.responseContentType=c.responseContentType(l,f)||"*/*";var S,k=c.requestBodyValue(l,f),O=c.requestBodyInclusionSetting(l,f);if(k&&k.toJS)e.requestBody=A()(S=v()(k).call(k,(function(e){return U.Map.isMap(e)?e.get("value"):e}))).call(S,(function(e,t){return(d()(e)?0!==e.length:!Object(Z.q)(e))||O.get(t)})).toJS();else e.requestBody=k}var C=B()({},e);C=o.buildRequest(C),a.setRequest(e.pathName,e.method,C);var j=function(){var t=s()(p.a.mark((function t(n){var r,o;return p.a.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,g.apply(undefined,[n]);case 2:return r=t.sent,o=B()({},r),a.setMutatedRequest(e.pathName,e.method,o),t.abrupt("return",r);case 6:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}();e.requestInterceptor=j,e.responseInterceptor=y;var T=z()();return o.execute(e).then((function(t){t.duration=z()()-T,a.setResponse(e.pathName,e.method,t)})).catch((function(t){"Failed to fetch"===t.message&&(t.name="",t.message='**Failed to fetch.** \n**Possible Reasons:** \n - CORS \n - Network Failure \n - URL scheme must be "http" or "https" for CORS request.'),a.setResponse(e.pathName,e.method,{error:!0,err:Object(H.serializeError)(t)})}))}},qe=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.path,n=e.method,r=i()(e,X);return function(e){var a=e.fn.fetch,i=e.specSelectors,u=e.specActions,s=i.specJsonWithResolvedSubtrees().toJS(),c=i.operationScheme(t,n),l=i.contentTypeValues([t,n]).toJS(),f=l.requestContentType,p=l.responseContentType,h=/xml/i.test(f),d=i.parameterValues([t,n],h).toJS();return u.executeRequest(o()(o()({},r),{},{fetch:a,spec:s,pathName:t,method:n,parameters:d,requestContentType:f,scheme:c,responseContentType:p}))}};function Ue(e,t){return{type:le,payload:{path:e,method:t}}}function Ve(e,t){return{type:fe,payload:{path:e,method:t}}}function We(e,t,n){return{type:ve,payload:{scheme:e,path:t,method:n}}}},function(e,t,n){var r;!function(){"use strict";var n={}.hasOwnProperty;function o(){for(var e=[],t=0;t=e.length?{done:!0}:{done:!1,value:e[u++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var c,l=!0,f=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return l=e.done,e},e:function(e){f=!0,c=e},f:function(){try{l||null==n.return||n.return()}finally{if(f)throw c}}}},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t){var n=Function.prototype.call;e.exports=n.bind?n.bind(n):function(){return n.apply(n,arguments)}},function(e,t,n){var r=n(17),o=n(43),a=r.String,i=r.TypeError;e.exports=function(e){if(o(e))return e;throw i(a(e)+" is not an object")}},function(e,t){var n=Array.isArray;e.exports=n},function(e,t){e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},function(e,t,n){var r=n(421),o=n(423),a=n(820);e.exports=function(e,t){if(null==e)return{};var n,i,u=a(e,t);if(r){var s=r(e);for(i=0;i=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(u[n]=e[n])}return u},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){"use strict";n.r(t),n.d(t,"UPDATE_SELECTED_SERVER",(function(){return r})),n.d(t,"UPDATE_REQUEST_BODY_VALUE",(function(){return o})),n.d(t,"UPDATE_REQUEST_BODY_VALUE_RETAIN_FLAG",(function(){return a})),n.d(t,"UPDATE_REQUEST_BODY_INCLUSION",(function(){return i})),n.d(t,"UPDATE_ACTIVE_EXAMPLES_MEMBER",(function(){return u})),n.d(t,"UPDATE_REQUEST_CONTENT_TYPE",(function(){return s})),n.d(t,"UPDATE_RESPONSE_CONTENT_TYPE",(function(){return c})),n.d(t,"UPDATE_SERVER_VARIABLE_VALUE",(function(){return l})),n.d(t,"SET_REQUEST_BODY_VALIDATE_ERROR",(function(){return f})),n.d(t,"CLEAR_REQUEST_BODY_VALIDATE_ERROR",(function(){return p})),n.d(t,"CLEAR_REQUEST_BODY_VALUE",(function(){return h})),n.d(t,"setSelectedServer",(function(){return d})),n.d(t,"setRequestBodyValue",(function(){return m})),n.d(t,"setRetainRequestBodyValueFlag",(function(){return v})),n.d(t,"setRequestBodyInclusion",(function(){return g})),n.d(t,"setActiveExamplesMember",(function(){return y})),n.d(t,"setRequestContentType",(function(){return b})),n.d(t,"setResponseContentType",(function(){return w})),n.d(t,"setServerVariableValue",(function(){return x})),n.d(t,"setRequestBodyValidateError",(function(){return _})),n.d(t,"clearRequestBodyValidateError",(function(){return E})),n.d(t,"initRequestBodyValidateError",(function(){return S})),n.d(t,"clearRequestBodyValue",(function(){return k}));var r="oas3_set_servers",o="oas3_set_request_body_value",a="oas3_set_request_body_retain_flag",i="oas3_set_request_body_inclusion",u="oas3_set_active_examples_member",s="oas3_set_request_content_type",c="oas3_set_response_content_type",l="oas3_set_server_variable_value",f="oas3_set_request_body_validate_error",p="oas3_clear_request_body_validate_error",h="oas3_clear_request_body_value";function d(e,t){return{type:r,payload:{selectedServerUrl:e,namespace:t}}}function m(e){var t=e.value,n=e.pathMethod;return{type:o,payload:{value:t,pathMethod:n}}}var v=function(e){var t=e.value,n=e.pathMethod;return{type:a,payload:{value:t,pathMethod:n}}};function g(e){var t=e.value,n=e.pathMethod,r=e.name;return{type:i,payload:{value:t,pathMethod:n,name:r}}}function y(e){var t=e.name,n=e.pathMethod,r=e.contextType,o=e.contextName;return{type:u,payload:{name:t,pathMethod:n,contextType:r,contextName:o}}}function b(e){var t=e.value,n=e.pathMethod;return{type:s,payload:{value:t,pathMethod:n}}}function w(e){var t=e.value,n=e.path,r=e.method;return{type:c,payload:{value:t,path:n,method:r}}}function x(e){var t=e.server,n=e.namespace,r=e.key,o=e.val;return{type:l,payload:{server:t,namespace:n,key:r,val:o}}}var _=function(e){var t=e.path,n=e.method,r=e.validationErrors;return{type:f,payload:{path:t,method:n,validationErrors:r}}},E=function(e){var t=e.path,n=e.method;return{type:p,payload:{path:t,method:n}}},S=function(e){var t=e.pathMethod;return{type:p,payload:{path:t[0],method:t[1]}}},k=function(e){var t=e.pathMethod;return{type:h,payload:{pathMethod:t}}}},function(e,t,n){e.exports=n(647)},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){var r=n(34),o=n(17),a=n(41),i=function(e){return a(e)?e:void 0};e.exports=function(e,t){return arguments.length<2?i(r[e])||i(o[e]):r[e]&&r[e][t]||o[e]&&o[e][t]}},function(e,t,n){"use strict";n.d(t,"b",(function(){return m})),n.d(t,"e",(function(){return v})),n.d(t,"c",(function(){return y})),n.d(t,"a",(function(){return b})),n.d(t,"d",(function(){return w}));var r=n(49),o=n.n(r),a=n(19),i=n.n(a),u=n(108),s=n.n(u),c=n(2),l=n.n(c),f=n(53),p=n.n(f),h=function(e){return String.prototype.toLowerCase.call(e)},d=function(e){return e.replace(/[^\w]/gi,"_")};function m(e){var t=e.openapi;return!!t&&s()(t).call(t,"3")}function v(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=r.v2OperationIdCompatibilityMode;if(!e||"object"!==i()(e))return null;var a=(e.operationId||"").replace(/\s/g,"");return a.length?d(e.operationId):g(t,n,{v2OperationIdCompatibilityMode:o})}function g(e,t){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=r.v2OperationIdCompatibilityMode;if(o){var a,i,u=l()(a="".concat(t.toLowerCase(),"_")).call(a,e).replace(/[\s!@#$%^&*()_+=[{\]};:<>|./?,\\'""-]/g,"_");return(u=u||l()(i="".concat(e.substring(1),"_")).call(i,t)).replace(/((_){2,})/g,"_").replace(/^(_)*/g,"").replace(/([_])*$/g,"")}return l()(n="".concat(h(t))).call(n,d(e))}function y(e,t){var n;return l()(n="".concat(h(t),"-")).call(n,e)}function b(e,t){return e&&e.paths?function(e,t){return function(e,t,n){if(!e||"object"!==i()(e)||!e.paths||"object"!==i()(e.paths))return null;var r=e.paths;for(var o in r)for(var a in r[o])if("PARAMETERS"!==a.toUpperCase()){var u=r[o][a];if(u&&"object"===i()(u)){var s={spec:e,pathName:o,method:a.toUpperCase(),operation:u},c=t(s);if(n&&c)return s}}return}(e,t,!0)||null}(e,(function(e){var n=e.pathName,r=e.method,o=e.operation;if(!o||"object"!==i()(o))return!1;var a=o.operationId;return[v(o,n,r),y(n,r),a].some((function(e){return e&&e===t}))})):null}function w(e){var t=e.spec,n=t.paths,r={};if(!n||t.$$normalized)return e;for(var a in n){var i=n[a];if(p()(i)){var u=i.parameters,s=function(e){var n=i[e];if(!p()(n))return"continue";var s=v(n,a,e);if(s){r[s]?r[s].push(n):r[s]=[n];var c=r[s];if(c.length>1)c.forEach((function(e,t){var n;e.__originalOperationId=e.__originalOperationId||e.operationId,e.operationId=l()(n="".concat(s)).call(n,t+1)}));else if(void 0!==n.operationId){var f=c[0];f.__originalOperationId=f.__originalOperationId||n.operationId,f.operationId=s}}if("parameters"!==e){var h=[],d={};for(var m in t)"produces"!==m&&"consumes"!==m&&"security"!==m||(d[m]=t[m],h.push(d));if(u&&(d.parameters=u,h.push(d)),h.length){var g,y=o()(h);try{for(y.s();!(g=y.n()).done;){var b=g.value;for(var w in b)if(n[w]){if("parameters"===w){var x,_=o()(b[w]);try{var E=function(){var e=x.value;n[w].some((function(t){return t.name&&t.name===e.name||t.$ref&&t.$ref===e.$ref||t.$$ref&&t.$$ref===e.$$ref||t===e}))||n[w].push(e)};for(_.s();!(x=_.n()).done;)E()}catch(e){_.e(e)}finally{_.f()}}}else n[w]=b[w]}}catch(e){y.e(e)}finally{y.f()}}}};for(var c in i)s(c)}}return t.$$normalized=!0,e}},function(e,t,n){"use strict";n.r(t),n.d(t,"NEW_THROWN_ERR",(function(){return o})),n.d(t,"NEW_THROWN_ERR_BATCH",(function(){return a})),n.d(t,"NEW_SPEC_ERR",(function(){return i})),n.d(t,"NEW_SPEC_ERR_BATCH",(function(){return u})),n.d(t,"NEW_AUTH_ERR",(function(){return s})),n.d(t,"CLEAR",(function(){return c})),n.d(t,"CLEAR_BY",(function(){return l})),n.d(t,"newThrownErr",(function(){return f})),n.d(t,"newThrownErrBatch",(function(){return p})),n.d(t,"newSpecErr",(function(){return h})),n.d(t,"newSpecErrBatch",(function(){return d})),n.d(t,"newAuthErr",(function(){return m})),n.d(t,"clear",(function(){return v})),n.d(t,"clearBy",(function(){return g}));var r=n(141),o="err_new_thrown_err",a="err_new_thrown_err_batch",i="err_new_spec_err",u="err_new_spec_err_batch",s="err_new_auth_err",c="err_clear",l="err_clear_by";function f(e){return{type:o,payload:Object(r.serializeError)(e)}}function p(e){return{type:a,payload:e}}function h(e){return{type:i,payload:e}}function d(e){return{type:u,payload:e}}function m(e){return{type:s,payload:e}}function v(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:c,payload:e}}function g(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:function(){return!0};return{type:l,payload:e}}},function(e,t,n){var r=n(168),o=n(113);e.exports=function(e){return r(o(e))}},function(e,t,n){var r=n(17),o=n(113),a=r.Object;e.exports=function(e){return a(o(e))}},function(e,t,n){var r=n(17),o=n(48),a=n(330),i=n(51),u=n(169),s=r.TypeError,c=Object.defineProperty;t.f=o?c:function(e,t,n){if(i(e),t=u(t),i(n),a)try{return c(e,t,n)}catch(e){}if("get"in n||"set"in n)throw s("Accessors not supported");return"value"in n&&(e[t]=n.value),e}},function(e,t){"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},function(e,t,n){var r=n(132),o=r.Buffer;function a(e,t){for(var n in e)t[n]=e[n]}function i(e,t,n){return o(e,t,n)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?e.exports=r:(a(r,t),t.Buffer=i),a(o,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},function(e,t,n){e.exports=n(424)},function(e,t,n){var r=n(17),o=n(75),a=r.String;e.exports=function(e){if("Symbol"===o(e))throw TypeError("Cannot convert a Symbol value to a string");return a(e)}},function(e,t,n){n(77);var r=n(507),o=n(17),a=n(75),i=n(85),u=n(130),s=n(38)("toStringTag");for(var c in r){var l=o[c],f=l&&l.prototype;f&&a(f)!==s&&i(f,s,c),u[c]=u.Array}},function(e,t,n){var r=n(355),o="object"==typeof self&&self&&self.Object===Object&&self,a=r||o||Function("return this")();e.exports=a},function(e,t,n){"use strict";function r(e){return null==e}var o={isNothing:r,isObject:function(e){return"object"==typeof e&&null!==e},toArray:function(e){return Array.isArray(e)?e:r(e)?[]:[e]},repeat:function(e,t){var n,r="";for(n=0;nu&&(t=r-u+(a=" ... ").length),n-r>u&&(n=r+u-(i=" ...").length),{str:a+e.slice(t,n).replace(/\t/g,"→")+i,pos:r-t+a.length}}function c(e,t){return o.repeat(" ",t-e.length)+e}var l=function(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||(t.maxLength=79),"number"!=typeof t.indent&&(t.indent=1),"number"!=typeof t.linesBefore&&(t.linesBefore=3),"number"!=typeof t.linesAfter&&(t.linesAfter=2);for(var n,r=/\r?\n|\r|\0/g,a=[0],i=[],u=-1;n=r.exec(e.buffer);)i.push(n.index),a.push(n.index+n[0].length),e.position<=n.index&&u<0&&(u=a.length-2);u<0&&(u=a.length-1);var l,f,p="",h=Math.min(e.line+t.linesAfter,i.length).toString().length,d=t.maxLength-(t.indent+h+3);for(l=1;l<=t.linesBefore&&!(u-l<0);l++)f=s(e.buffer,a[u-l],i[u-l],e.position-(a[u]-a[u-l]),d),p=o.repeat(" ",t.indent)+c((e.line-l+1).toString(),h)+" | "+f.str+"\n"+p;for(f=s(e.buffer,a[u],i[u],e.position,d),p+=o.repeat(" ",t.indent)+c((e.line+1).toString(),h)+" | "+f.str+"\n",p+=o.repeat("-",t.indent+h+3+f.pos)+"^\n",l=1;l<=t.linesAfter&&!(u+l>=i.length);l++)f=s(e.buffer,a[u+l],i[u+l],e.position-(a[u]-a[u+l]),d),p+=o.repeat(" ",t.indent)+c((e.line+l+1).toString(),h)+" | "+f.str+"\n";return p.replace(/\n$/,"")},f=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],p=["scalar","sequence","mapping"];var h=function(e,t){if(t=t||{},Object.keys(t).forEach((function(t){if(-1===f.indexOf(t))throw new u('Unknown option "'+t+'" is met in definition of "'+e+'" YAML type.')})),this.options=t,this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(e){return e},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.representName=t.representName||null,this.defaultStyle=t.defaultStyle||null,this.multi=t.multi||!1,this.styleAliases=function(e){var t={};return null!==e&&Object.keys(e).forEach((function(n){e[n].forEach((function(e){t[String(e)]=n}))})),t}(t.styleAliases||null),-1===p.indexOf(this.kind))throw new u('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')};function d(e,t){var n=[];return e[t].forEach((function(e){var t=n.length;n.forEach((function(n,r){n.tag===e.tag&&n.kind===e.kind&&n.multi===e.multi&&(t=r)})),n[t]=e})),n}function m(e){return this.extend(e)}m.prototype.extend=function(e){var t=[],n=[];if(e instanceof h)n.push(e);else if(Array.isArray(e))n=n.concat(e);else{if(!e||!Array.isArray(e.implicit)&&!Array.isArray(e.explicit))throw new u("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");e.implicit&&(t=t.concat(e.implicit)),e.explicit&&(n=n.concat(e.explicit))}t.forEach((function(e){if(!(e instanceof h))throw new u("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(e.loadKind&&"scalar"!==e.loadKind)throw new u("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(e.multi)throw new u("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")})),n.forEach((function(e){if(!(e instanceof h))throw new u("Specified list of YAML types (or a single Type object) contains a non-Type object.")}));var r=Object.create(m.prototype);return r.implicit=(this.implicit||[]).concat(t),r.explicit=(this.explicit||[]).concat(n),r.compiledImplicit=d(r,"implicit"),r.compiledExplicit=d(r,"explicit"),r.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function r(e){e.multi?(n.multi[e.kind].push(e),n.multi.fallback.push(e)):n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},octal:function(e){return e>=0?"0o"+e.toString(8):"-0o"+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),A=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var O=/^[-+]?[0-9]+e/;var C=new h("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!A.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n;return n="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,"+-".indexOf(t[0])>=0&&(t=t.slice(1)),".inf"===t?1===n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:n*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||o.isNegativeZero(e))},represent:function(e,t){var n;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(o.isNegativeZero(e))return"-0.0";return n=e.toString(10),O.test(n)?n.replace("e",".e"):n},defaultStyle:"lowercase"}),j=w.extend({implicit:[x,_,k,C]}),T=j,I=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),N=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");var P=new h("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:function(e){return null!==e&&(null!==I.exec(e)||null!==N.exec(e))},construct:function(e){var t,n,r,o,a,i,u,s,c=0,l=null;if(null===(t=I.exec(e))&&(t=N.exec(e)),null===t)throw new Error("Date resolve error");if(n=+t[1],r=+t[2]-1,o=+t[3],!t[4])return new Date(Date.UTC(n,r,o));if(a=+t[4],i=+t[5],u=+t[6],t[7]){for(c=t[7].slice(0,3);c.length<3;)c+="0";c=+c}return t[9]&&(l=6e4*(60*+t[10]+ +(t[11]||0)),"-"===t[9]&&(l=-l)),s=new Date(Date.UTC(n,r,o,a,i,u,c)),l&&s.setTime(s.getTime()-l),s},instanceOf:Date,represent:function(e){return e.toISOString()}});var M=new h("tag:yaml.org,2002:merge",{kind:"scalar",resolve:function(e){return"<<"===e||null===e}}),R="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";var D=new h("tag:yaml.org,2002:binary",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,r=0,o=e.length,a=R;for(n=0;n64)){if(t<0)return!1;r+=6}return r%8==0},construct:function(e){var t,n,r=e.replace(/[\r\n=]/g,""),o=r.length,a=R,i=0,u=[];for(t=0;t>16&255),u.push(i>>8&255),u.push(255&i)),i=i<<6|a.indexOf(r.charAt(t));return 0===(n=o%4*6)?(u.push(i>>16&255),u.push(i>>8&255),u.push(255&i)):18===n?(u.push(i>>10&255),u.push(i>>2&255)):12===n&&u.push(i>>4&255),new Uint8Array(u)},predicate:function(e){return"[object Uint8Array]"===Object.prototype.toString.call(e)},represent:function(e){var t,n,r="",o=0,a=e.length,i=R;for(t=0;t>18&63],r+=i[o>>12&63],r+=i[o>>6&63],r+=i[63&o]),o=(o<<8)+e[t];return 0===(n=a%3)?(r+=i[o>>18&63],r+=i[o>>12&63],r+=i[o>>6&63],r+=i[63&o]):2===n?(r+=i[o>>10&63],r+=i[o>>4&63],r+=i[o<<2&63],r+=i[64]):1===n&&(r+=i[o>>2&63],r+=i[o<<4&63],r+=i[64],r+=i[64]),r}}),L=Object.prototype.hasOwnProperty,B=Object.prototype.toString;var F=new h("tag:yaml.org,2002:omap",{kind:"sequence",resolve:function(e){if(null===e)return!0;var t,n,r,o,a,i=[],u=e;for(t=0,n=u.length;t>10),56320+(e-65536&1023))}for(var ae=new Array(256),ie=new Array(256),ue=0;ue<256;ue++)ae[ue]=re(ue)?1:0,ie[ue]=re(ue);function se(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||W,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}function ce(e,t){var n={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return n.snippet=l(n),new u(t,n)}function le(e,t){throw ce(e,t)}function fe(e,t){e.onWarning&&e.onWarning.call(null,ce(e,t))}var pe={YAML:function(e,t,n){var r,o,a;null!==e.version&&le(e,"duplication of %YAML directive"),1!==n.length&&le(e,"YAML directive accepts exactly one argument"),null===(r=/^([0-9]+)\.([0-9]+)$/.exec(n[0]))&&le(e,"ill-formed argument of the YAML directive"),o=parseInt(r[1],10),a=parseInt(r[2],10),1!==o&&le(e,"unacceptable YAML version of the document"),e.version=n[0],e.checkLineBreaks=a<2,1!==a&&2!==a&&fe(e,"unsupported YAML version of the document")},TAG:function(e,t,n){var r,o;2!==n.length&&le(e,"TAG directive accepts exactly two arguments"),r=n[0],o=n[1],Y.test(r)||le(e,"ill-formed tag handle (first argument) of the TAG directive"),H.call(e.tagMap,r)&&le(e,'there is a previously declared suffix for "'+r+'" tag handle'),G.test(o)||le(e,"ill-formed tag prefix (second argument) of the TAG directive");try{o=decodeURIComponent(o)}catch(t){le(e,"tag prefix is malformed: "+o)}e.tagMap[r]=o}};function he(e,t,n,r){var o,a,i,u;if(t1&&(e.result+=o.repeat("\n",t-1))}function we(e,t){var n,r,o=e.tag,a=e.anchor,i=[],u=!1;if(-1!==e.firstTabInLine)return!1;for(null!==e.anchor&&(e.anchorMap[e.anchor]=i),r=e.input.charCodeAt(e.position);0!==r&&(-1!==e.firstTabInLine&&(e.position=e.firstTabInLine,le(e,"tab characters must not be used in indentation")),45===r)&&ee(e.input.charCodeAt(e.position+1));)if(u=!0,e.position++,ge(e,!0,-1)&&e.lineIndent<=t)i.push(null),r=e.input.charCodeAt(e.position);else if(n=e.line,Ee(e,t,3,!1,!0),i.push(e.result),ge(e,!0,-1),r=e.input.charCodeAt(e.position),(e.line===n||e.lineIndent>t)&&0!==r)le(e,"bad indentation of a sequence entry");else if(e.lineIndentt?m=1:e.lineIndent===t?m=0:e.lineIndentt?m=1:e.lineIndent===t?m=0:e.lineIndentt)&&(g&&(i=e.line,u=e.lineStart,s=e.position),Ee(e,t,4,!0,o)&&(g?m=e.result:v=e.result),g||(me(e,p,h,d,m,v,i,u,s),d=m=v=null),ge(e,!0,-1),c=e.input.charCodeAt(e.position)),(e.line===a||e.lineIndent>t)&&0!==c)le(e,"bad indentation of a mapping entry");else if(e.lineIndent=0))break;0===a?le(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):l?le(e,"repeat of an indentation width identifier"):(f=t+a-1,l=!0)}if(X(i)){do{i=e.input.charCodeAt(++e.position)}while(X(i));if(35===i)do{i=e.input.charCodeAt(++e.position)}while(!Z(i)&&0!==i)}for(;0!==i;){for(ve(e),e.lineIndent=0,i=e.input.charCodeAt(e.position);(!l||e.lineIndentf&&(f=e.lineIndent),Z(i))p++;else{if(e.lineIndent0){for(o=i,a=0;o>0;o--)(i=ne(u=e.input.charCodeAt(++e.position)))>=0?a=(a<<4)+i:le(e,"expected hexadecimal character");e.result+=oe(a),e.position++}else le(e,"unknown escape sequence");n=r=e.position}else Z(u)?(he(e,n,r,!0),be(e,ge(e,!1,t)),n=r=e.position):e.position===e.lineStart&&ye(e)?le(e,"unexpected end of the document within a double quoted scalar"):(e.position++,r=e.position)}le(e,"unexpected end of the stream within a double quoted scalar")}(e,h)?g=!0:!function(e){var t,n,r;if(42!==(r=e.input.charCodeAt(e.position)))return!1;for(r=e.input.charCodeAt(++e.position),t=e.position;0!==r&&!ee(r)&&!te(r);)r=e.input.charCodeAt(++e.position);return e.position===t&&le(e,"name of an alias node must contain at least one character"),n=e.input.slice(t,e.position),H.call(e.anchorMap,n)||le(e,'unidentified alias "'+n+'"'),e.result=e.anchorMap[n],ge(e,!0,-1),!0}(e)?function(e,t,n){var r,o,a,i,u,s,c,l,f=e.kind,p=e.result;if(ee(l=e.input.charCodeAt(e.position))||te(l)||35===l||38===l||42===l||33===l||124===l||62===l||39===l||34===l||37===l||64===l||96===l)return!1;if((63===l||45===l)&&(ee(r=e.input.charCodeAt(e.position+1))||n&&te(r)))return!1;for(e.kind="scalar",e.result="",o=a=e.position,i=!1;0!==l;){if(58===l){if(ee(r=e.input.charCodeAt(e.position+1))||n&&te(r))break}else if(35===l){if(ee(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&ye(e)||n&&te(l))break;if(Z(l)){if(u=e.line,s=e.lineStart,c=e.lineIndent,ge(e,!1,-1),e.lineIndent>=t){i=!0,l=e.input.charCodeAt(e.position);continue}e.position=a,e.line=u,e.lineStart=s,e.lineIndent=c;break}}i&&(he(e,o,a,!1),be(e,e.line-u),o=a=e.position,i=!1),X(l)||(a=e.position+1),l=e.input.charCodeAt(++e.position)}return he(e,o,a,!1),!!e.result||(e.kind=f,e.result=p,!1)}(e,h,1===n)&&(g=!0,null===e.tag&&(e.tag="?")):(g=!0,null===e.tag&&null===e.anchor||le(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===m&&(g=s&&we(e,d))),null===e.tag)null!==e.anchor&&(e.anchorMap[e.anchor]=e.result);else if("?"===e.tag){for(null!==e.result&&"scalar"!==e.kind&&le(e,'unacceptable node kind for !> tag; it should be "scalar", not "'+e.kind+'"'),c=0,l=e.implicitTypes.length;c"),null!==e.result&&p.kind!==e.kind&&le(e,"unacceptable node kind for !<"+e.tag+'> tag; it should be "'+p.kind+'", not "'+e.kind+'"'),p.resolve(e.result,e.tag)?(e.result=p.construct(e.result,e.tag),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):le(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")}return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||g}function Se(e){var t,n,r,o,a=e.position,i=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);0!==(o=e.input.charCodeAt(e.position))&&(ge(e,!0,-1),o=e.input.charCodeAt(e.position),!(e.lineIndent>0||37!==o));){for(i=!0,o=e.input.charCodeAt(++e.position),t=e.position;0!==o&&!ee(o);)o=e.input.charCodeAt(++e.position);for(r=[],(n=e.input.slice(t,e.position)).length<1&&le(e,"directive name must not be less than one character in length");0!==o;){for(;X(o);)o=e.input.charCodeAt(++e.position);if(35===o){do{o=e.input.charCodeAt(++e.position)}while(0!==o&&!Z(o));break}if(Z(o))break;for(t=e.position;0!==o&&!ee(o);)o=e.input.charCodeAt(++e.position);r.push(e.input.slice(t,e.position))}0!==o&&ve(e),H.call(pe,n)?pe[n](e,n,r):fe(e,'unknown document directive "'+n+'"')}ge(e,!0,-1),0===e.lineIndent&&45===e.input.charCodeAt(e.position)&&45===e.input.charCodeAt(e.position+1)&&45===e.input.charCodeAt(e.position+2)?(e.position+=3,ge(e,!0,-1)):i&&le(e,"directives end mark is expected"),Ee(e,e.lineIndent-1,4,!1,!0),ge(e,!0,-1),e.checkLineBreaks&&J.test(e.input.slice(a,e.position))&&fe(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&ye(e)?46===e.input.charCodeAt(e.position)&&(e.position+=3,ge(e,!0,-1)):e.position=55296&&r<=56319&&t+1=56320&&n<=57343?1024*(r-55296)+n-56320+65536:r}function Ue(e){return/^\n* /.test(e)}function Ve(e,t,n,r,o,a,i,u){var s,c,l=0,f=null,p=!1,h=!1,d=-1!==r,m=-1,v=Be(c=qe(e,0))&&c!==je&&!Le(c)&&45!==c&&63!==c&&58!==c&&44!==c&&91!==c&&93!==c&&123!==c&&125!==c&&35!==c&&38!==c&&42!==c&&33!==c&&124!==c&&61!==c&&62!==c&&39!==c&&34!==c&&37!==c&&64!==c&&96!==c&&function(e){return!Le(e)&&58!==e}(qe(e,e.length-1));if(t||i)for(s=0;s=65536?s+=2:s++){if(!Be(l=qe(e,s)))return 5;v=v&&ze(l,f,u),f=l}else{for(s=0;s=65536?s+=2:s++){if(10===(l=qe(e,s)))p=!0,d&&(h=h||s-m-1>r&&" "!==e[m+1],m=s);else if(!Be(l))return 5;v=v&&ze(l,f,u),f=l}h=h||d&&s-m-1>r&&" "!==e[m+1]}return p||h?n>9&&Ue(e)?5:i?2===a?5:2:h?4:3:!v||i||o(e)?2===a?5:2:1}function We(e,t,n,r,o){e.dump=function(){if(0===t.length)return 2===e.quotingType?'""':"''";if(!e.noCompatMode&&(-1!==Ie.indexOf(t)||Ne.test(t)))return 2===e.quotingType?'"'+t+'"':"'"+t+"'";var a=e.indent*Math.max(1,n),i=-1===e.lineWidth?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-a),s=r||e.flowLevel>-1&&n>=e.flowLevel;switch(Ve(t,s,e.indent,i,(function(t){return function(e,t){var n,r;for(n=0,r=e.implicitTypes.length;n"+He(t,e.indent)+$e(Re(function(e,t){var n,r,o=/(\n+)([^\n]*)/g,a=(u=e.indexOf("\n"),u=-1!==u?u:e.length,o.lastIndex=u,Je(e.slice(0,u),t)),i="\n"===e[0]||" "===e[0];var u;for(;r=o.exec(e);){var s=r[1],c=r[2];n=" "===c[0],a+=s+(i||n||""===c?"":"\n")+Je(c,t),i=n}return a}(t,i),a));case 5:return'"'+function(e){for(var t,n="",r=0,o=0;o=65536?o+=2:o++)r=qe(e,o),!(t=Te[r])&&Be(r)?(n+=e[o],r>=65536&&(n+=e[o+1])):n+=t||Pe(r);return n}(t)+'"';default:throw new u("impossible error: invalid scalar style")}}()}function He(e,t){var n=Ue(e)?String(t):"",r="\n"===e[e.length-1];return n+(r&&("\n"===e[e.length-2]||"\n"===e)?"+":r?"":"-")+"\n"}function $e(e){return"\n"===e[e.length-1]?e.slice(0,-1):e}function Je(e,t){if(""===e||" "===e[0])return e;for(var n,r,o=/ [^ ]/g,a=0,i=0,u=0,s="";n=o.exec(e);)(u=n.index)-a>t&&(r=i>a?i:u,s+="\n"+e.slice(a,r),a=r+1),i=u;return s+="\n",e.length-a>t&&i>a?s+=e.slice(a,i)+"\n"+e.slice(i+1):s+=e.slice(a),s.slice(1)}function Ke(e,t,n,r){var o,a,i,u="",s=e.tag;for(o=0,a=n.length;o tag resolver accepts not "'+c+'" style');r=s.represent[c](t,c)}e.dump=r}return!0}return!1}function Ge(e,t,n,r,o,a,i){e.tag=null,e.dump=n,Ye(e,n,!1)||Ye(e,n,!0);var s,c=Oe.call(e.dump),l=r;r&&(r=e.flowLevel<0||e.flowLevel>t);var f,p,h="[object Object]"===c||"[object Array]"===c;if(h&&(p=-1!==(f=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||p||2!==e.indent&&t>0)&&(o=!1),p&&e.usedDuplicates[f])e.dump="*ref_"+f;else{if(h&&p&&!e.usedDuplicates[f]&&(e.usedDuplicates[f]=!0),"[object Object]"===c)r&&0!==Object.keys(e.dump).length?(!function(e,t,n,r){var o,a,i,s,c,l,f="",p=e.tag,h=Object.keys(n);if(!0===e.sortKeys)h.sort();else if("function"==typeof e.sortKeys)h.sort(e.sortKeys);else if(e.sortKeys)throw new u("sortKeys must be a boolean or a function");for(o=0,a=h.length;o1024)&&(e.dump&&10===e.dump.charCodeAt(0)?l+="?":l+="? "),l+=e.dump,c&&(l+=De(e,t)),Ge(e,t+1,s,!0,c)&&(e.dump&&10===e.dump.charCodeAt(0)?l+=":":l+=": ",f+=l+=e.dump));e.tag=p,e.dump=f||"{}"}(e,t,e.dump,o),p&&(e.dump="&ref_"+f+e.dump)):(!function(e,t,n){var r,o,a,i,u,s="",c=e.tag,l=Object.keys(n);for(r=0,o=l.length;r1024&&(u+="? "),u+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),Ge(e,t,i,!1,!1)&&(s+=u+=e.dump));e.tag=c,e.dump="{"+s+"}"}(e,t,e.dump),p&&(e.dump="&ref_"+f+" "+e.dump));else if("[object Array]"===c)r&&0!==e.dump.length?(e.noArrayIndent&&!i&&t>0?Ke(e,t-1,e.dump,o):Ke(e,t,e.dump,o),p&&(e.dump="&ref_"+f+e.dump)):(!function(e,t,n){var r,o,a,i="",u=e.tag;for(r=0,o=n.length;r",e.dump=s+" "+e.dump)}return!0}function Qe(e,t){var n,r,o=[],a=[];for(Ze(e,o,a),n=0,r=a.length;n=t.length?(e.target=void 0,{value:void 0,done:!0}):"keys"==n?{value:r,done:!1}:"values"==n?{value:t[r],done:!1}:{value:[r,t[r]],done:!1}}),"values"),a.Arguments=a.Array,o("keys"),o("values"),o("entries")},function(e,t){e.exports=function(e){return null!=e&&"object"==typeof e}},function(e,t,n){"use strict";(function(t){function n(e){return e instanceof t||e instanceof Date||e instanceof RegExp}function r(e){if(e instanceof t){var n=t.alloc?t.alloc(e.length):new t(e.length);return e.copy(n),n}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e);throw new Error("Unexpected situation")}function o(e){var t=[];return e.forEach((function(e,a){"object"==typeof e&&null!==e?Array.isArray(e)?t[a]=o(e):n(e)?t[a]=r(e):t[a]=i({},e):t[a]=e})),t}function a(e,t){return"__proto__"===t?void 0:e[t]}var i=e.exports=function(){if(arguments.length<1||"object"!=typeof arguments[0])return!1;if(arguments.length<2)return arguments[0];var e,t,u=arguments[0],s=Array.prototype.slice.call(arguments,1);return s.forEach((function(s){"object"!=typeof s||null===s||Array.isArray(s)||Object.keys(s).forEach((function(c){return t=a(u,c),(e=a(s,c))===u?void 0:"object"!=typeof e||null===e?void(u[c]=e):Array.isArray(e)?void(u[c]=o(e)):n(e)?void(u[c]=r(e)):"object"!=typeof t||null===t||Array.isArray(t)?void(u[c]=i({},e)):void(u[c]=i(t,e))}))})),u}}).call(this,n(132).Buffer)},function(e,t,n){e.exports=n(619)},function(e,t,n){"use strict";var r=n(946),o=n(947);function a(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}t.parse=b,t.resolve=function(e,t){return b(e,!1,!0).resolve(t)},t.resolveObject=function(e,t){return e?b(e,!1,!0).resolveObject(t):t},t.format=function(e){o.isString(e)&&(e=b(e));return e instanceof a?e.format():a.prototype.format.call(e)},t.Url=a;var i=/^([a-z0-9.+-]+:)/i,u=/:[0-9]*$/,s=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),l=["'"].concat(c),f=["%","/","?",";","#"].concat(l),p=["/","?","#"],h=/^[+a-z0-9A-Z_-]{0,63}$/,d=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},v={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=n(948);function b(e,t,n){if(e&&o.isObject(e)&&e instanceof a)return e;var r=new a;return r.parse(e,t,n),r}a.prototype.parse=function(e,t,n){if(!o.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var a=e.indexOf("?"),u=-1!==a&&a127?P+="x":P+=N[M];if(!P.match(h)){var D=T.slice(0,O),L=T.slice(O+1),B=N.match(d);B&&(D.push(B[1]),L.unshift(B[2])),L.length&&(b="/"+L.join(".")+b),this.hostname=D.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),j||(this.hostname=r.toASCII(this.hostname));var F=this.port?":"+this.port:"",z=this.hostname||"";this.host=z+F,this.href+=this.host,j&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==b[0]&&(b="/"+b))}if(!m[_])for(O=0,I=l.length;O0)&&n.host.split("@"))&&(n.auth=j.shift(),n.host=n.hostname=j.shift());return n.search=e.search,n.query=e.query,o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n}if(!E.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var k=E.slice(-1)[0],A=(n.host||e.host||E.length>1)&&("."===k||".."===k)||""===k,O=0,C=E.length;C>=0;C--)"."===(k=E[C])?E.splice(C,1):".."===k?(E.splice(C,1),O++):O&&(E.splice(C,1),O--);if(!x&&!_)for(;O--;O)E.unshift("..");!x||""===E[0]||E[0]&&"/"===E[0].charAt(0)||E.unshift(""),A&&"/"!==E.join("/").substr(-1)&&E.push("");var j,T=""===E[0]||E[0]&&"/"===E[0].charAt(0);S&&(n.hostname=n.host=T?"":E.length?E.shift():"",(j=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=j.shift(),n.host=n.hostname=j.shift()));return(x=x||n.host&&E.length)&&!T&&E.unshift(""),E.length?n.pathname=E.join("/"):(n.pathname=null,n.path=null),o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},a.prototype.parseHost=function(){var e=this.host,t=u.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},function(e,t,n){"use strict";n.r(t),n.d(t,"SHOW_AUTH_POPUP",(function(){return h})),n.d(t,"AUTHORIZE",(function(){return d})),n.d(t,"LOGOUT",(function(){return m})),n.d(t,"PRE_AUTHORIZE_OAUTH2",(function(){return v})),n.d(t,"AUTHORIZE_OAUTH2",(function(){return g})),n.d(t,"VALIDATE",(function(){return y})),n.d(t,"CONFIGURE_AUTH",(function(){return b})),n.d(t,"RESTORE_AUTHORIZATION",(function(){return w})),n.d(t,"showDefinitions",(function(){return x})),n.d(t,"authorize",(function(){return _})),n.d(t,"authorizeWithPersistOption",(function(){return E})),n.d(t,"logout",(function(){return S})),n.d(t,"logoutWithPersistOption",(function(){return k})),n.d(t,"preAuthorizeImplicit",(function(){return A})),n.d(t,"authorizeOauth2",(function(){return O})),n.d(t,"authorizeOauth2WithPersistOption",(function(){return C})),n.d(t,"authorizePassword",(function(){return j})),n.d(t,"authorizeApplication",(function(){return T})),n.d(t,"authorizeAccessCodeWithFormParams",(function(){return I})),n.d(t,"authorizeAccessCodeWithBasicAuthentication",(function(){return N})),n.d(t,"authorizeRequest",(function(){return P})),n.d(t,"configureAuth",(function(){return M})),n.d(t,"restoreAuthorization",(function(){return R})),n.d(t,"persistAuthorizationIfNeeded",(function(){return D}));var r=n(19),o=n.n(r),a=n(32),i=n.n(a),u=n(21),s=n.n(u),c=n(89),l=n.n(c),f=n(26),p=n(5),h="show_popup",d="authorize",m="logout",v="pre_authorize_oauth2",g="authorize_oauth2",y="validate",b="configure_auth",w="restore_authorization";function x(e){return{type:h,payload:e}}function _(e){return{type:d,payload:e}}var E=function(e){return function(t){var n=t.authActions;n.authorize(e),n.persistAuthorizationIfNeeded()}};function S(e){return{type:m,payload:e}}var k=function(e){return function(t){var n=t.authActions;n.logout(e),n.persistAuthorizationIfNeeded()}},A=function(e){return function(t){var n=t.authActions,r=t.errActions,o=e.auth,a=e.token,u=e.isValid,s=o.schema,c=o.name,l=s.get("flow");delete f.a.swaggerUIRedirectOauth2,"accessCode"===l||u||r.newAuthErr({authId:c,source:"auth",level:"warning",message:"Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"}),a.error?r.newAuthErr({authId:c,source:"auth",level:"error",message:i()(a)}):n.authorizeOauth2WithPersistOption({auth:o,token:a})}};function O(e){return{type:g,payload:e}}var C=function(e){return function(t){var n=t.authActions;n.authorizeOauth2(e),n.persistAuthorizationIfNeeded()}},j=function(e){return function(t){var n=t.authActions,r=e.schema,o=e.name,a=e.username,i=e.password,u=e.passwordType,c=e.clientId,l=e.clientSecret,f={grant_type:"password",scope:e.scopes.join(" "),username:a,password:i},h={};switch(u){case"request-body":!function(e,t,n){t&&s()(e,{client_id:t});n&&s()(e,{client_secret:n})}(f,c,l);break;case"basic":h.Authorization="Basic "+Object(p.a)(c+":"+l);break;default:console.warn("Warning: invalid passwordType ".concat(u," was passed, not including client id and secret"))}return n.authorizeRequest({body:Object(p.b)(f),url:r.get("tokenUrl"),name:o,headers:h,query:{},auth:e})}};var T=function(e){return function(t){var n=t.authActions,r=e.schema,o=e.scopes,a=e.name,i=e.clientId,u=e.clientSecret,s={Authorization:"Basic "+Object(p.a)(i+":"+u)},c={grant_type:"client_credentials",scope:o.join(" ")};return n.authorizeRequest({body:Object(p.b)(c),name:a,url:r.get("tokenUrl"),auth:e,headers:s})}},I=function(e){var t=e.auth,n=e.redirectUrl;return function(e){var r=e.authActions,o=t.schema,a=t.name,i=t.clientId,u=t.clientSecret,s=t.codeVerifier,c={grant_type:"authorization_code",code:t.code,client_id:i,client_secret:u,redirect_uri:n,code_verifier:s};return r.authorizeRequest({body:Object(p.b)(c),name:a,url:o.get("tokenUrl"),auth:t})}},N=function(e){var t=e.auth,n=e.redirectUrl;return function(e){var r=e.authActions,o=t.schema,a=t.name,i=t.clientId,u=t.clientSecret,s=t.codeVerifier,c={Authorization:"Basic "+Object(p.a)(i+":"+u)},l={grant_type:"authorization_code",code:t.code,client_id:i,redirect_uri:n,code_verifier:s};return r.authorizeRequest({body:Object(p.b)(l),name:a,url:o.get("tokenUrl"),auth:t,headers:c})}},P=function(e){return function(t){var n,r=t.fn,a=t.getConfigs,u=t.authActions,c=t.errActions,f=t.oas3Selectors,p=t.specSelectors,h=t.authSelectors,d=e.body,m=e.query,v=void 0===m?{}:m,g=e.headers,y=void 0===g?{}:g,b=e.name,w=e.url,x=e.auth,_=(h.getConfigs()||{}).additionalQueryStringParams;if(p.isOAS3()){var E=f.serverEffectiveValue(f.selectedServer());n=l()(w,E,!0)}else n=l()(w,p.url(),!0);"object"===o()(_)&&(n.query=s()({},n.query,_));var S=n.toString(),k=s()({Accept:"application/json, text/plain, */*","Content-Type":"application/x-www-form-urlencoded","X-Requested-With":"XMLHttpRequest"},y);r.fetch({url:S,method:"post",headers:k,query:v,body:d,requestInterceptor:a().requestInterceptor,responseInterceptor:a().responseInterceptor}).then((function(e){var t=JSON.parse(e.data),n=t&&(t.error||""),r=t&&(t.parseError||"");e.ok?n||r?c.newAuthErr({authId:b,level:"error",source:"auth",message:i()(t)}):u.authorizeOauth2WithPersistOption({auth:x,token:t}):c.newAuthErr({authId:b,level:"error",source:"auth",message:e.statusText})})).catch((function(e){var t=new Error(e).message;if(e.response&&e.response.data){var n=e.response.data;try{var r="string"==typeof n?JSON.parse(n):n;r.error&&(t+=", error: ".concat(r.error)),r.error_description&&(t+=", description: ".concat(r.error_description))}catch(e){}}c.newAuthErr({authId:b,level:"error",source:"auth",message:t})}))}};function M(e){return{type:b,payload:e}}function R(e){return{type:w,payload:e}}var D=function(){return function(e){var t=e.authSelectors;if((0,e.getConfigs)().persistAuthorization){var n=t.authorized();localStorage.setItem("authorized",i()(n.toJS()))}}}},function(e,t,n){var r=n(919);e.exports=function(e){for(var t=1;tS;S++)if((h||S in x)&&(b=_(y=x[S],S,w),e))if(t)A[S]=b;else if(b)switch(e){case 3:return!0;case 5:return y;case 6:return S;case 2:c(A,y)}else switch(e){case 4:return!1;case 7:c(A,y)}return f?-1:o||l?l:A}};e.exports={forEach:l(0),map:l(1),filter:l(2),some:l(3),every:l(4),find:l(5),findIndex:l(6),filterReject:l(7)}},function(e,t,n){"use strict";n.r(t),n.d(t,"lastError",(function(){return M})),n.d(t,"url",(function(){return R})),n.d(t,"specStr",(function(){return D})),n.d(t,"specSource",(function(){return L})),n.d(t,"specJson",(function(){return B})),n.d(t,"specResolved",(function(){return F})),n.d(t,"specResolvedSubtree",(function(){return z})),n.d(t,"specJsonWithResolvedSubtrees",(function(){return U})),n.d(t,"spec",(function(){return V})),n.d(t,"isOAS3",(function(){return W})),n.d(t,"info",(function(){return H})),n.d(t,"externalDocs",(function(){return $})),n.d(t,"version",(function(){return J})),n.d(t,"semver",(function(){return K})),n.d(t,"paths",(function(){return Y})),n.d(t,"operations",(function(){return G})),n.d(t,"consumes",(function(){return Q})),n.d(t,"produces",(function(){return Z})),n.d(t,"security",(function(){return X})),n.d(t,"securityDefinitions",(function(){return ee})),n.d(t,"findDefinition",(function(){return te})),n.d(t,"definitions",(function(){return ne})),n.d(t,"basePath",(function(){return re})),n.d(t,"host",(function(){return oe})),n.d(t,"schemes",(function(){return ae})),n.d(t,"operationsWithRootInherited",(function(){return ie})),n.d(t,"tags",(function(){return ue})),n.d(t,"tagDetails",(function(){return se})),n.d(t,"operationsWithTags",(function(){return ce})),n.d(t,"taggedOperations",(function(){return le})),n.d(t,"responses",(function(){return fe})),n.d(t,"requests",(function(){return pe})),n.d(t,"mutatedRequests",(function(){return he})),n.d(t,"responseFor",(function(){return de})),n.d(t,"requestFor",(function(){return me})),n.d(t,"mutatedRequestFor",(function(){return ve})),n.d(t,"allowTryItOutFor",(function(){return ge})),n.d(t,"parameterWithMetaByIdentity",(function(){return ye})),n.d(t,"parameterInclusionSettingFor",(function(){return be})),n.d(t,"parameterWithMeta",(function(){return we})),n.d(t,"operationWithMeta",(function(){return xe})),n.d(t,"getParameter",(function(){return _e})),n.d(t,"hasHost",(function(){return Ee})),n.d(t,"parameterValues",(function(){return Se})),n.d(t,"parametersIncludeIn",(function(){return ke})),n.d(t,"parametersIncludeType",(function(){return Ae})),n.d(t,"contentTypeValues",(function(){return Oe})),n.d(t,"currentProducesFor",(function(){return Ce})),n.d(t,"producesOptionsFor",(function(){return je})),n.d(t,"consumesOptionsFor",(function(){return Te})),n.d(t,"operationScheme",(function(){return Ie})),n.d(t,"canExecuteScheme",(function(){return Ne})),n.d(t,"validateBeforeExecute",(function(){return Pe})),n.d(t,"getOAS3RequiredRequestBodyContentType",(function(){return Me})),n.d(t,"isMediaTypeSchemaPropertiesEqual",(function(){return Re}));var r=n(13),o=n.n(r),a=n(14),i=n.n(a),u=n(2),s=n.n(u),c=n(20),l=n.n(c),f=n(23),p=n.n(f),h=n(18),d=n.n(h),m=n(4),v=n.n(m),g=n(12),y=n.n(g),b=n(56),w=n.n(b),x=n(30),_=n.n(x),E=n(196),S=n.n(E),k=n(71),A=n.n(k),O=n(24),C=n.n(O),j=n(16),T=n(5),I=n(1),N=["get","put","post","delete","options","head","patch","trace"],P=function(e){return e||Object(I.Map)()},M=Object(j.a)(P,(function(e){return e.get("lastError")})),R=Object(j.a)(P,(function(e){return e.get("url")})),D=Object(j.a)(P,(function(e){return e.get("spec")||""})),L=Object(j.a)(P,(function(e){return e.get("specSource")||"not-editor"})),B=Object(j.a)(P,(function(e){return e.get("json",Object(I.Map)())})),F=Object(j.a)(P,(function(e){return e.get("resolved",Object(I.Map)())})),z=function(e,t){var n;return e.getIn(s()(n=["resolvedSubtrees"]).call(n,i()(t)),void 0)},q=function e(t,n){return I.Map.isMap(t)&&I.Map.isMap(n)?n.get("$$ref")?n:Object(I.OrderedMap)().mergeWith(e,t,n):n},U=Object(j.a)(P,(function(e){return Object(I.OrderedMap)().mergeWith(q,e.get("json"),e.get("resolvedSubtrees"))})),V=function(e){return B(e)},W=Object(j.a)(V,(function(){return!1})),H=Object(j.a)(V,(function(e){return De(e&&e.get("info"))})),$=Object(j.a)(V,(function(e){return De(e&&e.get("externalDocs"))})),J=Object(j.a)(H,(function(e){return e&&e.get("version")})),K=Object(j.a)(J,(function(e){var t;return l()(t=/v?([0-9]*)\.([0-9]*)\.([0-9]*)/i.exec(e)).call(t,1)})),Y=Object(j.a)(U,(function(e){return e.get("paths")})),G=Object(j.a)(Y,(function(e){if(!e||e.size<1)return Object(I.List)();var t=Object(I.List)();return e&&p()(e)?(p()(e).call(e,(function(e,n){if(!e||!p()(e))return{};p()(e).call(e,(function(e,r){var o;d()(N).call(N,r)<0||(t=t.push(Object(I.fromJS)({path:n,method:r,operation:e,id:s()(o="".concat(r,"-")).call(o,n)})))}))})),t):Object(I.List)()})),Q=Object(j.a)(V,(function(e){return Object(I.Set)(e.get("consumes"))})),Z=Object(j.a)(V,(function(e){return Object(I.Set)(e.get("produces"))})),X=Object(j.a)(V,(function(e){return e.get("security",Object(I.List)())})),ee=Object(j.a)(V,(function(e){return e.get("securityDefinitions")})),te=function(e,t){var n=e.getIn(["resolvedSubtrees","definitions",t],null),r=e.getIn(["json","definitions",t],null);return n||r||null},ne=Object(j.a)(V,(function(e){var t=e.get("definitions");return I.Map.isMap(t)?t:Object(I.Map)()})),re=Object(j.a)(V,(function(e){return e.get("basePath")})),oe=Object(j.a)(V,(function(e){return e.get("host")})),ae=Object(j.a)(V,(function(e){return e.get("schemes",Object(I.Map)())})),ie=Object(j.a)(G,Q,Z,(function(e,t,n){return v()(e).call(e,(function(e){return e.update("operation",(function(e){if(e){if(!I.Map.isMap(e))return;return e.withMutations((function(e){return e.get("consumes")||e.update("consumes",(function(e){return Object(I.Set)(e).merge(t)})),e.get("produces")||e.update("produces",(function(e){return Object(I.Set)(e).merge(n)})),e}))}return Object(I.Map)()}))}))})),ue=Object(j.a)(V,(function(e){var t=e.get("tags",Object(I.List)());return I.List.isList(t)?y()(t).call(t,(function(e){return I.Map.isMap(e)})):Object(I.List)()})),se=function(e,t){var n,r=ue(e)||Object(I.List)();return w()(n=y()(r).call(r,I.Map.isMap)).call(n,(function(e){return e.get("name")===t}),Object(I.Map)())},ce=Object(j.a)(ie,ue,(function(e,t){return _()(e).call(e,(function(e,t){var n=Object(I.Set)(t.getIn(["operation","tags"]));return n.count()<1?e.update("default",Object(I.List)(),(function(e){return e.push(t)})):_()(n).call(n,(function(e,n){return e.update(n,Object(I.List)(),(function(e){return e.push(t)}))}),e)}),_()(t).call(t,(function(e,t){return e.set(t.get("name"),Object(I.List)())}),Object(I.OrderedMap)()))})),le=function(e){return function(t){var n,r=(0,t.getConfigs)(),o=r.tagsSorter,a=r.operationsSorter;return v()(n=ce(e).sortBy((function(e,t){return t}),(function(e,t){var n="function"==typeof o?o:T.H.tagsSorter[o];return n?n(e,t):null}))).call(n,(function(t,n){var r="function"==typeof a?a:T.H.operationsSorter[a],o=r?S()(t).call(t,r):t;return Object(I.Map)({tagDetails:se(e,n),operations:o})}))}},fe=Object(j.a)(P,(function(e){return e.get("responses",Object(I.Map)())})),pe=Object(j.a)(P,(function(e){return e.get("requests",Object(I.Map)())})),he=Object(j.a)(P,(function(e){return e.get("mutatedRequests",Object(I.Map)())})),de=function(e,t,n){return fe(e).getIn([t,n],null)},me=function(e,t,n){return pe(e).getIn([t,n],null)},ve=function(e,t,n){return he(e).getIn([t,n],null)},ge=function(){return!0},ye=function(e,t,n){var r,o,a=U(e).getIn(s()(r=["paths"]).call(r,i()(t),["parameters"]),Object(I.OrderedMap)()),u=e.getIn(s()(o=["meta","paths"]).call(o,i()(t),["parameters"]),Object(I.OrderedMap)()),c=v()(a).call(a,(function(e){var t,r,o,a=u.get(s()(t="".concat(n.get("in"),".")).call(t,n.get("name"))),i=u.get(s()(r=s()(o="".concat(n.get("in"),".")).call(o,n.get("name"),".hash-")).call(r,n.hashCode()));return Object(I.OrderedMap)().merge(e,a,i)}));return w()(c).call(c,(function(e){return e.get("in")===n.get("in")&&e.get("name")===n.get("name")}),Object(I.OrderedMap)())},be=function(e,t,n,r){var o,a,u=s()(o="".concat(r,".")).call(o,n);return e.getIn(s()(a=["meta","paths"]).call(a,i()(t),["parameter_inclusions",u]),!1)},we=function(e,t,n,r){var o,a=U(e).getIn(s()(o=["paths"]).call(o,i()(t),["parameters"]),Object(I.OrderedMap)()),u=w()(a).call(a,(function(e){return e.get("in")===r&&e.get("name")===n}),Object(I.OrderedMap)());return ye(e,t,u)},xe=function(e,t,n){var r,o=U(e).getIn(["paths",t,n],Object(I.OrderedMap)()),a=e.getIn(["meta","paths",t,n],Object(I.OrderedMap)()),i=v()(r=o.get("parameters",Object(I.List)())).call(r,(function(r){return ye(e,[t,n],r)}));return Object(I.OrderedMap)().merge(o,a).set("parameters",i)};function _e(e,t,n,r){var o;t=t||[];var a=e.getIn(s()(o=["meta","paths"]).call(o,i()(t),["parameters"]),Object(I.fromJS)([]));return w()(a).call(a,(function(e){return I.Map.isMap(e)&&e.get("name")===n&&e.get("in")===r}))||Object(I.Map)()}var Ee=Object(j.a)(V,(function(e){var t=e.get("host");return"string"==typeof t&&t.length>0&&"/"!==t[0]}));function Se(e,t,n){var r;t=t||[];var o=xe.apply(void 0,s()(r=[e]).call(r,i()(t))).get("parameters",Object(I.List)());return _()(o).call(o,(function(e,t){var r=n&&"body"===t.get("in")?t.get("value_xml"):t.get("value");return e.set(Object(T.A)(t,{allowHashes:!1}),r)}),Object(I.fromJS)({}))}function ke(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(I.List.isList(e))return A()(e).call(e,(function(e){return I.Map.isMap(e)&&e.get("in")===t}))}function Ae(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(I.List.isList(e))return A()(e).call(e,(function(e){return I.Map.isMap(e)&&e.get("type")===t}))}function Oe(e,t){var n,r;t=t||[];var o=U(e).getIn(s()(n=["paths"]).call(n,i()(t)),Object(I.fromJS)({})),a=e.getIn(s()(r=["meta","paths"]).call(r,i()(t)),Object(I.fromJS)({})),u=Ce(e,t),c=o.get("parameters")||new I.List,l=a.get("consumes_value")?a.get("consumes_value"):Ae(c,"file")?"multipart/form-data":Ae(c,"formData")?"application/x-www-form-urlencoded":void 0;return Object(I.fromJS)({requestContentType:l,responseContentType:u})}function Ce(e,t){var n,r;t=t||[];var o=U(e).getIn(s()(n=["paths"]).call(n,i()(t)),null);if(null!==o){var a=e.getIn(s()(r=["meta","paths"]).call(r,i()(t),["produces_value"]),null),u=o.getIn(["produces",0],null);return a||u||"application/json"}}function je(e,t){var n;t=t||[];var r=U(e),a=r.getIn(s()(n=["paths"]).call(n,i()(t)),null);if(null!==a){var u=t,c=o()(u,1)[0],l=a.get("produces",null),f=r.getIn(["paths",c,"produces"],null),p=r.getIn(["produces"],null);return l||f||p}}function Te(e,t){var n;t=t||[];var r=U(e),a=r.getIn(s()(n=["paths"]).call(n,i()(t)),null);if(null!==a){var u=t,c=o()(u,1)[0],l=a.get("consumes",null),f=r.getIn(["paths",c,"consumes"],null),p=r.getIn(["consumes"],null);return l||f||p}}var Ie=function(e,t,n){var r=e.get("url").match(/^([a-z][a-z0-9+\-.]*):/),o=C()(r)?r[1]:null;return e.getIn(["scheme",t,n])||e.getIn(["scheme","_defaultScheme"])||o||""},Ne=function(e,t,n){var r;return d()(r=["http","https"]).call(r,Ie(e,t,n))>-1},Pe=function(e,t){var n;t=t||[];var r=e.getIn(s()(n=["meta","paths"]).call(n,i()(t),["parameters"]),Object(I.fromJS)([])),o=!0;return p()(r).call(r,(function(e){var t=e.get("errors");t&&t.count()&&(o=!1)})),o},Me=function(e,t){var n,r,o={requestBody:!1,requestContentType:{}},a=e.getIn(s()(n=["resolvedSubtrees","paths"]).call(n,i()(t),["requestBody"]),Object(I.fromJS)([]));return a.size<1||(a.getIn(["required"])&&(o.requestBody=a.getIn(["required"])),p()(r=a.getIn(["content"]).entrySeq()).call(r,(function(e){var t=e[0];if(e[1].getIn(["schema","required"])){var n=e[1].getIn(["schema","required"]).toJS();o.requestContentType[t]=n}}))),o},Re=function(e,t,n,r){var o;if((n||r)&&n===r)return!0;var a=e.getIn(s()(o=["resolvedSubtrees","paths"]).call(o,i()(t),["requestBody","content"]),Object(I.fromJS)([]));if(a.size<2||!n||!r)return!1;var u=a.getIn([n,"schema","properties"],Object(I.fromJS)([])),c=a.getIn([r,"schema","properties"],Object(I.fromJS)([]));return!!u.equals(c)};function De(e){return I.Map.isMap(e)?e:new I.Map}},function(e,t,n){"use strict";(function(t){var r=n(847),o=n(848),a=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,i=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,u=/^[a-zA-Z]:/,s=new RegExp("^[\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF]+");function c(e){return(e||"").toString().replace(s,"")}var l=[["#","hash"],["?","query"],function(e,t){return h(t.protocol)?e.replace(/\\/g,"/"):e},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d+)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],f={hash:1,query:1};function p(e){var n,r=("undefined"!=typeof window?window:void 0!==t?t:"undefined"!=typeof self?self:{}).location||{},o={},i=typeof(e=e||r);if("blob:"===e.protocol)o=new m(unescape(e.pathname),{});else if("string"===i)for(n in o=new m(e,{}),f)delete o[n];else if("object"===i){for(n in e)n in f||(o[n]=e[n]);void 0===o.slashes&&(o.slashes=a.test(e.href))}return o}function h(e){return"file:"===e||"ftp:"===e||"http:"===e||"https:"===e||"ws:"===e||"wss:"===e}function d(e,t){e=c(e),t=t||{};var n,r=i.exec(e),o=r[1]?r[1].toLowerCase():"",a=!!r[2],u=!!r[3],s=0;return a?u?(n=r[2]+r[3]+r[4],s=r[2].length+r[3].length):(n=r[2]+r[4],s=r[2].length):u?(n=r[3]+r[4],s=r[3].length):n=r[4],"file:"===o?s>=2&&(n=n.slice(2)):h(o)?n=r[4]:o?a&&(n=n.slice(2)):s>=2&&h(t.protocol)&&(n=r[4]),{protocol:o,slashes:a||h(o),slashesCount:s,rest:n}}function m(e,t,n){if(e=c(e),!(this instanceof m))return new m(e,t,n);var a,i,s,f,v,g,y=l.slice(),b=typeof t,w=this,x=0;for("object"!==b&&"string"!==b&&(n=t,t=null),n&&"function"!=typeof n&&(n=o.parse),a=!(i=d(e||"",t=p(t))).protocol&&!i.slashes,w.slashes=i.slashes||a&&t.slashes,w.protocol=i.protocol||t.protocol||"",e=i.rest,("file:"===i.protocol&&(2!==i.slashesCount||u.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!h(w.protocol)))&&(y[3]=[/(.*)/,"pathname"]);x=4?[t[0],t[1],t[2],t[3],"".concat(t[0],".").concat(t[1]),"".concat(t[0],".").concat(t[2]),"".concat(t[0],".").concat(t[3]),"".concat(t[1],".").concat(t[0]),"".concat(t[1],".").concat(t[2]),"".concat(t[1],".").concat(t[3]),"".concat(t[2],".").concat(t[0]),"".concat(t[2],".").concat(t[1]),"".concat(t[2],".").concat(t[3]),"".concat(t[3],".").concat(t[0]),"".concat(t[3],".").concat(t[1]),"".concat(t[3],".").concat(t[2]),"".concat(t[0],".").concat(t[1],".").concat(t[2]),"".concat(t[0],".").concat(t[1],".").concat(t[3]),"".concat(t[0],".").concat(t[2],".").concat(t[1]),"".concat(t[0],".").concat(t[2],".").concat(t[3]),"".concat(t[0],".").concat(t[3],".").concat(t[1]),"".concat(t[0],".").concat(t[3],".").concat(t[2]),"".concat(t[1],".").concat(t[0],".").concat(t[2]),"".concat(t[1],".").concat(t[0],".").concat(t[3]),"".concat(t[1],".").concat(t[2],".").concat(t[0]),"".concat(t[1],".").concat(t[2],".").concat(t[3]),"".concat(t[1],".").concat(t[3],".").concat(t[0]),"".concat(t[1],".").concat(t[3],".").concat(t[2]),"".concat(t[2],".").concat(t[0],".").concat(t[1]),"".concat(t[2],".").concat(t[0],".").concat(t[3]),"".concat(t[2],".").concat(t[1],".").concat(t[0]),"".concat(t[2],".").concat(t[1],".").concat(t[3]),"".concat(t[2],".").concat(t[3],".").concat(t[0]),"".concat(t[2],".").concat(t[3],".").concat(t[1]),"".concat(t[3],".").concat(t[0],".").concat(t[1]),"".concat(t[3],".").concat(t[0],".").concat(t[2]),"".concat(t[3],".").concat(t[1],".").concat(t[0]),"".concat(t[3],".").concat(t[1],".").concat(t[2]),"".concat(t[3],".").concat(t[2],".").concat(t[0]),"".concat(t[3],".").concat(t[2],".").concat(t[1]),"".concat(t[0],".").concat(t[1],".").concat(t[2],".").concat(t[3]),"".concat(t[0],".").concat(t[1],".").concat(t[3],".").concat(t[2]),"".concat(t[0],".").concat(t[2],".").concat(t[1],".").concat(t[3]),"".concat(t[0],".").concat(t[2],".").concat(t[3],".").concat(t[1]),"".concat(t[0],".").concat(t[3],".").concat(t[1],".").concat(t[2]),"".concat(t[0],".").concat(t[3],".").concat(t[2],".").concat(t[1]),"".concat(t[1],".").concat(t[0],".").concat(t[2],".").concat(t[3]),"".concat(t[1],".").concat(t[0],".").concat(t[3],".").concat(t[2]),"".concat(t[1],".").concat(t[2],".").concat(t[0],".").concat(t[3]),"".concat(t[1],".").concat(t[2],".").concat(t[3],".").concat(t[0]),"".concat(t[1],".").concat(t[3],".").concat(t[0],".").concat(t[2]),"".concat(t[1],".").concat(t[3],".").concat(t[2],".").concat(t[0]),"".concat(t[2],".").concat(t[0],".").concat(t[1],".").concat(t[3]),"".concat(t[2],".").concat(t[0],".").concat(t[3],".").concat(t[1]),"".concat(t[2],".").concat(t[1],".").concat(t[0],".").concat(t[3]),"".concat(t[2],".").concat(t[1],".").concat(t[3],".").concat(t[0]),"".concat(t[2],".").concat(t[3],".").concat(t[0],".").concat(t[1]),"".concat(t[2],".").concat(t[3],".").concat(t[1],".").concat(t[0]),"".concat(t[3],".").concat(t[0],".").concat(t[1],".").concat(t[2]),"".concat(t[3],".").concat(t[0],".").concat(t[2],".").concat(t[1]),"".concat(t[3],".").concat(t[1],".").concat(t[0],".").concat(t[2]),"".concat(t[3],".").concat(t[1],".").concat(t[2],".").concat(t[0]),"".concat(t[3],".").concat(t[2],".").concat(t[0],".").concat(t[1]),"".concat(t[3],".").concat(t[2],".").concat(t[1],".").concat(t[0])]:void 0),g[r]}function b(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,r=e.filter((function(e){return"token"!==e})),o=y(r);return o.reduce((function(e,t){return p()({},e,n[t])}),t)}function w(e){return e.join(" ")}function x(e){var t=e.node,n=e.stylesheet,r=e.style,o=void 0===r?{}:r,a=e.useInlineStyles,i=e.key,u=t.properties,s=t.type,c=t.tagName,l=t.value;if("text"===s)return l;if(c){var f,h=function(e,t){var n=0;return function(r){return n+=1,r.map((function(r,o){return x({node:r,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(o)})}))}}(n,a);if(a){var m=Object.keys(n).reduce((function(e,t){return t.split(".").forEach((function(t){e.includes(t)||e.push(t)})),e}),[]),g=u.className&&u.className.includes("token")?["token"]:[],y=u.className&&g.concat(u.className.filter((function(e){return!m.includes(e)})));f=p()({},u,{className:w(y)||void 0,style:b(u.className,Object.assign({},u.style,o),n)})}else f=p()({},u,{className:w(u.className)});var _=h(t.children);return d.a.createElement(c,v()({key:i},f),_)}}var _=/\n/g;function E(e){var t=e.codeString,n=e.codeStyle,r=e.containerStyle,o=void 0===r?{float:"left",paddingRight:"10px"}:r,a=e.numberStyle,i=void 0===a?{}:a,u=e.startingLineNumber;return d.a.createElement("code",{style:Object.assign({},n,o)},function(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map((function(e,t){var o=t+n;return d.a.createElement("span",{key:"line-".concat(t),className:"react-syntax-highlighter-line-number",style:"function"==typeof r?r(o):r},"".concat(o,"\n"))}))}({lines:t.replace(/\n$/,"").split("\n"),style:i,startingLineNumber:u}))}function S(e,t){return{type:"element",tagName:"span",properties:{key:"line-number--".concat(e),className:["comment","linenumber","react-syntax-highlighter-line-number"],style:t},children:[{type:"text",value:e}]}}function k(e,t,n){var r,o={display:"inline-block",minWidth:(r=n,"".concat(r.toString().length,".25em")),paddingRight:"1em",textAlign:"right",userSelect:"none"},a="function"==typeof e?e(t):e;return p()({},o,a)}function A(e){var t=e.children,n=e.lineNumber,r=e.lineNumberStyle,o=e.largestLineNumber,a=e.showInlineLineNumbers,i=e.lineProps,u=void 0===i?{}:i,s=e.className,c=void 0===s?[]:s,l=e.showLineNumbers,f=e.wrapLongLines,h="function"==typeof u?u(n):u;if(h.className=c,n&&a){var d=k(r,n,o);t.unshift(S(n,d))}return f&l&&(h.style=p()({},h.style,{display:"flex"})),{type:"element",tagName:"span",properties:h,children:t}}function O(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=0;r2&&void 0!==arguments[2]?arguments[2]:[];return A({children:e,lineNumber:t,lineNumberStyle:u,largestLineNumber:i,showInlineLineNumbers:o,lineProps:n,className:a,showLineNumbers:r,wrapLongLines:s})}function m(e,t){if(r&&t&&o){var n=k(u,t,i);e.unshift(S(t,n))}return e}function v(e,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return t||r.length>0?d(e,n,r):m(e,n)}for(var g=function(){var e=l[h],t=e.children[0].value;if(t.match(_)){var n=t.split("\n");n.forEach((function(t,o){var i=r&&f.length+a,u={type:"text",value:"".concat(t,"\n")};if(0===o){var s=v(l.slice(p+1,h).concat(A({children:[u],className:e.properties.className})),i);f.push(s)}else if(o===n.length-1){if(l[h+1]&&l[h+1].children&&l[h+1].children[0]){var c=A({children:[{type:"text",value:"".concat(t)}],className:e.properties.className});l.splice(h+1,0,c)}else{var d=v([u],i,e.properties.className);f.push(d)}}else{var m=v([u],i,e.properties.className);f.push(m)}})),p=h}h++};h .hljs-title":{color:"#88C0D0"},"hljs-keyword":{color:"#81A1C1"},"hljs-literal":{color:"#81A1C1"},"hljs-symbol":{color:"#81A1C1"},"hljs-number":{color:"#B48EAD"},"hljs-regexp":{color:"#EBCB8B"},"hljs-string":{color:"#A3BE8C"},"hljs-title":{color:"#8FBCBB"},"hljs-params":{color:"#D8DEE9"},"hljs-bullet":{color:"#81A1C1"},"hljs-code":{color:"#8FBCBB"},"hljs-emphasis":{fontStyle:"italic"},"hljs-formula":{color:"#8FBCBB"},"hljs-strong":{fontWeight:"bold"},"hljs-link:hover":{textDecoration:"underline"},"hljs-quote":{color:"#4C566A"},"hljs-comment":{color:"#4C566A"},"hljs-doctag":{color:"#8FBCBB"},"hljs-meta":{color:"#5E81AC"},"hljs-meta-keyword":{color:"#5E81AC"},"hljs-meta-string":{color:"#A3BE8C"},"hljs-attr":{color:"#8FBCBB"},"hljs-attribute":{color:"#D8DEE9"},"hljs-builtin-name":{color:"#81A1C1"},"hljs-name":{color:"#81A1C1"},"hljs-section":{color:"#88C0D0"},"hljs-tag":{color:"#81A1C1"},"hljs-variable":{color:"#D8DEE9"},"hljs-template-variable":{color:"#D8DEE9"},"hljs-template-tag":{color:"#5E81AC"},"abnf .hljs-attribute":{color:"#88C0D0"},"abnf .hljs-symbol":{color:"#EBCB8B"},"apache .hljs-attribute":{color:"#88C0D0"},"apache .hljs-section":{color:"#81A1C1"},"arduino .hljs-built_in":{color:"#88C0D0"},"aspectj .hljs-meta":{color:"#D08770"},"aspectj > .hljs-title":{color:"#88C0D0"},"bnf .hljs-attribute":{color:"#8FBCBB"},"clojure .hljs-name":{color:"#88C0D0"},"clojure .hljs-symbol":{color:"#EBCB8B"},"coq .hljs-built_in":{color:"#88C0D0"},"cpp .hljs-meta-string":{color:"#8FBCBB"},"css .hljs-built_in":{color:"#88C0D0"},"css .hljs-keyword":{color:"#D08770"},"diff .hljs-meta":{color:"#8FBCBB"},"ebnf .hljs-attribute":{color:"#8FBCBB"},"glsl .hljs-built_in":{color:"#88C0D0"},"groovy .hljs-meta:not(:first-child)":{color:"#D08770"},"haxe .hljs-meta":{color:"#D08770"},"java .hljs-meta":{color:"#D08770"},"ldif .hljs-attribute":{color:"#8FBCBB"},"lisp .hljs-name":{color:"#88C0D0"},"lua .hljs-built_in":{color:"#88C0D0"},"moonscript .hljs-built_in":{color:"#88C0D0"},"nginx .hljs-attribute":{color:"#88C0D0"},"nginx .hljs-section":{color:"#5E81AC"},"pf .hljs-built_in":{color:"#88C0D0"},"processing .hljs-built_in":{color:"#88C0D0"},"scss .hljs-keyword":{color:"#81A1C1"},"stylus .hljs-keyword":{color:"#81A1C1"},"swift .hljs-meta":{color:"#D08770"},"vim .hljs-built_in":{color:"#88C0D0",fontStyle:"italic"},"yaml .hljs-meta":{color:"#D08770"}},obsidian:{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"#282b2e",color:"#e0e2e4"},"hljs-keyword":{color:"#93c763",fontWeight:"bold"},"hljs-selector-tag":{color:"#93c763",fontWeight:"bold"},"hljs-literal":{color:"#93c763",fontWeight:"bold"},"hljs-selector-id":{color:"#93c763"},"hljs-number":{color:"#ffcd22"},"hljs-attribute":{color:"#668bb0"},"hljs-code":{color:"white"},"hljs-class .hljs-title":{color:"white"},"hljs-section":{color:"white",fontWeight:"bold"},"hljs-regexp":{color:"#d39745"},"hljs-link":{color:"#d39745"},"hljs-meta":{color:"#557182"},"hljs-tag":{color:"#8cbbad"},"hljs-name":{color:"#8cbbad",fontWeight:"bold"},"hljs-bullet":{color:"#8cbbad"},"hljs-subst":{color:"#8cbbad"},"hljs-emphasis":{color:"#8cbbad"},"hljs-type":{color:"#8cbbad",fontWeight:"bold"},"hljs-built_in":{color:"#8cbbad"},"hljs-selector-attr":{color:"#8cbbad"},"hljs-selector-pseudo":{color:"#8cbbad"},"hljs-addition":{color:"#8cbbad"},"hljs-variable":{color:"#8cbbad"},"hljs-template-tag":{color:"#8cbbad"},"hljs-template-variable":{color:"#8cbbad"},"hljs-string":{color:"#ec7600"},"hljs-symbol":{color:"#ec7600"},"hljs-comment":{color:"#818e96"},"hljs-quote":{color:"#818e96"},"hljs-deletion":{color:"#818e96"},"hljs-selector-class":{color:"#A082BD"},"hljs-doctag":{fontWeight:"bold"},"hljs-title":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"}},"tomorrow-night":{"hljs-comment":{color:"#969896"},"hljs-quote":{color:"#969896"},"hljs-variable":{color:"#cc6666"},"hljs-template-variable":{color:"#cc6666"},"hljs-tag":{color:"#cc6666"},"hljs-name":{color:"#cc6666"},"hljs-selector-id":{color:"#cc6666"},"hljs-selector-class":{color:"#cc6666"},"hljs-regexp":{color:"#cc6666"},"hljs-deletion":{color:"#cc6666"},"hljs-number":{color:"#de935f"},"hljs-built_in":{color:"#de935f"},"hljs-builtin-name":{color:"#de935f"},"hljs-literal":{color:"#de935f"},"hljs-type":{color:"#de935f"},"hljs-params":{color:"#de935f"},"hljs-meta":{color:"#de935f"},"hljs-link":{color:"#de935f"},"hljs-attribute":{color:"#f0c674"},"hljs-string":{color:"#b5bd68"},"hljs-symbol":{color:"#b5bd68"},"hljs-bullet":{color:"#b5bd68"},"hljs-addition":{color:"#b5bd68"},"hljs-title":{color:"#81a2be"},"hljs-section":{color:"#81a2be"},"hljs-keyword":{color:"#b294bb"},"hljs-selector-tag":{color:"#b294bb"},hljs:{display:"block",overflowX:"auto",background:"#1d1f21",color:"#c5c8c6",padding:"0.5em"},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}}},X=o()(Z),ee=function(e){return i()(X).call(X,e)?Z[e]:(console.warn("Request style '".concat(e,"' is not available, returning default instead")),Q)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.File=t.Blob=t.FormData=void 0;const r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;t.FormData=r.FormData,t.Blob=r.Blob,t.File=r.File},function(e,t){var n=Function.prototype,r=n.apply,o=n.bind,a=n.call;e.exports="object"==typeof Reflect&&Reflect.apply||(o?a.bind(r):function(){return a.apply(r,arguments)})},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(58);e.exports=r("navigator","userAgent")||""},function(e,t){e.exports=!0},function(e,t){},function(e,t,n){var r,o=n(51),a=n(218),i=n(221),u=n(150),s=n(335),c=n(214),l=n(173),f=l("IE_PROTO"),p=function(){},h=function(e){return"