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 + 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 + 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 c) { + return false; + } + + @Override + public boolean addAll(int index, Collection 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} + + ${source.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 + 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.source} + ${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} - ${java.version} + ${maven.compiler.source} + ${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} - - ${source.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.source.version} + ${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.source} + ${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.source} - ${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 + # fields that will be converted to json and stored in json_data + jsonData: + graphiteVersion: '1.1' + tlsAuth: false + tlsAuthWithCACert: false + # json object of data that will be encrypted. + secureJsonData: + tlsCACert: '...' + tlsClientCert: '...' + tlsClientKey: '...' + version: 1 + # allow users to edit datasources from the UI. + editable: true diff --git a/jhipster-6/bookstore-monolith/src/main/docker/monitoring.yml b/jhipster-6/bookstore-monolith/src/main/docker/monitoring.yml new file mode 100644 index 000000000000..fa75668445de --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/docker/monitoring.yml @@ -0,0 +1,26 @@ +version: '3' +services: + bookstore-prometheus: + image: prom/prometheus:v2.9.2 + volumes: + - ./prometheus/:/etc/prometheus/ + command: + - '--config.file=/etc/prometheus/prometheus.yml' + ports: + - 9090:9090 + # On MacOS, remove next line and replace localhost by host.docker.internal in prometheus/prometheus.yml and + # grafana/provisioning/datasources/datasource.yml + network_mode: 'host' # to test locally running service + bookstore-grafana: + image: grafana/grafana:6.1.4 + volumes: + - ./grafana/provisioning/:/etc/grafana/provisioning/ + environment: + - GF_SECURITY_ADMIN_PASSWORD=admin + - GF_USERS_ALLOW_SIGN_UP=false + - GF_INSTALL_PLUGINS=grafana-piechart-panel + ports: + - 3000:3000 + # On MacOS, remove next line and replace localhost by host.docker.internal in prometheus/prometheus.yml and + # grafana/provisioning/datasources/datasource.yml + network_mode: 'host' # to test locally running service diff --git a/jhipster-5/bookstore-monolith/src/main/docker/mysql.yml b/jhipster-6/bookstore-monolith/src/main/docker/mysql.yml similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/docker/mysql.yml rename to jhipster-6/bookstore-monolith/src/main/docker/mysql.yml diff --git a/jhipster-6/bookstore-monolith/src/main/docker/prometheus/prometheus.yml b/jhipster-6/bookstore-monolith/src/main/docker/prometheus/prometheus.yml new file mode 100644 index 000000000000..73f4c959da7b --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/docker/prometheus/prometheus.yml @@ -0,0 +1,26 @@ +# Sample global config for monitoring JHipster applications +global: + scrape_interval: 15s # By default, scrape targets every 15 seconds. + evaluation_interval: 15s # By default, scrape targets every 15 seconds. + # scrape_timeout is set to the global default (10s). + + # Attach these labels to any time series or alerts when communicating with + # external systems (federation, remote storage, Alertmanager). + external_labels: + monitor: 'jhipster' + +# A scrape configuration containing exactly one endpoint to scrape: +# Here it's Prometheus itself. +scrape_configs: + # The job name is added as a label `job=` to any timeseries scraped from this config. + - job_name: 'prometheus' + + # Override the global default and scrape targets from this job every 5 seconds. + scrape_interval: 5s + + # scheme defaults to 'http'. + metrics_path: /management/prometheus + static_configs: + - targets: + # On MacOS, replace localhost by host.docker.internal + - localhost:8080 diff --git a/jhipster-5/bookstore-monolith/src/main/docker/sonar.yml b/jhipster-6/bookstore-monolith/src/main/docker/sonar.yml similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/docker/sonar.yml rename to jhipster-6/bookstore-monolith/src/main/docker/sonar.yml diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/ApplicationWebXml.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/ApplicationWebXml.java similarity index 89% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/ApplicationWebXml.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/ApplicationWebXml.java index ca65727e77be..32f28a8e9e41 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/ApplicationWebXml.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/ApplicationWebXml.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5; +package com.baeldung.jhipster6; -import com.baeldung.jhipster5.config.DefaultProfileUtil; +import com.baeldung.jhipster6.config.DefaultProfileUtil; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/BookstoreApp.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/BookstoreApp.java similarity index 96% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/BookstoreApp.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/BookstoreApp.java index e7ca925228e5..278efb9270ac 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/BookstoreApp.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/BookstoreApp.java @@ -1,7 +1,7 @@ -package com.baeldung.jhipster5; +package com.baeldung.jhipster6; -import com.baeldung.jhipster5.config.ApplicationProperties; -import com.baeldung.jhipster5.config.DefaultProfileUtil; +import com.baeldung.jhipster6.config.ApplicationProperties; +import com.baeldung.jhipster6.config.DefaultProfileUtil; import io.github.jhipster.config.JHipsterConstants; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/aop/logging/LoggingAspect.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/aop/logging/LoggingAspect.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/aop/logging/LoggingAspect.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/aop/logging/LoggingAspect.java index 037963706158..1e5a47c12aba 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/aop/logging/LoggingAspect.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/aop/logging/LoggingAspect.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.aop.logging; +package com.baeldung.jhipster6.aop.logging; import io.github.jhipster.config.JHipsterConstants; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/ApplicationProperties.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/ApplicationProperties.java similarity index 90% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/ApplicationProperties.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/ApplicationProperties.java index 4ca3e9bd85d7..e9bf8bd1a8ec 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/ApplicationProperties.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/ApplicationProperties.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/AsyncConfiguration.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/AsyncConfiguration.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/AsyncConfiguration.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/AsyncConfiguration.java index 414fe152bf33..a24540217562 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/AsyncConfiguration.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/AsyncConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor; import io.github.jhipster.config.JHipsterProperties; @@ -46,7 +46,7 @@ public Executor getAsyncExecutor() { public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } - + @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(scheduledTaskExecutor()); diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/CloudDatabaseConfiguration.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/CloudDatabaseConfiguration.java similarity index 95% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/CloudDatabaseConfiguration.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/CloudDatabaseConfiguration.java index 887a1bae8940..3d57db655931 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/CloudDatabaseConfiguration.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/CloudDatabaseConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import io.github.jhipster.config.JHipsterConstants; @@ -16,7 +16,7 @@ public class CloudDatabaseConfiguration extends AbstractCloudConfig { private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class); - + private static final String CLOUD_CONFIGURATION_HIKARI_PREFIX = "spring.datasource.hikari"; @Bean diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/Constants.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/Constants.java similarity index 89% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/Constants.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/Constants.java index dd8f717f98f2..b5d6eba051c8 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/Constants.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/Constants.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; /** * Application constants. @@ -11,7 +11,7 @@ public final class Constants { public static final String SYSTEM_ACCOUNT = "system"; public static final String ANONYMOUS_USER = "anonymoususer"; public static final String DEFAULT_LANGUAGE = "en"; - + private Constants() { } } diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/DatabaseConfiguration.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/DatabaseConfiguration.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/DatabaseConfiguration.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/DatabaseConfiguration.java index 007b1d6431f2..2aa8ae2e82db 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/DatabaseConfiguration.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/DatabaseConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.h2.H2ConfigurationHelper; @@ -42,7 +42,7 @@ public Object h2TCPServer() throws SQLException { log.debug("H2 database is available on port {}", port); return H2ConfigurationHelper.createServer(port); } - + private String getValidPortForH2() { int port = Integer.parseInt(env.getProperty("server.port")); if (port < 10000) { diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/DateTimeFormatConfiguration.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/DateTimeFormatConfiguration.java similarity index 94% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/DateTimeFormatConfiguration.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/DateTimeFormatConfiguration.java index 4415ce0b1ea6..eeb4b55491b2 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/DateTimeFormatConfiguration.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/DateTimeFormatConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/DefaultProfileUtil.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/DefaultProfileUtil.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/DefaultProfileUtil.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/DefaultProfileUtil.java index 2cfe16a1ae71..02b3ce9db0aa 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/DefaultProfileUtil.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/DefaultProfileUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import io.github.jhipster.config.JHipsterConstants; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/JacksonConfiguration.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/JacksonConfiguration.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/JacksonConfiguration.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/JacksonConfiguration.java index 119cd5f0c6b7..68fb92ef2e59 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/JacksonConfiguration.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/JacksonConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/LiquibaseConfiguration.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/LiquibaseConfiguration.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/LiquibaseConfiguration.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/LiquibaseConfiguration.java index 4b2a7b1e66e2..2f82a1f447ab 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/LiquibaseConfiguration.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/LiquibaseConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import javax.sql.DataSource; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/LocaleConfiguration.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/LocaleConfiguration.java similarity index 96% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/LocaleConfiguration.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/LocaleConfiguration.java index 256c6b77b962..d73198e5bb2f 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/LocaleConfiguration.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/LocaleConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import io.github.jhipster.config.locale.AngularCookieLocaleResolver; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/LoggingAspectConfiguration.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/LoggingAspectConfiguration.java similarity index 81% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/LoggingAspectConfiguration.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/LoggingAspectConfiguration.java index 25d7ba379267..1638234a8975 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/LoggingAspectConfiguration.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/LoggingAspectConfiguration.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; -import com.baeldung.jhipster5.aop.logging.LoggingAspect; +import com.baeldung.jhipster6.aop.logging.LoggingAspect; import io.github.jhipster.config.JHipsterConstants; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/LoggingConfiguration.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/LoggingConfiguration.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/LoggingConfiguration.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/LoggingConfiguration.java index 9402a1bc36d0..893a16876f41 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/LoggingConfiguration.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/LoggingConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import java.net.InetSocketAddress; import java.util.Iterator; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/SecurityConfiguration.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/SecurityConfiguration.java similarity index 94% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/SecurityConfiguration.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/SecurityConfiguration.java index f07944271e88..f42ba55c206f 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/SecurityConfiguration.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/SecurityConfiguration.java @@ -1,7 +1,10 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; -import com.baeldung.jhipster5.security.*; -import com.baeldung.jhipster5.security.jwt.*; +import com.baeldung.jhipster6.security.*; +import com.baeldung.jhipster6.security.jwt.*; +import com.baeldung.jhipster6.security.AuthoritiesConstants; +import com.baeldung.jhipster6.security.jwt.JWTConfigurer; +import com.baeldung.jhipster6.security.jwt.TokenProvider; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.context.annotation.Bean; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/WebConfigurer.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/WebConfigurer.java similarity index 79% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/WebConfigurer.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/WebConfigurer.java index 26cfc9248784..8bed192c9f27 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/WebConfigurer.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/WebConfigurer.java @@ -1,20 +1,18 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; -import io.github.jhipster.config.h2.H2ConfigurationHelper; import io.github.jhipster.web.filter.CachingHttpHeadersFilter; -import io.undertow.UndertowOptions; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.boot.web.server.*; import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; import org.springframework.http.MediaType; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @@ -42,7 +40,6 @@ public class WebConfigurer implements ServletContextInitializer, WebServerFactor private final JHipsterProperties jHipsterProperties; public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) { - this.env = env; this.jHipsterProperties = jHipsterProperties; } @@ -53,12 +50,9 @@ public void onStartup(ServletContext servletContext) throws ServletException { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); - if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { + if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_PRODUCTION))) { initCachingHttpHeadersFilter(servletContext, disps); } - if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { - initH2Console(servletContext); - } log.info("Web application fully configured"); } @@ -70,20 +64,6 @@ public void customize(WebServerFactory server) { setMimeMappings(server); // When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets. setLocationForStaticAssets(server); - - /* - * Enable HTTP/2 for Undertow - https://twitter.com/ankinson/status/829256167700492288 - * HTTP/2 requires HTTPS, so HTTP requests will fallback to HTTP/1.1. - * See the JHipsterProperties class and your application-*.yml configuration files - * for more information. - */ - if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && - server instanceof UndertowServletWebServerFactory) { - - ((UndertowServletWebServerFactory) server) - .addBuilderCustomizers(builder -> - builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); - } } private void setMimeMappings(WebServerFactory server) { @@ -103,7 +83,7 @@ private void setLocationForStaticAssets(WebServerFactory server) { ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server; File root; String prefixPath = resolvePathPrefix(); - root = new File(prefixPath + "target/www/"); + root = new File(prefixPath + "target/classes/static/"); if (root.exists() && root.isDirectory()) { servletWebServer.setDocumentRoot(root); } @@ -134,7 +114,7 @@ private String resolvePathPrefix() { * Initializes the caching HTTP Headers Filter. */ private void initCachingHttpHeadersFilter(ServletContext servletContext, - EnumSet disps) { + EnumSet disps) { log.debug("Registering Caching HTTP Headers Filter"); FilterRegistration.Dynamic cachingHttpHeadersFilter = servletContext.addFilter("cachingHttpHeadersFilter", @@ -159,12 +139,4 @@ public CorsFilter corsFilter() { return new CorsFilter(source); } - /** - * Initializes H2 console. - */ - private void initH2Console(ServletContext servletContext) { - log.debug("Initialize H2 console"); - H2ConfigurationHelper.initH2Console(servletContext); - } - } diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/audit/AuditEventConverter.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/audit/AuditEventConverter.java similarity index 96% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/audit/AuditEventConverter.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/audit/AuditEventConverter.java index 6dd87bb82da9..fee87ffb96ec 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/audit/AuditEventConverter.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/audit/AuditEventConverter.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.config.audit; +package com.baeldung.jhipster6.config.audit; -import com.baeldung.jhipster5.domain.PersistentAuditEvent; +import com.baeldung.jhipster6.domain.PersistentAuditEvent; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.security.web.authentication.WebAuthenticationDetails; diff --git a/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/audit/package-info.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/audit/package-info.java new file mode 100644 index 000000000000..ce7911db40d1 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/audit/package-info.java @@ -0,0 +1,4 @@ +/** + * Audit specific code. + */ +package com.baeldung.jhipster6.config.audit; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/package-info.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/package-info.java similarity index 55% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/package-info.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/package-info.java index 868155ce9fcc..2f6261950af6 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/package-info.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/config/package-info.java @@ -1,4 +1,4 @@ /** * Spring Framework configuration files. */ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/AbstractAuditingEntity.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/AbstractAuditingEntity.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/AbstractAuditingEntity.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/AbstractAuditingEntity.java index 861674ccc9fc..b3881af03b70 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/AbstractAuditingEntity.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/AbstractAuditingEntity.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.domain; +package com.baeldung.jhipster6.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.envers.Audited; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/Authority.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/Authority.java similarity index 96% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/Authority.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/Authority.java index fbd4596fc77e..81d2b930cbf3 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/Authority.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/Authority.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.domain; +package com.baeldung.jhipster6.domain; import javax.persistence.Entity; import javax.persistence.Id; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/Book.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/Book.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/Book.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/Book.java index 16771d9e0926..14c5ec33961d 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/Book.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/Book.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.domain; +package com.baeldung.jhipster6.domain; @@ -17,7 +17,7 @@ public class Book implements Serializable { private static final long serialVersionUID = 1L; - + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/PersistentAuditEvent.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/PersistentAuditEvent.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/PersistentAuditEvent.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/PersistentAuditEvent.java index 15e2eeda5a37..f953eeded94c 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/PersistentAuditEvent.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/PersistentAuditEvent.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.domain; +package com.baeldung.jhipster6.domain; import javax.persistence.*; import javax.validation.constraints.NotNull; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/User.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/User.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/User.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/User.java index ff12d1ca9ced..d1ff6c33fabc 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/User.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/User.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.domain; +package com.baeldung.jhipster6.domain; -import com.baeldung.jhipster5.config.Constants; +import com.baeldung.jhipster6.config.Constants; import com.fasterxml.jackson.annotation.JsonIgnore; import org.apache.commons.lang3.StringUtils; diff --git a/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/package-info.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/package-info.java new file mode 100644 index 000000000000..9063a204d520 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/domain/package-info.java @@ -0,0 +1,4 @@ +/** + * JPA domain objects. + */ +package com.baeldung.jhipster6.domain; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/AuthorityRepository.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/AuthorityRepository.java similarity index 69% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/AuthorityRepository.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/AuthorityRepository.java index 310735eb5754..335631195d82 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/AuthorityRepository.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/AuthorityRepository.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.repository; +package com.baeldung.jhipster6.repository; -import com.baeldung.jhipster5.domain.Authority; +import com.baeldung.jhipster6.domain.Authority; import org.springframework.data.jpa.repository.JpaRepository; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/BookRepository.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/BookRepository.java similarity index 75% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/BookRepository.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/BookRepository.java index ebd3117e655d..0863d1b89b1b 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/BookRepository.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/BookRepository.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.repository; +package com.baeldung.jhipster6.repository; -import com.baeldung.jhipster5.domain.Book; +import com.baeldung.jhipster6.domain.Book; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/CustomAuditEventRepository.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/CustomAuditEventRepository.java similarity index 94% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/CustomAuditEventRepository.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/CustomAuditEventRepository.java index faa788ff5f35..4e17cfff2b85 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/CustomAuditEventRepository.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/CustomAuditEventRepository.java @@ -1,8 +1,8 @@ -package com.baeldung.jhipster5.repository; +package com.baeldung.jhipster6.repository; -import com.baeldung.jhipster5.config.Constants; -import com.baeldung.jhipster5.config.audit.AuditEventConverter; -import com.baeldung.jhipster5.domain.PersistentAuditEvent; +import com.baeldung.jhipster6.config.Constants; +import com.baeldung.jhipster6.config.audit.AuditEventConverter; +import com.baeldung.jhipster6.domain.PersistentAuditEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/PersistenceAuditEventRepository.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/PersistenceAuditEventRepository.java similarity index 89% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/PersistenceAuditEventRepository.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/PersistenceAuditEventRepository.java index 2eb6f3b84780..ca0025321e26 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/PersistenceAuditEventRepository.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/PersistenceAuditEventRepository.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.repository; +package com.baeldung.jhipster6.repository; -import com.baeldung.jhipster5.domain.PersistentAuditEvent; +import com.baeldung.jhipster6.domain.PersistentAuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/UserRepository.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/UserRepository.java similarity index 93% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/UserRepository.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/UserRepository.java index 42a5588b223c..27fd5fc359cb 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/UserRepository.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/UserRepository.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.repository; +package com.baeldung.jhipster6.repository; -import com.baeldung.jhipster5.domain.User; +import com.baeldung.jhipster6.domain.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/package-info.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/package-info.java new file mode 100644 index 000000000000..949ee586b74b --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/repository/package-info.java @@ -0,0 +1,4 @@ +/** + * Spring Data JPA repositories. + */ +package com.baeldung.jhipster6.repository; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/AuthoritiesConstants.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/AuthoritiesConstants.java similarity index 88% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/AuthoritiesConstants.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/AuthoritiesConstants.java index 6ecf44394f80..3f1709a6d928 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/AuthoritiesConstants.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/AuthoritiesConstants.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.security; +package com.baeldung.jhipster6.security; /** * Constants for Spring Security authorities. diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/CustomAuthenticationManager.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/CustomAuthenticationManager.java similarity index 93% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/CustomAuthenticationManager.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/CustomAuthenticationManager.java index 0a7dd66b2422..092adf1b06db 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/CustomAuthenticationManager.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/CustomAuthenticationManager.java @@ -1,10 +1,10 @@ -package com.baeldung.jhipster5.security; +package com.baeldung.jhipster6.security; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.security.dto.LoginRequest; -import com.baeldung.jhipster5.security.dto.LoginResponse; -import com.baeldung.jhipster5.service.UserService; -import com.baeldung.jhipster5.service.dto.UserDTO; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.security.dto.LoginRequest; +import com.baeldung.jhipster6.security.dto.LoginResponse; +import com.baeldung.jhipster6.service.UserService; +import com.baeldung.jhipster6.service.dto.UserDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/DomainUserDetailsService.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/DomainUserDetailsService.java similarity index 94% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/DomainUserDetailsService.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/DomainUserDetailsService.java index d0014096df29..3102604ee425 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/DomainUserDetailsService.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/DomainUserDetailsService.java @@ -1,7 +1,8 @@ -package com.baeldung.jhipster5.security; +package com.baeldung.jhipster6.security; + +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.UserRepository; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.UserRepository; import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/SecurityUtils.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/SecurityUtils.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/SecurityUtils.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/SecurityUtils.java index 462bb8abc90e..a4a1982b3c7b 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/SecurityUtils.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/SecurityUtils.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.security; +package com.baeldung.jhipster6.security; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/SpringSecurityAuditorAware.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/SpringSecurityAuditorAware.java similarity index 83% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/SpringSecurityAuditorAware.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/SpringSecurityAuditorAware.java index c1d6405ae391..aff636c13c01 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/SpringSecurityAuditorAware.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/SpringSecurityAuditorAware.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.security; +package com.baeldung.jhipster6.security; -import com.baeldung.jhipster5.config.Constants; +import com.baeldung.jhipster6.config.Constants; import java.util.Optional; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/UserNotActivatedException.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/UserNotActivatedException.java similarity index 92% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/UserNotActivatedException.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/UserNotActivatedException.java index 4b2d91983c1f..a1f71f5408ae 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/UserNotActivatedException.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/UserNotActivatedException.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.security; +package com.baeldung.jhipster6.security; import org.springframework.security.core.AuthenticationException; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/dto/LoginRequest.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/dto/LoginRequest.java similarity index 91% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/dto/LoginRequest.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/dto/LoginRequest.java index f45c23fa39b9..1de26385771e 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/dto/LoginRequest.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/dto/LoginRequest.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.security.dto; +package com.baeldung.jhipster6.security.dto; /** * Simple DTO representing a login request to a remote service. diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/dto/LoginResponse.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/dto/LoginResponse.java similarity index 95% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/dto/LoginResponse.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/dto/LoginResponse.java index ad1fe37a2f18..6063180569e0 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/dto/LoginResponse.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/dto/LoginResponse.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.security.dto; +package com.baeldung.jhipster6.security.dto; /** * Simple DTO representing the response of logging in using a remote service. diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/jwt/JWTConfigurer.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/jwt/JWTConfigurer.java similarity index 94% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/jwt/JWTConfigurer.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/jwt/JWTConfigurer.java index 944255e37dd4..570f6c8d9d21 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/jwt/JWTConfigurer.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/jwt/JWTConfigurer.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.security.jwt; +package com.baeldung.jhipster6.security.jwt; import org.springframework.security.config.annotation.SecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.builders.HttpSecurity; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/jwt/JWTFilter.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/jwt/JWTFilter.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/jwt/JWTFilter.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/jwt/JWTFilter.java index cf1060282c3a..4e921a2f6edc 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/jwt/JWTFilter.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/jwt/JWTFilter.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.security.jwt; +package com.baeldung.jhipster6.security.jwt; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/jwt/TokenProvider.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/jwt/TokenProvider.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/jwt/TokenProvider.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/jwt/TokenProvider.java index 248d45e05088..20f46c06e934 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/jwt/TokenProvider.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/jwt/TokenProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.security.jwt; +package com.baeldung.jhipster6.security.jwt; import java.nio.charset.StandardCharsets; import java.security.Key; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/package-info.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/package-info.java similarity index 50% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/package-info.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/package-info.java index 4759050c564f..3fc05c27e735 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/package-info.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/security/package-info.java @@ -1,4 +1,4 @@ /** * Spring Security configuration. */ -package com.baeldung.jhipster5.security; +package com.baeldung.jhipster6.security; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/AuditEventService.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/AuditEventService.java similarity index 90% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/AuditEventService.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/AuditEventService.java index 852eb951c91b..4d008e096e56 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/AuditEventService.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/AuditEventService.java @@ -1,7 +1,8 @@ -package com.baeldung.jhipster5.service; +package com.baeldung.jhipster6.service; + +import com.baeldung.jhipster6.config.audit.AuditEventConverter; +import com.baeldung.jhipster6.repository.PersistenceAuditEventRepository; -import com.baeldung.jhipster5.config.audit.AuditEventConverter; -import com.baeldung.jhipster5.repository.PersistenceAuditEventRepository; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/BookService.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/BookService.java similarity index 91% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/BookService.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/BookService.java index 6422d1a4249f..00fe8475278f 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/BookService.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/BookService.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.service; +package com.baeldung.jhipster6.service; -import com.baeldung.jhipster5.service.dto.BookDTO; +import com.baeldung.jhipster6.service.dto.BookDTO; import java.util.List; import java.util.Optional; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/MailService.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/MailService.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/MailService.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/MailService.java index b15a7faff29f..807cf8b5d6b7 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/MailService.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/MailService.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.service; +package com.baeldung.jhipster6.service; -import com.baeldung.jhipster5.domain.User; +import com.baeldung.jhipster6.domain.User; import io.github.jhipster.config.JHipsterProperties; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/UserService.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/UserService.java similarity index 92% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/UserService.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/UserService.java index 82d028f3ca80..9c4333207086 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/UserService.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/UserService.java @@ -1,15 +1,18 @@ -package com.baeldung.jhipster5.service; +package com.baeldung.jhipster6.service; -import com.baeldung.jhipster5.config.Constants; -import com.baeldung.jhipster5.domain.Authority; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.AuthorityRepository; -import com.baeldung.jhipster5.repository.UserRepository; -import com.baeldung.jhipster5.security.AuthoritiesConstants; -import com.baeldung.jhipster5.security.SecurityUtils; -import com.baeldung.jhipster5.service.dto.UserDTO; -import com.baeldung.jhipster5.service.util.RandomUtil; -import com.baeldung.jhipster5.web.rest.errors.*; +import com.baeldung.jhipster6.config.Constants; +import com.baeldung.jhipster6.domain.Authority; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.AuthorityRepository; +import com.baeldung.jhipster6.repository.UserRepository; +import com.baeldung.jhipster6.security.AuthoritiesConstants; +import com.baeldung.jhipster6.security.SecurityUtils; +import com.baeldung.jhipster6.service.dto.UserDTO; +import com.baeldung.jhipster6.service.util.RandomUtil; +import com.baeldung.jhipster6.web.rest.errors.*; +import com.baeldung.jhipster6.web.rest.errors.EmailAlreadyUsedException; +import com.baeldung.jhipster6.web.rest.errors.InvalidPasswordException; +import com.baeldung.jhipster6.web.rest.errors.LoginAlreadyUsedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/BookDTO.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/dto/BookDTO.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/BookDTO.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/dto/BookDTO.java index 5aa550e9893c..6334af6c21a3 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/BookDTO.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/dto/BookDTO.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.service.dto; +package com.baeldung.jhipster6.service.dto; import java.time.LocalDate; import javax.validation.constraints.*; import java.io.Serializable; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/PasswordChangeDTO.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/dto/PasswordChangeDTO.java similarity index 94% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/PasswordChangeDTO.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/dto/PasswordChangeDTO.java index 0711c97f446e..1439b6e58d7a 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/PasswordChangeDTO.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/dto/PasswordChangeDTO.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.service.dto; +package com.baeldung.jhipster6.service.dto; /** * A DTO representing a password change required data - current and new password. diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/UserDTO.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/dto/UserDTO.java similarity index 96% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/UserDTO.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/dto/UserDTO.java index 9142b3825ed8..2dd38f9c0fc2 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/UserDTO.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/dto/UserDTO.java @@ -1,9 +1,9 @@ -package com.baeldung.jhipster5.service.dto; +package com.baeldung.jhipster6.service.dto; -import com.baeldung.jhipster5.config.Constants; +import com.baeldung.jhipster6.config.Constants; -import com.baeldung.jhipster5.domain.Authority; -import com.baeldung.jhipster5.domain.User; +import com.baeldung.jhipster6.domain.Authority; +import com.baeldung.jhipster6.domain.User; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; diff --git a/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/dto/package-info.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/dto/package-info.java new file mode 100644 index 000000000000..c5363205842a --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/dto/package-info.java @@ -0,0 +1,4 @@ +/** + * Data Transfer Objects. + */ +package com.baeldung.jhipster6.service.dto; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/impl/BookServiceImpl.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/impl/BookServiceImpl.java similarity index 88% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/impl/BookServiceImpl.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/impl/BookServiceImpl.java index 23cd59584c00..0012489c5eca 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/impl/BookServiceImpl.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/impl/BookServiceImpl.java @@ -1,11 +1,12 @@ -package com.baeldung.jhipster5.service.impl; +package com.baeldung.jhipster6.service.impl; + +import com.baeldung.jhipster6.service.BookService; +import com.baeldung.jhipster6.domain.Book; +import com.baeldung.jhipster6.repository.BookRepository; +import com.baeldung.jhipster6.service.dto.BookDTO; +import com.baeldung.jhipster6.service.mapper.BookMapper; +import com.baeldung.jhipster6.web.rest.errors.BadRequestAlertException; -import com.baeldung.jhipster5.service.BookService; -import com.baeldung.jhipster5.domain.Book; -import com.baeldung.jhipster5.repository.BookRepository; -import com.baeldung.jhipster5.service.dto.BookDTO; -import com.baeldung.jhipster5.service.mapper.BookMapper; -import com.baeldung.jhipster5.web.rest.errors.BadRequestAlertException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/mapper/BookMapper.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/mapper/BookMapper.java similarity index 67% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/mapper/BookMapper.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/mapper/BookMapper.java index cd24c7088e9f..64350fb4ed7f 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/mapper/BookMapper.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/mapper/BookMapper.java @@ -1,7 +1,8 @@ -package com.baeldung.jhipster5.service.mapper; +package com.baeldung.jhipster6.service.mapper; -import com.baeldung.jhipster5.domain.*; -import com.baeldung.jhipster5.service.dto.BookDTO; +import com.baeldung.jhipster6.domain.*; +import com.baeldung.jhipster6.service.dto.BookDTO; +import com.baeldung.jhipster6.domain.Book; import org.mapstruct.*; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/mapper/EntityMapper.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/mapper/EntityMapper.java similarity index 87% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/mapper/EntityMapper.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/mapper/EntityMapper.java index 68af78179dc4..6ca8d894801c 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/mapper/EntityMapper.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/mapper/EntityMapper.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.service.mapper; +package com.baeldung.jhipster6.service.mapper; import java.util.List; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/mapper/UserMapper.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/mapper/UserMapper.java similarity index 92% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/mapper/UserMapper.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/mapper/UserMapper.java index 485c03813e85..8b2b4cfba048 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/mapper/UserMapper.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/mapper/UserMapper.java @@ -1,8 +1,8 @@ -package com.baeldung.jhipster5.service.mapper; +package com.baeldung.jhipster6.service.mapper; -import com.baeldung.jhipster5.domain.Authority; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.service.dto.UserDTO; +import com.baeldung.jhipster6.domain.Authority; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.service.dto.UserDTO; import org.springframework.stereotype.Service; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/mapper/package-info.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/mapper/package-info.java similarity index 63% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/mapper/package-info.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/mapper/package-info.java index 7d402321e7d5..6ce6ec42fbdf 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/mapper/package-info.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/mapper/package-info.java @@ -1,4 +1,4 @@ /** * MapStruct mappers for mapping domain objects and Data Transfer Objects. */ -package com.baeldung.jhipster5.service.mapper; +package com.baeldung.jhipster6.service.mapper; diff --git a/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/package-info.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/package-info.java new file mode 100644 index 000000000000..4f9584c45e85 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/package-info.java @@ -0,0 +1,4 @@ +/** + * Service layer beans. + */ +package com.baeldung.jhipster6.service; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/util/RandomUtil.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/util/RandomUtil.java similarity index 94% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/util/RandomUtil.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/util/RandomUtil.java index 97e4d9c6728c..74b8b178c27a 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/util/RandomUtil.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/service/util/RandomUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.service.util; +package com.baeldung.jhipster6.service.util; import org.apache.commons.lang3.RandomStringUtils; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/AccountResource.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/AccountResource.java similarity index 87% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/AccountResource.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/AccountResource.java index 2109e93999db..3603df148bd6 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/AccountResource.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/AccountResource.java @@ -1,16 +1,21 @@ -package com.baeldung.jhipster5.web.rest; - - -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.UserRepository; -import com.baeldung.jhipster5.security.SecurityUtils; -import com.baeldung.jhipster5.service.MailService; -import com.baeldung.jhipster5.service.UserService; -import com.baeldung.jhipster5.service.dto.PasswordChangeDTO; -import com.baeldung.jhipster5.service.dto.UserDTO; -import com.baeldung.jhipster5.web.rest.errors.*; -import com.baeldung.jhipster5.web.rest.vm.KeyAndPasswordVM; -import com.baeldung.jhipster5.web.rest.vm.ManagedUserVM; +package com.baeldung.jhipster6.web.rest; + + +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.UserRepository; +import com.baeldung.jhipster6.security.SecurityUtils; +import com.baeldung.jhipster6.service.MailService; +import com.baeldung.jhipster6.service.UserService; +import com.baeldung.jhipster6.service.dto.PasswordChangeDTO; +import com.baeldung.jhipster6.service.dto.UserDTO; +import com.baeldung.jhipster6.web.rest.errors.*; +import com.baeldung.jhipster6.web.rest.errors.EmailAlreadyUsedException; +import com.baeldung.jhipster6.web.rest.errors.EmailNotFoundException; +import com.baeldung.jhipster6.web.rest.errors.InternalServerErrorException; +import com.baeldung.jhipster6.web.rest.errors.InvalidPasswordException; +import com.baeldung.jhipster6.web.rest.errors.LoginAlreadyUsedException; +import com.baeldung.jhipster6.web.rest.vm.KeyAndPasswordVM; +import com.baeldung.jhipster6.web.rest.vm.ManagedUserVM; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/AuditResource.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/AuditResource.java similarity index 94% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/AuditResource.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/AuditResource.java index d0182d5d9da5..ebcdc42f64eb 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/AuditResource.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/AuditResource.java @@ -1,7 +1,7 @@ -package com.baeldung.jhipster5.web.rest; +package com.baeldung.jhipster6.web.rest; -import com.baeldung.jhipster5.service.AuditEventService; -import com.baeldung.jhipster5.web.rest.util.PaginationUtil; +import com.baeldung.jhipster6.service.AuditEventService; +import com.baeldung.jhipster6.web.rest.util.PaginationUtil; import io.github.jhipster.web.util.ResponseUtil; import org.springframework.boot.actuate.audit.AuditEvent; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/BookResource.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/BookResource.java similarity index 94% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/BookResource.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/BookResource.java index 0360ea05ed6b..584216b51d3b 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/BookResource.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/BookResource.java @@ -1,8 +1,8 @@ -package com.baeldung.jhipster5.web.rest; -import com.baeldung.jhipster5.service.BookService; -import com.baeldung.jhipster5.web.rest.errors.BadRequestAlertException; -import com.baeldung.jhipster5.web.rest.util.HeaderUtil; -import com.baeldung.jhipster5.service.dto.BookDTO; +package com.baeldung.jhipster6.web.rest; +import com.baeldung.jhipster6.service.BookService; +import com.baeldung.jhipster6.web.rest.errors.BadRequestAlertException; +import com.baeldung.jhipster6.web.rest.util.HeaderUtil; +import com.baeldung.jhipster6.service.dto.BookDTO; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/ClientForwardController.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/ClientForwardController.java new file mode 100644 index 000000000000..a524d90fc087 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/ClientForwardController.java @@ -0,0 +1,17 @@ +package com.baeldung.jhipster6.web.rest; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class ClientForwardController { + + /** + * Forwards any unmapped paths (except those containing a period) to the client {@code index.html}. + * @return forward to client {@code index.html}. + */ + @GetMapping(value = "/**/{path:[^\\.]*}") + public String forward() { + return "forward:/"; + } +} diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/LogsResource.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/LogsResource.java similarity index 91% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/LogsResource.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/LogsResource.java index f35b5f2d5c25..76d71d23d01b 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/LogsResource.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/LogsResource.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.web.rest; +package com.baeldung.jhipster6.web.rest; -import com.baeldung.jhipster5.web.rest.vm.LoggerVM; +import com.baeldung.jhipster6.web.rest.vm.LoggerVM; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/UserJWTController.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/UserJWTController.java similarity index 91% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/UserJWTController.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/UserJWTController.java index aeea5870892a..1bb647d2ef5e 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/UserJWTController.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/UserJWTController.java @@ -1,8 +1,8 @@ -package com.baeldung.jhipster5.web.rest; +package com.baeldung.jhipster6.web.rest; -import com.baeldung.jhipster5.security.jwt.JWTFilter; -import com.baeldung.jhipster5.security.jwt.TokenProvider; -import com.baeldung.jhipster5.web.rest.vm.LoginVM; +import com.baeldung.jhipster6.security.jwt.JWTFilter; +import com.baeldung.jhipster6.security.jwt.TokenProvider; +import com.baeldung.jhipster6.web.rest.vm.LoginVM; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/UserResource.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/UserResource.java similarity index 91% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/UserResource.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/UserResource.java index a95acf6759a6..36fa8f319cf9 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/UserResource.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/UserResource.java @@ -1,17 +1,17 @@ -package com.baeldung.jhipster5.web.rest; - -import com.baeldung.jhipster5.config.Constants; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.UserRepository; -import com.baeldung.jhipster5.security.AuthoritiesConstants; -import com.baeldung.jhipster5.service.MailService; -import com.baeldung.jhipster5.service.UserService; -import com.baeldung.jhipster5.service.dto.UserDTO; -import com.baeldung.jhipster5.web.rest.errors.BadRequestAlertException; -import com.baeldung.jhipster5.web.rest.errors.EmailAlreadyUsedException; -import com.baeldung.jhipster5.web.rest.errors.LoginAlreadyUsedException; -import com.baeldung.jhipster5.web.rest.util.HeaderUtil; -import com.baeldung.jhipster5.web.rest.util.PaginationUtil; +package com.baeldung.jhipster6.web.rest; + +import com.baeldung.jhipster6.config.Constants; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.UserRepository; +import com.baeldung.jhipster6.security.AuthoritiesConstants; +import com.baeldung.jhipster6.service.MailService; +import com.baeldung.jhipster6.service.UserService; +import com.baeldung.jhipster6.service.dto.UserDTO; +import com.baeldung.jhipster6.web.rest.errors.BadRequestAlertException; +import com.baeldung.jhipster6.web.rest.errors.EmailAlreadyUsedException; +import com.baeldung.jhipster6.web.rest.errors.LoginAlreadyUsedException; +import com.baeldung.jhipster6.web.rest.util.HeaderUtil; +import com.baeldung.jhipster6.web.rest.util.PaginationUtil; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/BadRequestAlertException.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/BadRequestAlertException.java similarity index 96% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/BadRequestAlertException.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/BadRequestAlertException.java index c4c403351a6c..a2e71a28bfbf 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/BadRequestAlertException.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/BadRequestAlertException.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/CustomParameterizedException.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/CustomParameterizedException.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/CustomParameterizedException.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/CustomParameterizedException.java index 8c3df82b8348..31add5c58880 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/CustomParameterizedException.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/CustomParameterizedException.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/EmailAlreadyUsedException.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/EmailAlreadyUsedException.java similarity index 86% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/EmailAlreadyUsedException.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/EmailAlreadyUsedException.java index b3dcc0279ebd..01e358b76c72 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/EmailAlreadyUsedException.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/EmailAlreadyUsedException.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; public class EmailAlreadyUsedException extends BadRequestAlertException { diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/EmailNotFoundException.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/EmailNotFoundException.java similarity index 88% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/EmailNotFoundException.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/EmailNotFoundException.java index b93081cacb13..51a7857f325a 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/EmailNotFoundException.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/EmailNotFoundException.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/ErrorConstants.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/ErrorConstants.java similarity index 96% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/ErrorConstants.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/ErrorConstants.java index 06be9254a922..b6a256dda09e 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/ErrorConstants.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/ErrorConstants.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; import java.net.URI; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslator.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/ExceptionTranslator.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslator.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/ExceptionTranslator.java index 3f7cc6b56520..d9e5697c77cc 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslator.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/ExceptionTranslator.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; -import com.baeldung.jhipster5.web.rest.util.HeaderUtil; +import com.baeldung.jhipster6.web.rest.util.HeaderUtil; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.ResponseEntity; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/FieldErrorVM.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/FieldErrorVM.java similarity index 92% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/FieldErrorVM.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/FieldErrorVM.java index 349f548850ca..7c2504a3fcdc 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/FieldErrorVM.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/FieldErrorVM.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; import java.io.Serializable; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/InternalServerErrorException.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/InternalServerErrorException.java similarity index 90% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/InternalServerErrorException.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/InternalServerErrorException.java index 13e128237b07..844f315bfde2 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/InternalServerErrorException.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/InternalServerErrorException.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/InvalidPasswordException.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/InvalidPasswordException.java similarity index 88% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/InvalidPasswordException.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/InvalidPasswordException.java index 6bb91247ff59..02d4b4da0179 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/InvalidPasswordException.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/InvalidPasswordException.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/LoginAlreadyUsedException.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/LoginAlreadyUsedException.java similarity index 85% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/LoginAlreadyUsedException.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/LoginAlreadyUsedException.java index 987a94193d26..fabd4d153d1b 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/LoginAlreadyUsedException.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/LoginAlreadyUsedException.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; public class LoginAlreadyUsedException extends BadRequestAlertException { diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/package-info.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/package-info.java similarity index 75% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/package-info.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/package-info.java index 7f57af4429c5..b791df1268ae 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/errors/package-info.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/errors/package-info.java @@ -3,4 +3,4 @@ * * More information on https://github.com/zalando/problem-spring-web */ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; diff --git a/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/package-info.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/package-info.java new file mode 100644 index 000000000000..f5d106c277a4 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/package-info.java @@ -0,0 +1,4 @@ +/** + * Spring MVC REST controllers. + */ +package com.baeldung.jhipster6.web.rest; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/util/HeaderUtil.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/util/HeaderUtil.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/util/HeaderUtil.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/util/HeaderUtil.java index 91fdd68261da..8546b979563c 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/util/HeaderUtil.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/util/HeaderUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.util; +package com.baeldung.jhipster6.web.rest.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/util/PaginationUtil.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/util/PaginationUtil.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/util/PaginationUtil.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/util/PaginationUtil.java index 9928dbe17175..7c28d9348609 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/util/PaginationUtil.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/util/PaginationUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.util; +package com.baeldung.jhipster6.web.rest.util; import org.springframework.data.domain.Page; import org.springframework.http.HttpHeaders; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/KeyAndPasswordVM.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/KeyAndPasswordVM.java similarity index 91% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/KeyAndPasswordVM.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/KeyAndPasswordVM.java index 840fa02cfcc6..b2b1f91b0ab7 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/KeyAndPasswordVM.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/KeyAndPasswordVM.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.vm; +package com.baeldung.jhipster6.web.rest.vm; /** * View Model object for storing the user's key and password. diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/LoggerVM.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/LoggerVM.java similarity index 95% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/LoggerVM.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/LoggerVM.java index 952e7df2985b..d7ca167edf8f 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/LoggerVM.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/LoggerVM.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.vm; +package com.baeldung.jhipster6.web.rest.vm; import ch.qos.logback.classic.Logger; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/LoginVM.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/LoginVM.java similarity index 96% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/LoginVM.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/LoginVM.java index 8fc119ab6935..40ede22b3a66 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/LoginVM.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/LoginVM.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.vm; +package com.baeldung.jhipster6.web.rest.vm; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/ManagedUserVM.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/ManagedUserVM.java similarity index 88% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/ManagedUserVM.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/ManagedUserVM.java index 314577c45610..2746ca6de049 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/ManagedUserVM.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/ManagedUserVM.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.web.rest.vm; +package com.baeldung.jhipster6.web.rest.vm; -import com.baeldung.jhipster5.service.dto.UserDTO; +import com.baeldung.jhipster6.service.dto.UserDTO; import javax.validation.constraints.Size; /** diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/package-info.java b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/package-info.java similarity index 57% rename from jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/package-info.java rename to jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/package-info.java index ff587990376b..af0defc392d4 100644 --- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/vm/package-info.java +++ b/jhipster-6/bookstore-monolith/src/main/java/com/baeldung/jhipster6/web/rest/vm/package-info.java @@ -1,4 +1,4 @@ /** * View Models used by Spring MVC REST controllers. */ -package com.baeldung.jhipster5.web.rest.vm; +package com.baeldung.jhipster6.web.rest.vm; diff --git a/jhipster-5/bookstore-monolith/src/main/jib/entrypoint.sh b/jhipster-6/bookstore-monolith/src/main/jib/entrypoint.sh similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/jib/entrypoint.sh rename to jhipster-6/bookstore-monolith/src/main/jib/entrypoint.sh diff --git a/jhipster-5/bookstore-monolith/src/main/resources/.h2.server.properties b/jhipster-6/bookstore-monolith/src/main/resources/.h2.server.properties similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/.h2.server.properties rename to jhipster-6/bookstore-monolith/src/main/resources/.h2.server.properties diff --git a/jhipster-5/bookstore-monolith/src/main/resources/banner.txt b/jhipster-6/bookstore-monolith/src/main/resources/banner.txt similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/banner.txt rename to jhipster-6/bookstore-monolith/src/main/resources/banner.txt diff --git a/jhipster-5/bookstore-monolith/src/main/resources/config/application-dev.yml b/jhipster-6/bookstore-monolith/src/main/resources/config/application-dev.yml similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/config/application-dev.yml rename to jhipster-6/bookstore-monolith/src/main/resources/config/application-dev.yml diff --git a/jhipster-5/bookstore-monolith/src/main/resources/config/application-prod.yml b/jhipster-6/bookstore-monolith/src/main/resources/config/application-prod.yml similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/config/application-prod.yml rename to jhipster-6/bookstore-monolith/src/main/resources/config/application-prod.yml diff --git a/jhipster-5/bookstore-monolith/src/main/resources/config/application-tls.yml b/jhipster-6/bookstore-monolith/src/main/resources/config/application-tls.yml similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/config/application-tls.yml rename to jhipster-6/bookstore-monolith/src/main/resources/config/application-tls.yml diff --git a/jhipster-5/bookstore-monolith/src/main/resources/config/application.yml b/jhipster-6/bookstore-monolith/src/main/resources/config/application.yml similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/config/application.yml rename to jhipster-6/bookstore-monolith/src/main/resources/config/application.yml diff --git a/jhipster-5/bookstore-monolith/src/main/resources/config/liquibase/authorities.csv b/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/authorities.csv similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/config/liquibase/authorities.csv rename to jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/authorities.csv diff --git a/jhipster-5/bookstore-monolith/src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml b/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml rename to jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml diff --git a/jhipster-5/bookstore-monolith/src/main/resources/config/liquibase/changelog/20190319124041_added_entity_Book.xml b/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/changelog/20190319124041_added_entity_Book.xml similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/config/liquibase/changelog/20190319124041_added_entity_Book.xml rename to jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/changelog/20190319124041_added_entity_Book.xml diff --git a/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/data/authority.csv b/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/data/authority.csv new file mode 100644 index 000000000000..af5c6dfa186d --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/data/authority.csv @@ -0,0 +1,3 @@ +name +ROLE_ADMIN +ROLE_USER diff --git a/jhipster-5/bookstore-monolith/src/main/resources/config/liquibase/users.csv b/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/data/user.csv similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/config/liquibase/users.csv rename to jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/data/user.csv diff --git a/jhipster-5/bookstore-monolith/src/main/resources/config/liquibase/users_authorities.csv b/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/data/user_authority.csv similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/config/liquibase/users_authorities.csv rename to jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/data/user_authority.csv diff --git a/jhipster-5/bookstore-monolith/src/main/resources/config/liquibase/master.xml b/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/master.xml similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/config/liquibase/master.xml rename to jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/master.xml diff --git a/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/users.csv b/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/users.csv new file mode 100644 index 000000000000..b25922b69906 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/users.csv @@ -0,0 +1,5 @@ +id;login;password_hash;first_name;last_name;email;image_url;activated;lang_key;created_by;last_modified_by +1;system;$2a$10$mE.qmcV0mFU5NcKh73TZx.z4ueI/.bDWbj0T1BYyqP481kGGarKLG;System;System;system@localhost;;true;en;system;system +2;anonymoususer;$2a$10$j8S5d7Sr7.8VTOYNviDPOeWX8KcYILUVJBsYV83Y5NtECayypx9lO;Anonymous;User;anonymous@localhost;;true;en;system;system +3;admin;$2a$10$gSAhZrxMllrbgj/kkK9UceBPpChGWJA7SYIb1Mqo.n5aNLq1/oRrC;Administrator;Administrator;admin@localhost;;true;en;system;system +4;user;$2a$10$VEjxo0jq2YG9Rbk2HmX9S.k1uZBGYUHdUcid3g/vfiEl7lwWgOH/K;User;User;user@localhost;;true;en;system;system diff --git a/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/users_authorities.csv b/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/users_authorities.csv new file mode 100644 index 000000000000..06c5feeeeace --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/resources/config/liquibase/users_authorities.csv @@ -0,0 +1,6 @@ +user_id;authority_name +1;ROLE_ADMIN +1;ROLE_USER +3;ROLE_ADMIN +3;ROLE_USER +4;ROLE_USER diff --git a/jhipster-5/bookstore-monolith/src/main/resources/config/tls/keystore.p12 b/jhipster-6/bookstore-monolith/src/main/resources/config/tls/keystore.p12 similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/config/tls/keystore.p12 rename to jhipster-6/bookstore-monolith/src/main/resources/config/tls/keystore.p12 diff --git a/jhipster-5/bookstore-monolith/src/main/resources/i18n/messages.properties b/jhipster-6/bookstore-monolith/src/main/resources/i18n/messages.properties similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/i18n/messages.properties rename to jhipster-6/bookstore-monolith/src/main/resources/i18n/messages.properties diff --git a/jhipster-5/bookstore-monolith/src/main/resources/logback-spring.xml b/jhipster-6/bookstore-monolith/src/main/resources/logback-spring.xml similarity index 98% rename from jhipster-5/bookstore-monolith/src/main/resources/logback-spring.xml rename to jhipster-6/bookstore-monolith/src/main/resources/logback-spring.xml index 4aa548af35d1..b0e2d9aa957f 100644 --- a/jhipster-5/bookstore-monolith/src/main/resources/logback-spring.xml +++ b/jhipster-6/bookstore-monolith/src/main/resources/logback-spring.xml @@ -30,9 +30,9 @@ - + - + diff --git a/jhipster-5/bookstore-monolith/src/main/resources/templates/error.html b/jhipster-6/bookstore-monolith/src/main/resources/templates/error.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/templates/error.html rename to jhipster-6/bookstore-monolith/src/main/resources/templates/error.html diff --git a/jhipster-5/bookstore-monolith/src/main/resources/templates/mail/activationEmail.html b/jhipster-6/bookstore-monolith/src/main/resources/templates/mail/activationEmail.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/templates/mail/activationEmail.html rename to jhipster-6/bookstore-monolith/src/main/resources/templates/mail/activationEmail.html diff --git a/jhipster-5/bookstore-monolith/src/main/resources/templates/mail/creationEmail.html b/jhipster-6/bookstore-monolith/src/main/resources/templates/mail/creationEmail.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/templates/mail/creationEmail.html rename to jhipster-6/bookstore-monolith/src/main/resources/templates/mail/creationEmail.html diff --git a/jhipster-5/bookstore-monolith/src/main/resources/templates/mail/passwordResetEmail.html b/jhipster-6/bookstore-monolith/src/main/resources/templates/mail/passwordResetEmail.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/resources/templates/mail/passwordResetEmail.html rename to jhipster-6/bookstore-monolith/src/main/resources/templates/mail/passwordResetEmail.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/404.html b/jhipster-6/bookstore-monolith/src/main/webapp/404.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/404.html rename to jhipster-6/bookstore-monolith/src/main/webapp/404.html diff --git a/jhipster-6/bookstore-monolith/src/main/webapp/WEB-INF/web.xml b/jhipster-6/bookstore-monolith/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 000000000000..f1611b515aed --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,13 @@ + + + + + html + text/html;charset=utf-8 + + + diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/account.module.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/account.module.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/account.module.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/account.module.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/account.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/account.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/account.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/account.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/activate/activate.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/activate/activate.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/activate/activate.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/activate/activate.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/activate/activate.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/activate/activate.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/activate/activate.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/activate/activate.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/activate/activate.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/activate/activate.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/activate/activate.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/activate/activate.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/activate/activate.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/activate/activate.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/activate/activate.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/activate/activate.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/index.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/index.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/index.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/index.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/finish/password-reset-finish.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password-reset/init/password-reset-init.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password/password-strength-bar.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password/password-strength-bar.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password/password-strength-bar.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password/password-strength-bar.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password/password-strength-bar.scss b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password/password-strength-bar.scss similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password/password-strength-bar.scss rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password/password-strength-bar.scss diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password/password.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password/password.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password/password.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password/password.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password/password.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password/password.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password/password.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password/password.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password/password.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password/password.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password/password.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password/password.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/password/password.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/password/password.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/password/password.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/password/password.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/register/register.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/register/register.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/register/register.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/register/register.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/register/register.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/register/register.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/register/register.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/register/register.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/register/register.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/register/register.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/register/register.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/register/register.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/register/register.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/register/register.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/register/register.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/register/register.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/settings/settings.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/settings/settings.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/settings/settings.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/settings/settings.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/settings/settings.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/settings/settings.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/settings/settings.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/settings/settings.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/settings/settings.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/account/settings/settings.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/account/settings/settings.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/account/settings/settings.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/admin.module.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/admin.module.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/admin.module.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/admin.module.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/admin.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/admin.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/admin.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/admin.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/audits/audit-data.model.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/audits/audit-data.model.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/audits/audit-data.model.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/audits/audit-data.model.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/audits/audit.model.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/audits/audit.model.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/audits/audit.model.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/audits/audit.model.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/audits/audits.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/audits/audits.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/audits/audits.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/audits/audits.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/audits/audits.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/audits/audits.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/audits/audits.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/audits/audits.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/audits/audits.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/audits/audits.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/audits/audits.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/audits/audits.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/audits/audits.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/audits/audits.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/audits/audits.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/audits/audits.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/configuration/configuration.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/docs/docs.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/docs/docs.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/docs/docs.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/docs/docs.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/docs/docs.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/docs/docs.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/docs/docs.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/docs/docs.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/docs/docs.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/docs/docs.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/docs/docs.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/docs/docs.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/health/health-modal.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/health/health-modal.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/health/health-modal.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/health/health-modal.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/health/health-modal.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/health/health-modal.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/health/health-modal.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/health/health-modal.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/health/health.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/health/health.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/health/health.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/health/health.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/health/health.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/health/health.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/health/health.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/health/health.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/health/health.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/health/health.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/health/health.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/health/health.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/health/health.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/health/health.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/health/health.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/health/health.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/index.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/index.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/index.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/index.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/logs/log.model.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/logs/log.model.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/logs/log.model.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/logs/log.model.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/logs/logs.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/logs/logs.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/logs/logs.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/logs/logs.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/logs/logs.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/logs/logs.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/logs/logs.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/logs/logs.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/logs/logs.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/logs/logs.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/logs/logs.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/logs/logs.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/logs/logs.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/logs/logs.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/logs/logs.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/logs/logs.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/metrics/metrics.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-delete-dialog.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-delete-dialog.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-delete-dialog.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-delete-dialog.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-delete-dialog.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-delete-dialog.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-delete-dialog.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-delete-dialog.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-detail.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-detail.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-detail.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-detail.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-detail.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-detail.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-detail.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-detail.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-update.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-update.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-update.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-update.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-update.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-update.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-update.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management-update.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/admin/user-management/user-management.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/app-routing.module.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/app-routing.module.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/app-routing.module.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/app-routing.module.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/app.constants.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/app.constants.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/app.constants.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/app.constants.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/app.main.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/app.main.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/app.main.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/app.main.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/app.module.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/app.module.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/app.module.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/app.module.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/blocks/config/prod.config.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/blocks/config/prod.config.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/blocks/config/prod.config.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/blocks/config/prod.config.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/blocks/config/uib-pagination.config.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/blocks/config/uib-pagination.config.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/blocks/config/uib-pagination.config.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/blocks/config/uib-pagination.config.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/blocks/interceptor/auth-expired.interceptor.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/blocks/interceptor/auth-expired.interceptor.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/blocks/interceptor/auth-expired.interceptor.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/blocks/interceptor/auth-expired.interceptor.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/blocks/interceptor/auth.interceptor.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/blocks/interceptor/auth.interceptor.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/blocks/interceptor/auth.interceptor.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/blocks/interceptor/auth.interceptor.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/blocks/interceptor/errorhandler.interceptor.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/blocks/interceptor/errorhandler.interceptor.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/blocks/interceptor/errorhandler.interceptor.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/blocks/interceptor/errorhandler.interceptor.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/blocks/interceptor/notification.interceptor.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/blocks/interceptor/notification.interceptor.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/blocks/interceptor/notification.interceptor.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/blocks/interceptor/notification.interceptor.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/core/auth/account.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/core/auth/account.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/core/auth/account.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/core/auth/account.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/core/auth/auth-jwt.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/core/auth/auth-jwt.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/core/auth/auth-jwt.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/core/auth/auth-jwt.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/core/auth/csrf.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/core/auth/csrf.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/core/auth/csrf.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/core/auth/csrf.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/core/auth/state-storage.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/core/auth/state-storage.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/core/auth/state-storage.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/core/auth/state-storage.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/core/auth/user-route-access-service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/core/auth/user-route-access-service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/core/auth/user-route-access-service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/core/auth/user-route-access-service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/core/core.module.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/core/core.module.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/core/core.module.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/core/core.module.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/core/index.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/core/index.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/core/index.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/core/index.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/core/login/login-modal.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/core/login/login-modal.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/core/login/login-modal.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/core/login/login-modal.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/core/login/login.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/core/login/login.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/core/login/login.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/core/login/login.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/core/user/account.model.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/core/user/account.model.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/core/user/account.model.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/core/user/account.model.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/core/user/user.model.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/core/user/user.model.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/core/user/user.model.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/core/user/user.model.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/core/user/user.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/core/user/user.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/core/user/user.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/core/user/user.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book-delete-dialog.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book-delete-dialog.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book-delete-dialog.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book-delete-dialog.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book-delete-dialog.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book-delete-dialog.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book-delete-dialog.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book-delete-dialog.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book-detail.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book-detail.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book-detail.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book-detail.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book-detail.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book-detail.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book-detail.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book-detail.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book-update.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book-update.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book-update.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book-update.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book-update.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book-update.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book-update.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book-update.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book.module.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book.module.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book.module.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book.module.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/book.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/book.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/index.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/index.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/book/index.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/book/index.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/entities/entity.module.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/entities/entity.module.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/entities/entity.module.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/entities/entity.module.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/home/home.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/home/home.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/home/home.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/home/home.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/home/home.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/home/home.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/home/home.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/home/home.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/home/home.module.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/home/home.module.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/home/home.module.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/home/home.module.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/home/home.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/home/home.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/home/home.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/home/home.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/home/home.scss b/jhipster-6/bookstore-monolith/src/main/webapp/app/home/home.scss similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/home/home.scss rename to jhipster-6/bookstore-monolith/src/main/webapp/app/home/home.scss diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/home/index.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/home/index.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/home/index.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/home/index.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/error/error.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/error/error.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/error/error.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/error/error.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/error/error.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/error/error.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/error/error.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/error/error.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/error/error.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/error/error.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/error/error.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/error/error.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/footer/footer.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/footer/footer.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/footer/footer.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/footer/footer.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/footer/footer.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/footer/footer.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/footer/footer.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/footer/footer.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/index.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/index.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/index.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/index.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/main/main.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/main/main.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/main/main.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/main/main.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/main/main.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/main/main.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/main/main.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/main/main.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.route.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.route.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.route.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.route.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.scss b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.scss similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.scss rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.scss diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/profiles/page-ribbon.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/profiles/page-ribbon.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/profiles/page-ribbon.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/profiles/page-ribbon.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/profiles/page-ribbon.scss b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/profiles/page-ribbon.scss similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/profiles/page-ribbon.scss rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/profiles/page-ribbon.scss diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/profiles/profile-info.model.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/profiles/profile-info.model.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/profiles/profile-info.model.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/profiles/profile-info.model.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/profiles/profile.service.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/profiles/profile.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/profiles/profile.service.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/layouts/profiles/profile.service.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/polyfills.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/polyfills.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/polyfills.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/polyfills.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/alert/alert-error.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/alert/alert-error.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/alert/alert-error.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/alert/alert-error.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/alert/alert.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/alert/alert.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/alert/alert.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/alert/alert.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/auth/has-any-authority.directive.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/auth/has-any-authority.directive.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/auth/has-any-authority.directive.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/auth/has-any-authority.directive.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/constants/error.constants.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/constants/error.constants.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/constants/error.constants.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/constants/error.constants.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/constants/input.constants.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/constants/input.constants.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/constants/input.constants.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/constants/input.constants.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/constants/pagination.constants.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/constants/pagination.constants.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/constants/pagination.constants.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/constants/pagination.constants.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/index.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/index.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/index.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/index.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/login/login.component.html b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/login/login.component.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/login/login.component.html rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/login/login.component.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/login/login.component.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/login/login.component.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/login/login.component.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/login/login.component.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/model/book.model.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/model/book.model.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/model/book.model.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/model/book.model.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/shared-common.module.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/shared-common.module.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/shared-common.module.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/shared-common.module.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/shared-libs.module.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/shared-libs.module.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/shared-libs.module.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/shared-libs.module.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/shared.module.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/shared.module.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/shared.module.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/shared.module.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/util/datepicker-adapter.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/util/datepicker-adapter.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/util/datepicker-adapter.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/util/datepicker-adapter.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/util/request-util.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/shared/util/request-util.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/shared/util/request-util.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/shared/util/request-util.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/vendor.ts b/jhipster-6/bookstore-monolith/src/main/webapp/app/vendor.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/app/vendor.ts rename to jhipster-6/bookstore-monolith/src/main/webapp/app/vendor.ts diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/css/loading.css b/jhipster-6/bookstore-monolith/src/main/webapp/content/css/loading.css similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/css/loading.css rename to jhipster-6/bookstore-monolith/src/main/webapp/content/css/loading.css diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0.svg b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0.svg old mode 100755 new mode 100644 similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0.svg rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0.svg diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-192.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-192.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-192.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-192.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-256.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-256.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-256.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-256.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-384.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-384.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-384.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-384.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-512.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-512.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-512.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_0_head-512.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1.svg b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1.svg old mode 100755 new mode 100644 similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1.svg rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1.svg diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-192.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-192.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-192.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-192.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-256.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-256.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-256.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-256.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-384.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-384.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-384.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-384.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-512.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-512.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-512.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_1_head-512.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2.svg b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2.svg old mode 100755 new mode 100644 similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2.svg rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2.svg diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-192.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-192.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-192.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-192.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-256.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-256.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-256.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-256.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-384.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-384.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-384.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-384.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-512.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-512.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-512.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_2_head-512.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3.svg b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3.svg old mode 100755 new mode 100644 similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3.svg rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3.svg diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-192.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-192.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-192.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-192.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-256.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-256.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-256.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-256.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-384.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-384.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-384.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-384.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-512.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-512.png similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-512.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/jhipster_family_member_3_head-512.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/images/logo-jhipster.png b/jhipster-6/bookstore-monolith/src/main/webapp/content/images/logo-jhipster.png old mode 100755 new mode 100644 similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/images/logo-jhipster.png rename to jhipster-6/bookstore-monolith/src/main/webapp/content/images/logo-jhipster.png diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/scss/_bootstrap-variables.scss b/jhipster-6/bookstore-monolith/src/main/webapp/content/scss/_bootstrap-variables.scss similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/scss/_bootstrap-variables.scss rename to jhipster-6/bookstore-monolith/src/main/webapp/content/scss/_bootstrap-variables.scss diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/scss/global.scss b/jhipster-6/bookstore-monolith/src/main/webapp/content/scss/global.scss similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/scss/global.scss rename to jhipster-6/bookstore-monolith/src/main/webapp/content/scss/global.scss diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/content/scss/vendor.scss b/jhipster-6/bookstore-monolith/src/main/webapp/content/scss/vendor.scss similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/content/scss/vendor.scss rename to jhipster-6/bookstore-monolith/src/main/webapp/content/scss/vendor.scss diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/favicon.ico b/jhipster-6/bookstore-monolith/src/main/webapp/favicon.ico old mode 100755 new mode 100644 similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/favicon.ico rename to jhipster-6/bookstore-monolith/src/main/webapp/favicon.ico diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/index.html b/jhipster-6/bookstore-monolith/src/main/webapp/index.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/index.html rename to jhipster-6/bookstore-monolith/src/main/webapp/index.html diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/manifest.webapp b/jhipster-6/bookstore-monolith/src/main/webapp/manifest.webapp similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/manifest.webapp rename to jhipster-6/bookstore-monolith/src/main/webapp/manifest.webapp diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/robots.txt b/jhipster-6/bookstore-monolith/src/main/webapp/robots.txt similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/robots.txt rename to jhipster-6/bookstore-monolith/src/main/webapp/robots.txt diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/swagger-ui/index.html b/jhipster-6/bookstore-monolith/src/main/webapp/swagger-ui/index.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/main/webapp/swagger-ui/index.html rename to jhipster-6/bookstore-monolith/src/main/webapp/swagger-ui/index.html diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/config/WebConfigurerUnitTest.java similarity index 73% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/config/WebConfigurerUnitTest.java index 764d6b35875a..44452caac96b 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/config/WebConfigurerUnitTest.java @@ -1,26 +1,19 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.web.filter.CachingHttpHeadersFilter; -import io.undertow.Undertow; -import io.undertow.Undertow.Builder; -import io.undertow.UndertowOptions; -import org.apache.commons.io.FilenameUtils; - import org.h2.server.web.WebServlet; -import org.junit.Before; -import org.junit.Test; -import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.web.MockServletContext; -import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.xnio.OptionMap; import javax.servlet.*; + import java.util.*; import static org.assertj.core.api.Assertions.assertThat; @@ -33,9 +26,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** - * Unit tests for the WebConfigurer class. - * - * @see WebConfigurer + * Unit tests for the {@link WebConfigurer} class. */ public class WebConfigurerUnitTest { @@ -47,7 +38,7 @@ public class WebConfigurerUnitTest { private JHipsterProperties props; - @Before + @BeforeEach public void setup() { servletContext = spy(new MockServletContext()); doReturn(mock(FilterRegistration.Dynamic.class)) @@ -78,35 +69,19 @@ public void testStartUpDevServletContext() throws ServletException { verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class)); verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); } - - @Test - public void testCustomizeServletContainer() { - env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); - UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); - webConfigurer.customize(container); - assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); - assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); - assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); - if (container.getDocumentRoot() != null) { - assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www")); - } - - Builder builder = Undertow.builder(); - container.getBuilderCustomizers().forEach(c -> c.customize(builder)); - OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); - assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); - } - - @Test - public void testUndertowHttp2Enabled() { - props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0); - UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); - webConfigurer.customize(container); - Builder builder = Undertow.builder(); - container.getBuilderCustomizers().forEach(c -> c.customize(builder)); - OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); - assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue(); - } +// +// @Test +// public void testCustomizeServletContainer() { +// env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); +// UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); +// webConfigurer.customize(container); +// assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); +// assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); +// assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); +// if (container.getDocumentRoot() != null) { +// assertThat(container.getDocumentRoot()).isEqualTo(new File("target/classes/static/")); +// } +// } @Test public void testCorsFilterOnApiPath() throws Exception { diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTestController.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/config/WebConfigurerUnitTestController.java similarity index 89% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTestController.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/config/WebConfigurerUnitTestController.java index ee72e1c80e46..271d18278e81 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/WebConfigurerUnitTestController.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/config/WebConfigurerUnitTestController.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.config; +package com.baeldung.jhipster6.config; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/config/timezone/HibernateTimeZoneIT.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/config/timezone/HibernateTimeZoneIT.java new file mode 100644 index 000000000000..2e506edab46a --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/config/timezone/HibernateTimeZoneIT.java @@ -0,0 +1,174 @@ +package com.baeldung.jhipster6.config.timezone; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.repository.timezone.DateTimeWrapper; +import com.baeldung.jhipster6.repository.timezone.DateTimeWrapperRepository; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.support.rowset.SqlRowSet; +import org.springframework.transaction.annotation.Transactional; + +import java.time.*; +import java.time.format.DateTimeFormatter; + +import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Integration tests for the UTC Hibernate configuration. + */ +@SpringBootTest(classes = BookstoreApp.class) +public class HibernateTimeZoneIT { + + @Autowired + private DateTimeWrapperRepository dateTimeWrapperRepository; + @Autowired + private JdbcTemplate jdbcTemplate; + + private DateTimeWrapper dateTimeWrapper; + private DateTimeFormatter dateTimeFormatter; + private DateTimeFormatter timeFormatter; + private DateTimeFormatter dateFormatter; + + @BeforeEach + public void setup() { + dateTimeWrapper = new DateTimeWrapper(); + dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:50:00.0Z")); + dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:50:00.0")); + dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z")); + dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:30:00.0Z")); + dateTimeWrapper.setLocalTime(LocalTime.parse("14:30:00")); + dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:30:00+02:00")); + dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10")); + + dateTimeFormatter = DateTimeFormatter + .ofPattern("yyyy-MM-dd HH:mm:ss.S") + .withZone(ZoneId.of("UTC")); + + timeFormatter = DateTimeFormatter + .ofPattern("HH:mm:ss") + .withZone(ZoneId.of("UTC")); + + dateFormatter = DateTimeFormatter + .ofPattern("yyyy-MM-dd"); + } + + @Test + @Transactional + public void storeInstantWithUtcConfigShouldBeStoredOnGMTTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("instant", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeFormatter.format(dateTimeWrapper.getInstant()); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeLocalDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getLocalDateTime() + .atZone(ZoneId.systemDefault()) + .format(dateTimeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeOffsetDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getOffsetDateTime() + .format(dateTimeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeZoneDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getZonedDateTime() + .format(dateTimeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeLocalTimeWithUtcConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("local_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getLocalTime() + .atDate(LocalDate.of(1970, Month.JANUARY, 1)) + .atZone(ZoneId.systemDefault()) + .format(timeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeOffsetTimeWithUtcConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("offset_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getOffsetTime() + .toLocalTime() + .atDate(LocalDate.of(1970, Month.JANUARY, 1)) + .atZone(ZoneId.systemDefault()) + .format(timeFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + @Test + @Transactional + public void storeLocalDateWithUtcConfigShouldBeStoredWithoutTransformation() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("local_date", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getLocalDate() + .format(dateFormatter); + + assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); + } + + private String generateSqlRequest(String fieldName, long id) { + return format("SELECT %s FROM jhi_date_time_wrapper where id=%d", fieldName, id); + } + + private void assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(SqlRowSet sqlRowSet, String expectedValue) { + while (sqlRowSet.next()) { + String dbValue = sqlRowSet.getString(1); + + assertThat(dbValue).isNotNull(); + assertThat(dbValue).isEqualTo(expectedValue); + } + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/timezone/HibernateTimeZoneIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/config/timezone/HibernateTimeZoneIntegrationTest.java similarity index 96% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/timezone/HibernateTimeZoneIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/config/timezone/HibernateTimeZoneIntegrationTest.java index fba77e037ee9..f0bf619ae41f 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/config/timezone/HibernateTimeZoneIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/config/timezone/HibernateTimeZoneIntegrationTest.java @@ -1,8 +1,9 @@ -package com.baeldung.jhipster5.config.timezone; +package com.baeldung.jhipster6.config.timezone; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.repository.timezone.DateTimeWrapper; +import com.baeldung.jhipster6.repository.timezone.DateTimeWrapperRepository; -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.repository.timezone.DateTimeWrapper; -import com.baeldung.jhipster5.repository.timezone.DateTimeWrapperRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/repository/CustomAuditEventRepositoryIT.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/repository/CustomAuditEventRepositoryIT.java new file mode 100644 index 000000000000..a1f27a21da96 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/repository/CustomAuditEventRepositoryIT.java @@ -0,0 +1,163 @@ +package com.baeldung.jhipster6.repository; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.config.Constants; +import com.baeldung.jhipster6.config.audit.AuditEventConverter; +import com.baeldung.jhipster6.domain.PersistentAuditEvent; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.actuate.audit.AuditEvent; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.web.authentication.WebAuthenticationDetails; +import org.springframework.transaction.annotation.Transactional; + +import javax.servlet.http.HttpSession; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Integration tests for {@link CustomAuditEventRepository}. + */ +@SpringBootTest(classes = BookstoreApp.class) +@Transactional +public class CustomAuditEventRepositoryIT { + + @Autowired + private PersistenceAuditEventRepository persistenceAuditEventRepository; + + @Autowired + private AuditEventConverter auditEventConverter; + + private CustomAuditEventRepository customAuditEventRepository; + + private PersistentAuditEvent testUserEvent; + + private PersistentAuditEvent testOtherUserEvent; + + private PersistentAuditEvent testOldUserEvent; + + @BeforeEach + public void setup() { + customAuditEventRepository = new CustomAuditEventRepository(persistenceAuditEventRepository, auditEventConverter); + persistenceAuditEventRepository.deleteAll(); + Instant oneHourAgo = Instant.now().minusSeconds(3600); + + testUserEvent = new PersistentAuditEvent(); + testUserEvent.setPrincipal("test-user"); + testUserEvent.setAuditEventType("test-type"); + testUserEvent.setAuditEventDate(oneHourAgo); + Map data = new HashMap<>(); + data.put("test-key", "test-value"); + testUserEvent.setData(data); + + testOldUserEvent = new PersistentAuditEvent(); + testOldUserEvent.setPrincipal("test-user"); + testOldUserEvent.setAuditEventType("test-type"); + testOldUserEvent.setAuditEventDate(oneHourAgo.minusSeconds(10000)); + + testOtherUserEvent = new PersistentAuditEvent(); + testOtherUserEvent.setPrincipal("other-test-user"); + testOtherUserEvent.setAuditEventType("test-type"); + testOtherUserEvent.setAuditEventDate(oneHourAgo); + } + + @Test + public void addAuditEvent() { + Map data = new HashMap<>(); + data.put("test-key", "test-value"); + AuditEvent event = new AuditEvent("test-user", "test-type", data); + customAuditEventRepository.add(event); + List persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(1); + PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); + assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); + assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); + assertThat(persistentAuditEvent.getData()).containsKey("test-key"); + assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("test-value"); + assertThat(persistentAuditEvent.getAuditEventDate().truncatedTo(ChronoUnit.MILLIS)) + .isEqualTo(event.getTimestamp().truncatedTo(ChronoUnit.MILLIS)); + } + + @Test + public void addAuditEventTruncateLargeData() { + Map data = new HashMap<>(); + StringBuilder largeData = new StringBuilder(); + for (int i = 0; i < CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH + 10; i++) { + largeData.append("a"); + } + data.put("test-key", largeData); + AuditEvent event = new AuditEvent("test-user", "test-type", data); + customAuditEventRepository.add(event); + List persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(1); + PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); + assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); + assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); + assertThat(persistentAuditEvent.getData()).containsKey("test-key"); + String actualData = persistentAuditEvent.getData().get("test-key"); + assertThat(actualData.length()).isEqualTo(CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH); + assertThat(actualData).isSubstringOf(largeData); + assertThat(persistentAuditEvent.getAuditEventDate().truncatedTo(ChronoUnit.MILLIS)) + .isEqualTo(event.getTimestamp().truncatedTo(ChronoUnit.MILLIS)); + } + + @Test + public void testAddEventWithWebAuthenticationDetails() { + HttpSession session = new MockHttpSession(null, "test-session-id"); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setSession(session); + request.setRemoteAddr("1.2.3.4"); + WebAuthenticationDetails details = new WebAuthenticationDetails(request); + Map data = new HashMap<>(); + data.put("test-key", details); + AuditEvent event = new AuditEvent("test-user", "test-type", data); + customAuditEventRepository.add(event); + List persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(1); + PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); + assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4"); + assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id"); + } + + @Test + public void testAddEventWithNullData() { + Map data = new HashMap<>(); + data.put("test-key", null); + AuditEvent event = new AuditEvent("test-user", "test-type", data); + customAuditEventRepository.add(event); + List persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(1); + PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); + assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("null"); + } + + @Test + public void addAuditEventWithAnonymousUser() { + Map data = new HashMap<>(); + data.put("test-key", "test-value"); + AuditEvent event = new AuditEvent(Constants.ANONYMOUS_USER, "test-type", data); + customAuditEventRepository.add(event); + List persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(0); + } + + @Test + public void addAuditEventWithAuthorizationFailureType() { + Map data = new HashMap<>(); + data.put("test-key", "test-value"); + AuditEvent event = new AuditEvent("test-user", "AUTHORIZATION_FAILURE", data); + customAuditEventRepository.add(event); + List persistentAuditEvents = persistenceAuditEventRepository.findAll(); + assertThat(persistentAuditEvents).hasSize(0); + } + +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/repository/CustomAuditEventRepositoryIntegrationTest.java similarity index 93% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/repository/CustomAuditEventRepositoryIntegrationTest.java index 948bf43f8776..89ed2d4649ce 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/CustomAuditEventRepositoryIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/repository/CustomAuditEventRepositoryIntegrationTest.java @@ -1,9 +1,10 @@ -package com.baeldung.jhipster5.repository; +package com.baeldung.jhipster6.repository; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.config.Constants; +import com.baeldung.jhipster6.config.audit.AuditEventConverter; +import com.baeldung.jhipster6.domain.PersistentAuditEvent; -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.config.Constants; -import com.baeldung.jhipster5.config.audit.AuditEventConverter; -import com.baeldung.jhipster5.domain.PersistentAuditEvent; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -23,7 +24,6 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static com.baeldung.jhipster5.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH; /** * Test class for the CustomAuditEventRepository class. @@ -94,7 +94,7 @@ public void addAuditEvent() { public void addAuditEventTruncateLargeData() { Map data = new HashMap<>(); StringBuilder largeData = new StringBuilder(); - for (int i = 0; i < EVENT_DATA_COLUMN_MAX_LENGTH + 10; i++) { + for (int i = 0; i < CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH + 10; i++) { largeData.append("a"); } data.put("test-key", largeData); @@ -107,7 +107,7 @@ public void addAuditEventTruncateLargeData() { assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); assertThat(persistentAuditEvent.getData()).containsKey("test-key"); String actualData = persistentAuditEvent.getData().get("test-key"); - assertThat(actualData.length()).isEqualTo(EVENT_DATA_COLUMN_MAX_LENGTH); + assertThat(actualData.length()).isEqualTo(CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH); assertThat(actualData).isSubstringOf(largeData); assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp()); } diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/timezone/DateTimeWrapper.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/repository/timezone/DateTimeWrapper.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/timezone/DateTimeWrapper.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/repository/timezone/DateTimeWrapper.java index 473a8e782ef4..0d03a44cf8a9 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/timezone/DateTimeWrapper.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/repository/timezone/DateTimeWrapper.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.repository.timezone; +package com.baeldung.jhipster6.repository.timezone; import javax.persistence.*; import java.io.Serializable; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/timezone/DateTimeWrapperRepository.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/repository/timezone/DateTimeWrapperRepository.java similarity index 84% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/timezone/DateTimeWrapperRepository.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/repository/timezone/DateTimeWrapperRepository.java index 9c3831879fb5..5923db6ca0d9 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/repository/timezone/DateTimeWrapperRepository.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/repository/timezone/DateTimeWrapperRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.repository.timezone; +package com.baeldung.jhipster6.repository.timezone; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/DomainUserDetailsServiceIT.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/DomainUserDetailsServiceIT.java new file mode 100644 index 000000000000..3e641dfad762 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/DomainUserDetailsServiceIT.java @@ -0,0 +1,125 @@ +package com.baeldung.jhipster6.security; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.UserRepository; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Locale; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +/** + * Integrations tests for {@link DomainUserDetailsService}. + */ +@SpringBootTest(classes = BookstoreApp.class) +@Transactional +public class DomainUserDetailsServiceIT { + + private static final String USER_ONE_LOGIN = "test-user-one"; + private static final String USER_ONE_EMAIL = "test-user-one@localhost"; + private static final String USER_TWO_LOGIN = "test-user-two"; + private static final String USER_TWO_EMAIL = "test-user-two@localhost"; + private static final String USER_THREE_LOGIN = "test-user-three"; + private static final String USER_THREE_EMAIL = "test-user-three@localhost"; + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserDetailsService domainUserDetailsService; + + private User userOne; + private User userTwo; + private User userThree; + + @BeforeEach + public void init() { + userOne = new User(); + userOne.setLogin(USER_ONE_LOGIN); + userOne.setPassword(RandomStringUtils.random(60)); + userOne.setActivated(true); + userOne.setEmail(USER_ONE_EMAIL); + userOne.setFirstName("userOne"); + userOne.setLastName("doe"); + userOne.setLangKey("en"); + userRepository.save(userOne); + + userTwo = new User(); + userTwo.setLogin(USER_TWO_LOGIN); + userTwo.setPassword(RandomStringUtils.random(60)); + userTwo.setActivated(true); + userTwo.setEmail(USER_TWO_EMAIL); + userTwo.setFirstName("userTwo"); + userTwo.setLastName("doe"); + userTwo.setLangKey("en"); + userRepository.save(userTwo); + + userThree = new User(); + userThree.setLogin(USER_THREE_LOGIN); + userThree.setPassword(RandomStringUtils.random(60)); + userThree.setActivated(false); + userThree.setEmail(USER_THREE_EMAIL); + userThree.setFirstName("userThree"); + userThree.setLastName("doe"); + userThree.setLangKey("en"); + userRepository.save(userThree); + } + + @Test + @Transactional + public void assertThatUserCanBeFoundByLogin() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); + } + + @Test + @Transactional + public void assertThatUserCanBeFoundByLoginIgnoreCase() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN.toUpperCase(Locale.ENGLISH)); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); + } + + @Test + @Transactional + public void assertThatUserCanBeFoundByEmail() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN); + } + + @Test + @Transactional + public void assertThatUserCanNotBeFoundByEmailIgnoreCase() { + assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy( + () -> domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH))); + } + + @Test + @Transactional + public void assertThatEmailIsPrioritizedOverLogin() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_EMAIL); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); + } + + @Test + @Transactional + public void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() { + assertThatExceptionOfType(UserNotActivatedException.class).isThrownBy( + () -> domainUserDetailsService.loadUserByUsername(USER_THREE_LOGIN)); + } + +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/DomainUserDetailsServiceIntegrationTest.java similarity index 95% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/DomainUserDetailsServiceIntegrationTest.java index 11757f651624..bf30067406be 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/DomainUserDetailsServiceIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/DomainUserDetailsServiceIntegrationTest.java @@ -1,8 +1,8 @@ -package com.baeldung.jhipster5.security; +package com.baeldung.jhipster6.security; -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.UserRepository; +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.UserRepository; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/MockAuthenticationManager.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/MockAuthenticationManager.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/MockAuthenticationManager.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/MockAuthenticationManager.java index bdcdba7644b7..0b320720101e 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/MockAuthenticationManager.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/MockAuthenticationManager.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.security; +package com.baeldung.jhipster6.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/SecurityUtilsUnitTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/SecurityUtilsUnitTest.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/SecurityUtilsUnitTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/SecurityUtilsUnitTest.java index b2736badd638..b017acd022cf 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/SecurityUtilsUnitTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/SecurityUtilsUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.security; +package com.baeldung.jhipster6.security; import org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/jwt/JWTFilter2UnitTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/jwt/JWTFilter2UnitTest.java new file mode 100644 index 000000000000..11a64993e920 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/jwt/JWTFilter2UnitTest.java @@ -0,0 +1,116 @@ +package com.baeldung.jhipster6.security.jwt; + +import com.baeldung.jhipster6.security.AuthoritiesConstants; + +import io.github.jhipster.config.JHipsterProperties; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.HttpStatus; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JWTFilter2UnitTest { + + private TokenProvider tokenProvider; + + private JWTFilter jwtFilter; + + @Before + public void setup() { + JHipsterProperties jHipsterProperties = new JHipsterProperties(); + tokenProvider = new TokenProvider(jHipsterProperties); + ReflectionTestUtils.setField(tokenProvider, "key", + Keys.hmacShaKeyFor(Decoders.BASE64 + .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"))); + + ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000); + jwtFilter = new JWTFilter(tokenProvider); + SecurityContextHolder.getContext().setAuthentication(null); + } + + @Test + public void testJWTFilter() throws Exception { + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( + "test-user", + "test-password", + Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) + ); + String jwt = tokenProvider.createToken(authentication, false); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user"); + assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt); + } + + @Test + public void testJWTFilterInvalidToken() throws Exception { + String jwt = "wrong_jwt"; + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + + @Test + public void testJWTFilterMissingAuthorization() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + + @Test + public void testJWTFilterMissingToken() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer "); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + + @Test + public void testJWTFilterWrongScheme() throws Exception { + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( + "test-user", + "test-password", + Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) + ); + String jwt = tokenProvider.createToken(authentication, false); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt); + request.setRequestURI("/api/test"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain filterChain = new MockFilterChain(); + jwtFilter.doFilter(request, response, filterChain); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); + } + +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterUnitTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/jwt/JWTFilterUnitTest.java similarity index 96% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterUnitTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/jwt/JWTFilterUnitTest.java index 2be8e6809ad7..13633c901c78 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/JWTFilterUnitTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/jwt/JWTFilterUnitTest.java @@ -1,12 +1,13 @@ -package com.baeldung.jhipster5.security.jwt; +package com.baeldung.jhipster6.security.jwt; + +import com.baeldung.jhipster6.security.AuthoritiesConstants; -import com.baeldung.jhipster5.security.AuthoritiesConstants; import io.github.jhipster.config.JHipsterProperties; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; @@ -26,7 +27,7 @@ public class JWTFilterUnitTest { private JWTFilter jwtFilter; - @Before + @BeforeEach public void setup() { JHipsterProperties jHipsterProperties = new JHipsterProperties(); tokenProvider = new TokenProvider(jHipsterProperties); diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/jwt/TokenProvider2UnitTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/jwt/TokenProvider2UnitTest.java new file mode 100644 index 000000000000..311deb3fd712 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/jwt/TokenProvider2UnitTest.java @@ -0,0 +1,111 @@ +package com.baeldung.jhipster6.security.jwt; + +import com.baeldung.jhipster6.security.AuthoritiesConstants; + +import java.security.Key; +import java.util.*; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.test.util.ReflectionTestUtils; + +import io.github.jhipster.config.JHipsterProperties; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; + +import static org.assertj.core.api.Assertions.assertThat; + +public class TokenProvider2UnitTest { + + private final long ONE_MINUTE = 60000; + private Key key; + private JHipsterProperties jHipsterProperties; + private TokenProvider tokenProvider; + + @Before + public void setup() { + jHipsterProperties = Mockito.mock(JHipsterProperties.class); + tokenProvider = new TokenProvider(jHipsterProperties); + key = Keys.hmacShaKeyFor(Decoders.BASE64 + .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); + + ReflectionTestUtils.setField(tokenProvider, "key", key); + ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE); + } + + @Test + public void testReturnFalseWhenJWThasInvalidSignature() { + boolean isTokenValid = tokenProvider.validateToken(createTokenWithDifferentSignature()); + + assertThat(isTokenValid).isEqualTo(false); + } + + @Test + public void testReturnFalseWhenJWTisMalformed() { + Authentication authentication = createAuthentication(); + String token = tokenProvider.createToken(authentication, false); + String invalidToken = token.substring(1); + boolean isTokenValid = tokenProvider.validateToken(invalidToken); + + assertThat(isTokenValid).isEqualTo(false); + } + + @Test + public void testReturnFalseWhenJWTisExpired() { + ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", -ONE_MINUTE); + + Authentication authentication = createAuthentication(); + String token = tokenProvider.createToken(authentication, false); + + boolean isTokenValid = tokenProvider.validateToken(token); + + assertThat(isTokenValid).isEqualTo(false); + } + + @Test + public void testReturnFalseWhenJWTisUnsupported() { + String unsupportedToken = createUnsupportedToken(); + + boolean isTokenValid = tokenProvider.validateToken(unsupportedToken); + + assertThat(isTokenValid).isEqualTo(false); + } + + @Test + public void testReturnFalseWhenJWTisInvalid() { + boolean isTokenValid = tokenProvider.validateToken(""); + + assertThat(isTokenValid).isEqualTo(false); + } + + private Authentication createAuthentication() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); + return new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities); + } + + private String createUnsupportedToken() { + return Jwts.builder() + .setPayload("payload") + .signWith(key, SignatureAlgorithm.HS512) + .compact(); + } + + private String createTokenWithDifferentSignature() { + Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64 + .decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); + + return Jwts.builder() + .setSubject("anonymous") + .signWith(otherKey, SignatureAlgorithm.HS512) + .setExpiration(new Date(new Date().getTime() + ONE_MINUTE)) + .compact(); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderUnitTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/jwt/TokenProviderUnitTest.java similarity index 89% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderUnitTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/jwt/TokenProviderUnitTest.java index 18da2eb87563..3d14352c797a 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/jwt/TokenProviderUnitTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/security/jwt/TokenProviderUnitTest.java @@ -1,13 +1,12 @@ -package com.baeldung.jhipster5.security.jwt; +package com.baeldung.jhipster6.security.jwt; -import com.baeldung.jhipster5.security.AuthoritiesConstants; +import com.baeldung.jhipster6.security.AuthoritiesConstants; import java.security.Key; import java.util.*; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; @@ -24,15 +23,14 @@ public class TokenProviderUnitTest { - private final long ONE_MINUTE = 60000; + private static final long ONE_MINUTE = 60000; + private Key key; - private JHipsterProperties jHipsterProperties; private TokenProvider tokenProvider; - @Before + @BeforeEach public void setup() { - jHipsterProperties = Mockito.mock(JHipsterProperties.class); - tokenProvider = new TokenProvider(jHipsterProperties); + tokenProvider = new TokenProvider( new JHipsterProperties()); key = Keys.hmacShaKeyFor(Decoders.BASE64 .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/MailServiceIT.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/MailServiceIT.java new file mode 100644 index 000000000000..602ff4319d64 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/MailServiceIT.java @@ -0,0 +1,189 @@ +package com.baeldung.jhipster6.service; + +import com.baeldung.jhipster6.config.Constants; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.domain.User; + +import io.github.jhipster.config.JHipsterProperties; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.MessageSource; +import org.springframework.mail.MailSendException; +import org.springframework.mail.javamail.JavaMailSenderImpl; +import org.thymeleaf.spring5.SpringTemplateEngine; + +import javax.mail.Multipart; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; +import java.io.ByteArrayOutputStream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +/** + * Integration tests for {@link MailService}. + */ +@SpringBootTest(classes = BookstoreApp.class) +public class MailServiceIT { + + @Autowired + private JHipsterProperties jHipsterProperties; + + @Autowired + private MessageSource messageSource; + + @Autowired + private SpringTemplateEngine templateEngine; + + @Spy + private JavaMailSenderImpl javaMailSender; + + @Captor + private ArgumentCaptor messageCaptor; + + private MailService mailService; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + doNothing().when(javaMailSender).send(any(MimeMessage.class)); + mailService = new MailService(jHipsterProperties, javaMailSender, messageSource, templateEngine); + } + + @Test + public void testSendEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent()).isInstanceOf(String.class); + assertThat(message.getContent().toString()).isEqualTo("testContent"); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); + } + + @Test + public void testSendHtmlEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, true); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent()).isInstanceOf(String.class); + assertThat(message.getContent().toString()).isEqualTo("testContent"); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendMultipartEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, false); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + MimeMultipart mp = (MimeMultipart) message.getContent(); + MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + part.writeTo(aos); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent()).isInstanceOf(Multipart.class); + assertThat(aos.toString()).isEqualTo("\r\ntestContent"); + assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); + } + + @Test + public void testSendMultipartHtmlEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, true); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + MimeMultipart mp = (MimeMultipart) message.getContent(); + MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + part.writeTo(aos); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent()).isInstanceOf(Multipart.class); + assertThat(aos.toString()).isEqualTo("\r\ntestContent"); + assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendEmailFromTemplate() throws Exception { + User user = new User(); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + user.setLangKey("en"); + mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title"); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getSubject()).isEqualTo("test title"); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("test title, http://127.0.0.1:8080, john\n"); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendActivationEmail() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendActivationEmail(user); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent().toString()).isNotEmpty(); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testCreationEmail() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendCreationEmail(user); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent().toString()).isNotEmpty(); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendPasswordResetMail() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendPasswordResetMail(user); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); + assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); + assertThat(message.getContent().toString()).isNotEmpty(); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + public void testSendEmailWithException() throws Exception { + doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class)); + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); + } + +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/MailServiceIntegrationTest.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/MailServiceIntegrationTest.java index 72592e1239c7..af04430ee7c9 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/MailServiceIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/MailServiceIntegrationTest.java @@ -1,8 +1,9 @@ -package com.baeldung.jhipster5.service; -import com.baeldung.jhipster5.config.Constants; +package com.baeldung.jhipster6.service; +import com.baeldung.jhipster6.config.Constants; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.domain.User; -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.domain.User; import io.github.jhipster.config.JHipsterProperties; import org.junit.Before; import org.junit.Test; diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/UserServiceIT.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/UserServiceIT.java new file mode 100644 index 000000000000..5c624b166d4a --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/UserServiceIT.java @@ -0,0 +1,200 @@ +package com.baeldung.jhipster6.service; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.config.Constants; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.UserRepository; +import com.baeldung.jhipster6.service.dto.UserDTO; +import com.baeldung.jhipster6.service.util.RandomUtil; + +import org.apache.commons.lang3.RandomStringUtils; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.auditing.AuditingHandler; +import org.springframework.data.auditing.DateTimeProvider; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.time.LocalDateTime; +import java.util.Optional; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +/** + * Integration tests for {@link UserService}. + */ +@SpringBootTest(classes = BookstoreApp.class) +@Transactional +public class UserServiceIT { + + private static final String DEFAULT_LOGIN = "johndoe"; + + private static final String DEFAULT_EMAIL = "johndoe@localhost"; + + private static final String DEFAULT_FIRSTNAME = "john"; + + private static final String DEFAULT_LASTNAME = "doe"; + + private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50"; + + private static final String DEFAULT_LANGKEY = "en"; + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserService userService; + + @Autowired + private AuditingHandler auditingHandler; + + @Mock + private DateTimeProvider dateTimeProvider; + + private User user; + + @BeforeEach + public void init() { + user = new User(); + user.setLogin(DEFAULT_LOGIN); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setEmail(DEFAULT_EMAIL); + user.setFirstName(DEFAULT_FIRSTNAME); + user.setLastName(DEFAULT_LASTNAME); + user.setImageUrl(DEFAULT_IMAGEURL); + user.setLangKey(DEFAULT_LANGKEY); + + when(dateTimeProvider.getNow()).thenReturn(Optional.of(LocalDateTime.now())); + auditingHandler.setDateTimeProvider(dateTimeProvider); + } + + @Test + @Transactional + public void assertThatUserMustExistToResetPassword() { + userRepository.saveAndFlush(user); + Optional maybeUser = userService.requestPasswordReset("invalid.login@localhost"); + assertThat(maybeUser).isNotPresent(); + + maybeUser = userService.requestPasswordReset(user.getEmail()); + assertThat(maybeUser).isPresent(); + assertThat(maybeUser.orElse(null).getEmail()).isEqualTo(user.getEmail()); + assertThat(maybeUser.orElse(null).getResetDate()).isNotNull(); + assertThat(maybeUser.orElse(null).getResetKey()).isNotNull(); + } + + @Test + @Transactional + public void assertThatOnlyActivatedUserCanRequestPasswordReset() { + user.setActivated(false); + userRepository.saveAndFlush(user); + + Optional maybeUser = userService.requestPasswordReset(user.getLogin()); + assertThat(maybeUser).isNotPresent(); + userRepository.delete(user); + } + + @Test + @Transactional + public void assertThatResetKeyMustNotBeOlderThan24Hours() { + Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS); + String resetKey = RandomUtil.generateResetKey(); + user.setActivated(true); + user.setResetDate(daysAgo); + user.setResetKey(resetKey); + userRepository.saveAndFlush(user); + + Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); + assertThat(maybeUser).isNotPresent(); + userRepository.delete(user); + } + + @Test + @Transactional + public void assertThatResetKeyMustBeValid() { + Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS); + user.setActivated(true); + user.setResetDate(daysAgo); + user.setResetKey("1234"); + userRepository.saveAndFlush(user); + + Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); + assertThat(maybeUser).isNotPresent(); + userRepository.delete(user); + } + + @Test + @Transactional + public void assertThatUserCanResetPassword() { + String oldPassword = user.getPassword(); + Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS); + String resetKey = RandomUtil.generateResetKey(); + user.setActivated(true); + user.setResetDate(daysAgo); + user.setResetKey(resetKey); + userRepository.saveAndFlush(user); + + Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); + assertThat(maybeUser).isPresent(); + assertThat(maybeUser.orElse(null).getResetDate()).isNull(); + assertThat(maybeUser.orElse(null).getResetKey()).isNull(); + assertThat(maybeUser.orElse(null).getPassword()).isNotEqualTo(oldPassword); + + userRepository.delete(user); + } + + @Test + @Transactional + public void testFindNotActivatedUsersByCreationDateBefore() { + Instant now = Instant.now(); + when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS))); + user.setActivated(false); + User dbUser = userRepository.saveAndFlush(user); + dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS)); + userRepository.saveAndFlush(user); + List users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS)); + assertThat(users).isNotEmpty(); + userService.removeNotActivatedUsers(); + users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS)); + assertThat(users).isEmpty(); + } + + @Test + @Transactional + public void assertThatAnonymousUserIsNotGet() { + user.setLogin(Constants.ANONYMOUS_USER); + if (!userRepository.findOneByLogin(Constants.ANONYMOUS_USER).isPresent()) { + userRepository.saveAndFlush(user); + } + final PageRequest pageable = PageRequest.of(0, (int) userRepository.count()); + final Page allManagedUsers = userService.getAllManagedUsers(pageable); + assertThat(allManagedUsers.getContent().stream() + .noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin()))) + .isTrue(); + } + + + @Test + @Transactional + public void testRemoveNotActivatedUsers() { + // custom "now" for audit to use as creation date + when(dateTimeProvider.getNow()).thenReturn(Optional.of(Instant.now().minus(30, ChronoUnit.DAYS))); + + user.setActivated(false); + userRepository.saveAndFlush(user); + + Assertions.assertThat(userRepository.findOneByLogin(DEFAULT_LOGIN)).isPresent(); + userService.removeNotActivatedUsers(); + Assertions.assertThat(userRepository.findOneByLogin(DEFAULT_LOGIN)).isNotPresent(); + } + +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/UserServiceIntegrationTest.java similarity index 92% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/UserServiceIntegrationTest.java index ca3608462d7a..b8e8a9e1aafb 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/UserServiceIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/UserServiceIntegrationTest.java @@ -1,13 +1,14 @@ -package com.baeldung.jhipster5.service; +package com.baeldung.jhipster6.service; -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.config.Constants; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.UserRepository; -import com.baeldung.jhipster5.service.dto.UserDTO; -import com.baeldung.jhipster5.service.util.RandomUtil; +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.config.Constants; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.UserRepository; +import com.baeldung.jhipster6.service.dto.UserDTO; +import com.baeldung.jhipster6.service.util.RandomUtil; import org.apache.commons.lang3.RandomStringUtils; +import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -184,9 +185,9 @@ public void testRemoveNotActivatedUsers() { user.setActivated(false); userRepository.saveAndFlush(user); - assertThat(userRepository.findOneByLogin("johndoe")).isPresent(); + Assertions.assertThat(userRepository.findOneByLogin("johndoe")).isPresent(); userService.removeNotActivatedUsers(); - assertThat(userRepository.findOneByLogin("johndoe")).isNotPresent(); + Assertions.assertThat(userRepository.findOneByLogin("johndoe")).isNotPresent(); } } diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/mapper/UserMapperIT.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/mapper/UserMapperIT.java new file mode 100644 index 000000000000..cca2dc7d92ec --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/mapper/UserMapperIT.java @@ -0,0 +1,143 @@ +package com.baeldung.jhipster6.service.mapper; + + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.service.dto.UserDTO; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Integration tests for {@link UserMapper}. + */ +@SpringBootTest(classes = BookstoreApp.class) +public class UserMapperIT { + + private static final String DEFAULT_LOGIN = "johndoe"; + private static final Long DEFAULT_ID = 1L; + + @Autowired + private UserMapper userMapper; + + private User user; + private UserDTO userDto; + + @BeforeEach + public void init() { + user = new User(); + user.setLogin(DEFAULT_LOGIN); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setEmail("johndoe@localhost"); + user.setFirstName("john"); + user.setLastName("doe"); + user.setImageUrl("image_url"); + user.setLangKey("en"); + + userDto = new UserDTO(user); + } + + @Test + public void usersToUserDTOsShouldMapOnlyNonNullUsers() { + List users = new ArrayList<>(); + users.add(user); + users.add(null); + + List userDTOS = userMapper.usersToUserDTOs(users); + + assertThat(userDTOS).isNotEmpty(); + assertThat(userDTOS).size().isEqualTo(1); + } + + @Test + public void userDTOsToUsersShouldMapOnlyNonNullUsers() { + List usersDto = new ArrayList<>(); + usersDto.add(userDto); + usersDto.add(null); + + List users = userMapper.userDTOsToUsers(usersDto); + + assertThat(users).isNotEmpty(); + assertThat(users).size().isEqualTo(1); + } + + @Test + public void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain() { + Set authoritiesAsString = new HashSet<>(); + authoritiesAsString.add("ADMIN"); + userDto.setAuthorities(authoritiesAsString); + + List usersDto = new ArrayList<>(); + usersDto.add(userDto); + + List users = userMapper.userDTOsToUsers(usersDto); + + assertThat(users).isNotEmpty(); + assertThat(users).size().isEqualTo(1); + assertThat(users.get(0).getAuthorities()).isNotNull(); + assertThat(users.get(0).getAuthorities()).isNotEmpty(); + assertThat(users.get(0).getAuthorities().iterator().next().getName()).isEqualTo("ADMIN"); + } + + @Test + public void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() { + userDto.setAuthorities(null); + + List usersDto = new ArrayList<>(); + usersDto.add(userDto); + + List users = userMapper.userDTOsToUsers(usersDto); + + assertThat(users).isNotEmpty(); + assertThat(users).size().isEqualTo(1); + assertThat(users.get(0).getAuthorities()).isNotNull(); + assertThat(users.get(0).getAuthorities()).isEmpty(); + } + + @Test + public void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities() { + Set authoritiesAsString = new HashSet<>(); + authoritiesAsString.add("ADMIN"); + userDto.setAuthorities(authoritiesAsString); + + User user = userMapper.userDTOToUser(userDto); + + assertThat(user).isNotNull(); + assertThat(user.getAuthorities()).isNotNull(); + assertThat(user.getAuthorities()).isNotEmpty(); + assertThat(user.getAuthorities().iterator().next().getName()).isEqualTo("ADMIN"); + } + + @Test + public void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() { + userDto.setAuthorities(null); + + User user = userMapper.userDTOToUser(userDto); + + assertThat(user).isNotNull(); + assertThat(user.getAuthorities()).isNotNull(); + assertThat(user.getAuthorities()).isEmpty(); + } + + @Test + public void userDTOToUserMapWithNullUserShouldReturnNull() { + assertThat(userMapper.userDTOToUser(null)).isNull(); + } + + @Test + public void testUserFromId() { + assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID); + assertThat(userMapper.userFromId(null)).isNull(); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/mapper/UserMapperIntegrationTest.java similarity index 96% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/mapper/UserMapperIntegrationTest.java index cd49135d63c7..d143caccf61f 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/service/mapper/UserMapperIntegrationTest.java @@ -1,9 +1,10 @@ -package com.baeldung.jhipster5.service.mapper; +package com.baeldung.jhipster6.service.mapper; -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.service.dto.UserDTO; +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.service.dto.UserDTO; + import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/AccountResourceIT.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/AccountResourceIT.java new file mode 100644 index 000000000000..4655526bb04c --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/AccountResourceIT.java @@ -0,0 +1,815 @@ +package com.baeldung.jhipster6.web.rest; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.config.Constants; +import com.baeldung.jhipster6.domain.Authority; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.AuthorityRepository; +import com.baeldung.jhipster6.repository.UserRepository; +import com.baeldung.jhipster6.security.AuthoritiesConstants; +import com.baeldung.jhipster6.service.MailService; +import com.baeldung.jhipster6.service.UserService; +import com.baeldung.jhipster6.service.dto.PasswordChangeDTO; +import com.baeldung.jhipster6.service.dto.UserDTO; +import com.baeldung.jhipster6.web.rest.errors.ExceptionTranslator; +import com.baeldung.jhipster6.web.rest.vm.KeyAndPasswordVM; +import com.baeldung.jhipster6.web.rest.vm.ManagedUserVM; + +import org.apache.commons.lang3.RandomStringUtils; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Instant; +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** + * Integration tests for the {@link AccountResource} REST controller. + */ +@SpringBootTest(classes = BookstoreApp.class) +public class AccountResourceIT { + + @Autowired + private UserRepository userRepository; + + @Autowired + private AuthorityRepository authorityRepository; + + @Autowired + private UserService userService; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private HttpMessageConverter[] httpMessageConverters; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Mock + private UserService mockUserService; + + @Mock + private MailService mockMailService; + + private MockMvc restMvc; + + private MockMvc restUserMockMvc; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + doNothing().when(mockMailService).sendActivationEmail(any()); + AccountResource accountResource = + new AccountResource(userRepository, userService, mockMailService); + + AccountResource accountUserMockResource = + new AccountResource(userRepository, mockUserService, mockMailService); + this.restMvc = MockMvcBuilders.standaloneSetup(accountResource) + .setMessageConverters(httpMessageConverters) + .setControllerAdvice(exceptionTranslator) + .build(); + this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource) + .setControllerAdvice(exceptionTranslator) + .build(); + } + + @Test + public void testNonAuthenticatedUser() throws Exception { + restUserMockMvc.perform(get("/api/authenticate") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("")); + } + + @Test + public void testAuthenticatedUser() throws Exception { + restUserMockMvc.perform(get("/api/authenticate") + .with(request -> { + request.setRemoteUser("test"); + return request; + }) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("test")); + } + + @Test + public void testGetExistingAccount() throws Exception { + Set authorities = new HashSet<>(); + Authority authority = new Authority(); + authority.setName(AuthoritiesConstants.ADMIN); + authorities.add(authority); + + User user = new User(); + user.setLogin("test"); + user.setFirstName("john"); + user.setLastName("doe"); + user.setEmail("john.doe@jhipster.com"); + user.setImageUrl("http://placehold.it/50x50"); + user.setLangKey("en"); + user.setAuthorities(authorities); + when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user)); + + restUserMockMvc.perform(get("/api/account") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.login").value("test")) + .andExpect(jsonPath("$.firstName").value("john")) + .andExpect(jsonPath("$.lastName").value("doe")) + .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) + .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) + .andExpect(jsonPath("$.langKey").value("en")) + .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); + } + + @Test + public void testGetUnknownAccount() throws Exception { + when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty()); + + restUserMockMvc.perform(get("/api/account") + .accept(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(status().isInternalServerError()); + } + + @Test + @Transactional + public void testRegisterValid() throws Exception { + ManagedUserVM validUser = new ManagedUserVM(); + validUser.setLogin("test-register-valid"); + validUser.setPassword("password"); + validUser.setFirstName("Alice"); + validUser.setLastName("Test"); + validUser.setEmail("test-register-valid@example.com"); + validUser.setImageUrl("http://placehold.it/50x50"); + validUser.setLangKey(Constants.DEFAULT_LANGUAGE); + validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse(); + + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(validUser))) + .andExpect(status().isCreated()); + + assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue(); + } + + @Test + @Transactional + public void testRegisterInvalidLogin() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("funky-log!n");// <-- invalid + invalidUser.setPassword("password"); + invalidUser.setFirstName("Funky"); + invalidUser.setLastName("One"); + invalidUser.setEmail("funky@example.com"); + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional user = userRepository.findOneByEmailIgnoreCase("funky@example.com"); + assertThat(user.isPresent()).isFalse(); + } + + @Test + @Transactional + public void testRegisterInvalidEmail() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("bob"); + invalidUser.setPassword("password"); + invalidUser.setFirstName("Bob"); + invalidUser.setLastName("Green"); + invalidUser.setEmail("invalid");// <-- invalid + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional user = userRepository.findOneByLogin("bob"); + assertThat(user.isPresent()).isFalse(); + } + + @Test + @Transactional + public void testRegisterInvalidPassword() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("bob"); + invalidUser.setPassword("123");// password with only 3 digits + invalidUser.setFirstName("Bob"); + invalidUser.setLastName("Green"); + invalidUser.setEmail("bob@example.com"); + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional user = userRepository.findOneByLogin("bob"); + assertThat(user.isPresent()).isFalse(); + } + + @Test + @Transactional + public void testRegisterNullPassword() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("bob"); + invalidUser.setPassword(null);// invalid null password + invalidUser.setFirstName("Bob"); + invalidUser.setLastName("Green"); + invalidUser.setEmail("bob@example.com"); + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional user = userRepository.findOneByLogin("bob"); + assertThat(user.isPresent()).isFalse(); + } + + @Test + @Transactional + public void testRegisterDuplicateLogin() throws Exception { + // First registration + ManagedUserVM firstUser = new ManagedUserVM(); + firstUser.setLogin("alice"); + firstUser.setPassword("password"); + firstUser.setFirstName("Alice"); + firstUser.setLastName("Something"); + firstUser.setEmail("alice@example.com"); + firstUser.setImageUrl("http://placehold.it/50x50"); + firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); + firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // Duplicate login, different email + ManagedUserVM secondUser = new ManagedUserVM(); + secondUser.setLogin(firstUser.getLogin()); + secondUser.setPassword(firstUser.getPassword()); + secondUser.setFirstName(firstUser.getFirstName()); + secondUser.setLastName(firstUser.getLastName()); + secondUser.setEmail("alice2@example.com"); + secondUser.setImageUrl(firstUser.getImageUrl()); + secondUser.setLangKey(firstUser.getLangKey()); + secondUser.setCreatedBy(firstUser.getCreatedBy()); + secondUser.setCreatedDate(firstUser.getCreatedDate()); + secondUser.setLastModifiedBy(firstUser.getLastModifiedBy()); + secondUser.setLastModifiedDate(firstUser.getLastModifiedDate()); + secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); + + // First user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(firstUser))) + .andExpect(status().isCreated()); + + // Second (non activated) user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().isCreated()); + + Optional testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com"); + assertThat(testUser.isPresent()).isTrue(); + testUser.get().setActivated(true); + userRepository.save(testUser.get()); + + // Second (already activated) user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().is4xxClientError()); + } + + @Test + @Transactional + public void testRegisterDuplicateEmail() throws Exception { + // First user + ManagedUserVM firstUser = new ManagedUserVM(); + firstUser.setLogin("test-register-duplicate-email"); + firstUser.setPassword("password"); + firstUser.setFirstName("Alice"); + firstUser.setLastName("Test"); + firstUser.setEmail("test-register-duplicate-email@example.com"); + firstUser.setImageUrl("http://placehold.it/50x50"); + firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); + firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // Register first user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(firstUser))) + .andExpect(status().isCreated()); + + Optional testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); + assertThat(testUser1.isPresent()).isTrue(); + + // Duplicate email, different login + ManagedUserVM secondUser = new ManagedUserVM(); + secondUser.setLogin("test-register-duplicate-email-2"); + secondUser.setPassword(firstUser.getPassword()); + secondUser.setFirstName(firstUser.getFirstName()); + secondUser.setLastName(firstUser.getLastName()); + secondUser.setEmail(firstUser.getEmail()); + secondUser.setImageUrl(firstUser.getImageUrl()); + secondUser.setLangKey(firstUser.getLangKey()); + secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); + + // Register second (non activated) user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().isCreated()); + + Optional testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); + assertThat(testUser2.isPresent()).isFalse(); + + Optional testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2"); + assertThat(testUser3.isPresent()).isTrue(); + + // Duplicate email - with uppercase email address + ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM(); + userWithUpperCaseEmail.setId(firstUser.getId()); + userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3"); + userWithUpperCaseEmail.setPassword(firstUser.getPassword()); + userWithUpperCaseEmail.setFirstName(firstUser.getFirstName()); + userWithUpperCaseEmail.setLastName(firstUser.getLastName()); + userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com"); + userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl()); + userWithUpperCaseEmail.setLangKey(firstUser.getLangKey()); + userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities())); + + // Register third (not activated) user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))) + .andExpect(status().isCreated()); + + Optional testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); + assertThat(testUser4.isPresent()).isTrue(); + assertThat(testUser4.get().getEmail()).isEqualTo("test-register-duplicate-email@example.com"); + + testUser4.get().setActivated(true); + userService.updateUser((new UserDTO(testUser4.get()))); + + // Register 4th (already activated) user + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().is4xxClientError()); + } + + @Test + @Transactional + public void testRegisterAdminIsIgnored() throws Exception { + ManagedUserVM validUser = new ManagedUserVM(); + validUser.setLogin("badguy"); + validUser.setPassword("password"); + validUser.setFirstName("Bad"); + validUser.setLastName("Guy"); + validUser.setEmail("badguy@example.com"); + validUser.setActivated(true); + validUser.setImageUrl("http://placehold.it/50x50"); + validUser.setLangKey(Constants.DEFAULT_LANGUAGE); + validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restMvc.perform( + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(validUser))) + .andExpect(status().isCreated()); + + Optional userDup = userRepository.findOneByLogin("badguy"); + assertThat(userDup.isPresent()).isTrue(); + assertThat(userDup.get().getAuthorities()).hasSize(1) + .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); + } + + @Test + @Transactional + public void testActivateAccount() throws Exception { + final String activationKey = "some activation key"; + User user = new User(); + user.setLogin("activate-account"); + user.setEmail("activate-account@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(false); + user.setActivationKey(activationKey); + + userRepository.saveAndFlush(user); + + restMvc.perform(get("/api/activate?key={activationKey}", activationKey)) + .andExpect(status().isOk()); + + user = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(user.getActivated()).isTrue(); + } + + @Test + @Transactional + public void testActivateAccountWithWrongKey() throws Exception { + restMvc.perform(get("/api/activate?key=wrongActivationKey")) + .andExpect(status().isInternalServerError()); + } + + @Test + @Transactional + @WithMockUser("save-account") + public void testSaveAccount() throws Exception { + User user = new User(); + user.setLogin("save-account"); + user.setEmail("save-account@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + + userRepository.saveAndFlush(user); + + UserDTO userDTO = new UserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("save-account@example.com"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restMvc.perform( + post("/api/account") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName()); + assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName()); + assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail()); + assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey()); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl()); + assertThat(updatedUser.getActivated()).isEqualTo(true); + assertThat(updatedUser.getAuthorities()).isEmpty(); + } + + @Test + @Transactional + @WithMockUser("save-invalid-email") + public void testSaveInvalidEmail() throws Exception { + User user = new User(); + user.setLogin("save-invalid-email"); + user.setEmail("save-invalid-email@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + + userRepository.saveAndFlush(user); + + UserDTO userDTO = new UserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("invalid email"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restMvc.perform( + post("/api/account") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isBadRequest()); + + Assertions.assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); + } + + @Test + @Transactional + @WithMockUser("save-existing-email") + public void testSaveExistingEmail() throws Exception { + User user = new User(); + user.setLogin("save-existing-email"); + user.setEmail("save-existing-email@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + + userRepository.saveAndFlush(user); + + User anotherUser = new User(); + anotherUser.setLogin("save-existing-email2"); + anotherUser.setEmail("save-existing-email2@example.com"); + anotherUser.setPassword(RandomStringUtils.random(60)); + anotherUser.setActivated(true); + + userRepository.saveAndFlush(anotherUser); + + UserDTO userDTO = new UserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("save-existing-email2@example.com"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restMvc.perform( + post("/api/account") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null); + assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com"); + } + + @Test + @Transactional + @WithMockUser("save-existing-email-and-login") + public void testSaveExistingEmailAndLogin() throws Exception { + User user = new User(); + user.setLogin("save-existing-email-and-login"); + user.setEmail("save-existing-email-and-login@example.com"); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + + userRepository.saveAndFlush(user); + + UserDTO userDTO = new UserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("save-existing-email-and-login@example.com"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); + + restMvc.perform( + post("/api/account") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null); + assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com"); + } + + @Test + @Transactional + @WithMockUser("change-password-wrong-existing-password") + public void testChangePasswordWrongExistingPassword() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-wrong-existing-password"); + user.setEmail("change-password-wrong-existing-password@example.com"); + userRepository.saveAndFlush(user); + + restMvc.perform(post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password")))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null); + assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse(); + assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue(); + } + + @Test + @Transactional + @WithMockUser("change-password") + public void testChangePassword() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password"); + user.setEmail("change-password@example.com"); + userRepository.saveAndFlush(user); + + restMvc.perform(post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password")))) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin("change-password").orElse(null); + assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue(); + } + + @Test + @Transactional + @WithMockUser("change-password-too-small") + public void testChangePasswordTooSmall() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-too-small"); + user.setEmail("change-password-too-small@example.com"); + userRepository.saveAndFlush(user); + + String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); + + restMvc.perform(post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + } + + @Test + @Transactional + @WithMockUser("change-password-too-long") + public void testChangePasswordTooLong() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-too-long"); + user.setEmail("change-password-too-long@example.com"); + userRepository.saveAndFlush(user); + + String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); + + restMvc.perform(post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + } + + @Test + @Transactional + @WithMockUser("change-password-empty") + public void testChangePasswordEmpty() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.random(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-empty"); + user.setEmail("change-password-empty@example.com"); + userRepository.saveAndFlush(user); + + restMvc.perform(post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + } + + @Test + @Transactional + public void testRequestPasswordReset() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setLogin("password-reset"); + user.setEmail("password-reset@example.com"); + userRepository.saveAndFlush(user); + + restMvc.perform(post("/api/account/reset-password/init") + .content("password-reset@example.com")) + .andExpect(status().isOk()); + } + + @Test + @Transactional + public void testRequestPasswordResetUpperCaseEmail() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setLogin("password-reset"); + user.setEmail("password-reset@example.com"); + userRepository.saveAndFlush(user); + + restMvc.perform(post("/api/account/reset-password/init") + .content("password-reset@EXAMPLE.COM")) + .andExpect(status().isOk()); + } + + @Test + public void testRequestPasswordResetWrongEmail() throws Exception { + restMvc.perform( + post("/api/account/reset-password/init") + .content("password-reset-wrong-email@example.com")) + .andExpect(status().isBadRequest()); + } + + @Test + @Transactional + public void testFinishPasswordReset() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.random(60)); + user.setLogin("finish-password-reset"); + user.setEmail("finish-password-reset@example.com"); + user.setResetDate(Instant.now().plusSeconds(60)); + user.setResetKey("reset key"); + userRepository.saveAndFlush(user); + + KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); + keyAndPassword.setKey(user.getResetKey()); + keyAndPassword.setNewPassword("new password"); + + restMvc.perform( + post("/api/account/reset-password/finish") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); + } + + @Test + @Transactional + public void testFinishPasswordResetTooSmall() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.random(60)); + user.setLogin("finish-password-reset-too-small"); + user.setEmail("finish-password-reset-too-small@example.com"); + user.setResetDate(Instant.now().plusSeconds(60)); + user.setResetKey("reset key too small"); + userRepository.saveAndFlush(user); + + KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); + keyAndPassword.setKey(user.getResetKey()); + keyAndPassword.setNewPassword("foo"); + + restMvc.perform( + post("/api/account/reset-password/finish") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse(); + } + + + @Test + @Transactional + public void testFinishPasswordResetWrongKey() throws Exception { + KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); + keyAndPassword.setKey("wrong reset key"); + keyAndPassword.setNewPassword("new password"); + + restMvc.perform( + post("/api/account/reset-password/finish") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) + .andExpect(status().isInternalServerError()); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/AccountResourceIntegrationTest.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/AccountResourceIntegrationTest.java index f591b7ecbfbd..adc7deec18bd 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/AccountResourceIntegrationTest.java @@ -1,21 +1,23 @@ -package com.baeldung.jhipster5.web.rest; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.config.Constants; -import com.baeldung.jhipster5.domain.Authority; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.AuthorityRepository; -import com.baeldung.jhipster5.repository.UserRepository; -import com.baeldung.jhipster5.security.AuthoritiesConstants; -import com.baeldung.jhipster5.service.MailService; -import com.baeldung.jhipster5.service.UserService; -import com.baeldung.jhipster5.service.dto.PasswordChangeDTO; -import com.baeldung.jhipster5.service.dto.UserDTO; -import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; -import com.baeldung.jhipster5.web.rest.vm.KeyAndPasswordVM; -import com.baeldung.jhipster5.web.rest.vm.ManagedUserVM; +package com.baeldung.jhipster6.web.rest; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.config.Constants; +import com.baeldung.jhipster6.domain.Authority; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.AuthorityRepository; +import com.baeldung.jhipster6.repository.UserRepository; +import com.baeldung.jhipster6.security.AuthoritiesConstants; +import com.baeldung.jhipster6.service.MailService; +import com.baeldung.jhipster6.service.UserService; +import com.baeldung.jhipster6.service.dto.PasswordChangeDTO; +import com.baeldung.jhipster6.service.dto.UserDTO; +import com.baeldung.jhipster6.web.rest.errors.ExceptionTranslator; +import com.baeldung.jhipster6.web.rest.vm.KeyAndPasswordVM; +import com.baeldung.jhipster6.web.rest.vm.ManagedUserVM; + import org.apache.commons.lang3.RandomStringUtils; +import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -533,7 +535,7 @@ public void testSaveInvalidEmail() throws Exception { .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isBadRequest()); - assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); + Assertions.assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); } @Test diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/AuditResourceIT.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/AuditResourceIT.java new file mode 100644 index 000000000000..d9c82f48a58e --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/AuditResourceIT.java @@ -0,0 +1,161 @@ +package com.baeldung.jhipster6.web.rest; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.config.audit.AuditEventConverter; +import com.baeldung.jhipster6.domain.PersistentAuditEvent; +import com.baeldung.jhipster6.repository.PersistenceAuditEventRepository; + +import com.baeldung.jhipster6.service.AuditEventService; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.web.PageableHandlerMethodArgumentResolver; +import org.springframework.format.support.FormattingConversionService; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Instant; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** + * Integration tests for the {@link AuditResource} REST controller. + */ +@SpringBootTest(classes = BookstoreApp.class) +@Transactional +public class AuditResourceIT { + + private static final String SAMPLE_PRINCIPAL = "SAMPLE_PRINCIPAL"; + private static final String SAMPLE_TYPE = "SAMPLE_TYPE"; + private static final Instant SAMPLE_TIMESTAMP = Instant.parse("2015-08-04T10:11:30Z"); + private static final long SECONDS_PER_DAY = 60 * 60 * 24; + + @Autowired + private PersistenceAuditEventRepository auditEventRepository; + + @Autowired + private AuditEventConverter auditEventConverter; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + @Qualifier("mvcConversionService") + private FormattingConversionService formattingConversionService; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + private PersistentAuditEvent auditEvent; + + private MockMvc restAuditMockMvc; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + AuditEventService auditEventService = + new AuditEventService(auditEventRepository, auditEventConverter); + AuditResource auditResource = new AuditResource(auditEventService); + this.restAuditMockMvc = MockMvcBuilders.standaloneSetup(auditResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setConversionService(formattingConversionService) + .setMessageConverters(jacksonMessageConverter).build(); + } + + @BeforeEach + public void initTest() { + auditEventRepository.deleteAll(); + auditEvent = new PersistentAuditEvent(); + auditEvent.setAuditEventType(SAMPLE_TYPE); + auditEvent.setPrincipal(SAMPLE_PRINCIPAL); + auditEvent.setAuditEventDate(SAMPLE_TIMESTAMP); + } + + @Test + public void getAllAudits() throws Exception { + // Initialize the database + auditEventRepository.save(auditEvent); + + // Get all the audits + restAuditMockMvc.perform(get("/management/audits")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); + } + + @Test + public void getAudit() throws Exception { + // Initialize the database + auditEventRepository.save(auditEvent); + + // Get the audit + restAuditMockMvc.perform(get("/management/audits/{id}", auditEvent.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL)); + } + + @Test + public void getAuditsByDate() throws Exception { + // Initialize the database + auditEventRepository.save(auditEvent); + + // Generate dates for selecting audits by date, making sure the period will contain the audit + String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); + String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); + + // Get the audit + restAuditMockMvc.perform(get("/management/audits?fromDate="+fromDate+"&toDate="+toDate)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); + } + + @Test + public void getNonExistingAuditsByDate() throws Exception { + // Initialize the database + auditEventRepository.save(auditEvent); + + // Generate dates for selecting audits by date, making sure the period will not contain the sample audit + String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0, 10); + String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); + + // Query audits but expect no results + restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(header().string("X-Total-Count", "0")); + } + + @Test + public void getNonExistingAudit() throws Exception { + // Get the audit + restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void testPersistentAuditEventEquals() throws Exception { + TestUtil.equalsVerifier(PersistentAuditEvent.class); + PersistentAuditEvent auditEvent1 = new PersistentAuditEvent(); + auditEvent1.setId(1L); + PersistentAuditEvent auditEvent2 = new PersistentAuditEvent(); + auditEvent2.setId(auditEvent1.getId()); + assertThat(auditEvent1).isEqualTo(auditEvent2); + auditEvent2.setId(2L); + assertThat(auditEvent1).isNotEqualTo(auditEvent2); + auditEvent1.setId(null); + assertThat(auditEvent1).isNotEqualTo(auditEvent2); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/AuditResourceIntegrationTest.java similarity index 95% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/AuditResourceIntegrationTest.java index 05d8f9d503be..d7bb995e1c29 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AuditResourceIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/AuditResourceIntegrationTest.java @@ -1,10 +1,11 @@ -package com.baeldung.jhipster5.web.rest; +package com.baeldung.jhipster6.web.rest; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.config.audit.AuditEventConverter; +import com.baeldung.jhipster6.domain.PersistentAuditEvent; +import com.baeldung.jhipster6.repository.PersistenceAuditEventRepository; +import com.baeldung.jhipster6.service.AuditEventService; -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.config.audit.AuditEventConverter; -import com.baeldung.jhipster5.domain.PersistentAuditEvent; -import com.baeldung.jhipster5.repository.PersistenceAuditEventRepository; -import com.baeldung.jhipster5.service.AuditEventService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/BookResourceIntegrationTest.java similarity index 96% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/BookResourceIntegrationTest.java index 4f5cb25cdb85..429d937f265c 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/BookResourceIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/BookResourceIntegrationTest.java @@ -1,13 +1,13 @@ -package com.baeldung.jhipster5.web.rest; +package com.baeldung.jhipster6.web.rest; -import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster6.BookstoreApp; -import com.baeldung.jhipster5.domain.Book; -import com.baeldung.jhipster5.repository.BookRepository; -import com.baeldung.jhipster5.service.BookService; -import com.baeldung.jhipster5.service.dto.BookDTO; -import com.baeldung.jhipster5.service.mapper.BookMapper; -import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; +import com.baeldung.jhipster6.domain.Book; +import com.baeldung.jhipster6.repository.BookRepository; +import com.baeldung.jhipster6.service.BookService; +import com.baeldung.jhipster6.service.dto.BookDTO; +import com.baeldung.jhipster6.service.mapper.BookMapper; +import com.baeldung.jhipster6.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; @@ -29,8 +29,6 @@ import java.time.ZoneId; import java.util.List; - -import static com.baeldung.jhipster5.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; @@ -95,7 +93,7 @@ public void setup() { this.restBookMockMvc = MockMvcBuilders.standaloneSetup(bookResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) - .setConversionService(createFormattingConversionService()) + .setConversionService(TestUtil.createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter) .setValidator(validator).build(); } @@ -276,7 +274,7 @@ public void getAllBooks() throws Exception { .andExpect(jsonPath("$.[*].quantity").value(hasItem(DEFAULT_QUANTITY))) .andExpect(jsonPath("$.[*].price").value(hasItem(DEFAULT_PRICE.doubleValue()))); } - + @Test @Transactional public void getBook() throws Exception { diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/ClientForwardControllerIT.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/ClientForwardControllerIT.java new file mode 100644 index 000000000000..9dcc2e605504 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/ClientForwardControllerIT.java @@ -0,0 +1,67 @@ +package com.baeldung.jhipster6.web.rest; + +import com.baeldung.jhipster6.BookstoreApp; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Integration tests for the {@link ClientForwardController} REST controller. + */ +@SpringBootTest(classes = BookstoreApp.class) +public class ClientForwardControllerIT { + + private MockMvc restMockMvc; + + @BeforeEach + public void setup() { + ClientForwardController clientForwardController = new ClientForwardController(); + this.restMockMvc = MockMvcBuilders + .standaloneSetup(clientForwardController, new TestController()) + .build(); + } + + @Test + public void getBackendEndpoint() throws Exception { + restMockMvc.perform(get("/test")) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN_VALUE)) + .andExpect(content().string("test")); + } + + @Test + public void getClientEndpoint() throws Exception { + ResultActions perform = restMockMvc.perform(get("/non-existant-mapping")); + perform + .andExpect(status().isOk()) + .andExpect(forwardedUrl("/")); + } + + @Test + public void getNestedClientEndpoint() throws Exception { + restMockMvc.perform(get("/admin/user-management")) + .andExpect(status().isOk()) + .andExpect(forwardedUrl("/")); + } + + @RestController + public static class TestController { + + @RequestMapping(value = "/test") + public String test() { + return "test"; + } + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/LogsResourceIntegrationTest.java similarity index 94% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/LogsResourceIntegrationTest.java index b045f52f873e..a9aa9b27c161 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/LogsResourceIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/LogsResourceIntegrationTest.java @@ -1,7 +1,8 @@ -package com.baeldung.jhipster5.web.rest; +package com.baeldung.jhipster6.web.rest; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.web.rest.vm.LoggerVM; -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.web.rest.vm.LoggerVM; import ch.qos.logback.classic.AsyncAppender; import ch.qos.logback.classic.LoggerContext; import org.junit.Before; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/TestUtil.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/TestUtil.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/TestUtil.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/TestUtil.java index 403bb9c9b046..50c6cc24a661 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/TestUtil.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/TestUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest; +package com.baeldung.jhipster6.web.rest; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/UserJWTControllerIT.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/UserJWTControllerIT.java new file mode 100644 index 000000000000..3ad59b31669e --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/UserJWTControllerIT.java @@ -0,0 +1,120 @@ +package com.baeldung.jhipster6.web.rest; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.UserRepository; +import com.baeldung.jhipster6.security.jwt.TokenProvider; +import com.baeldung.jhipster6.web.rest.errors.ExceptionTranslator; +import com.baeldung.jhipster6.web.rest.vm.LoginVM; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; + +/** + * Integration tests for the {@link UserJWTController} REST controller. + */ +@SpringBootTest(classes = BookstoreApp.class) +public class UserJWTControllerIT { + + @Autowired + private TokenProvider tokenProvider; + + @Autowired + private AuthenticationManager authenticationManager; + + @Autowired + private UserRepository userRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + UserJWTController userJWTController = new UserJWTController(tokenProvider, authenticationManager); + this.mockMvc = MockMvcBuilders.standaloneSetup(userJWTController) + .setControllerAdvice(exceptionTranslator) + .build(); + } + + @Test + @Transactional + public void testAuthorize() throws Exception { + User user = new User(); + user.setLogin("user-jwt-controller"); + user.setEmail("user-jwt-controller@example.com"); + user.setActivated(true); + user.setPassword(passwordEncoder.encode("test")); + + userRepository.saveAndFlush(user); + + LoginVM login = new LoginVM(); + login.setUsername("user-jwt-controller"); + login.setPassword("test"); + mockMvc.perform(post("/api/authenticate") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(login))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id_token").isString()) + .andExpect(jsonPath("$.id_token").isNotEmpty()) + .andExpect(header().string("Authorization", not(nullValue()))) + .andExpect(header().string("Authorization", not(isEmptyString()))); + } + + @Test + @Transactional + public void testAuthorizeWithRememberMe() throws Exception { + User user = new User(); + user.setLogin("user-jwt-controller-remember-me"); + user.setEmail("user-jwt-controller-remember-me@example.com"); + user.setActivated(true); + user.setPassword(passwordEncoder.encode("test")); + + userRepository.saveAndFlush(user); + + LoginVM login = new LoginVM(); + login.setUsername("user-jwt-controller-remember-me"); + login.setPassword("test"); + login.setRememberMe(true); + mockMvc.perform(post("/api/authenticate") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(login))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id_token").isString()) + .andExpect(jsonPath("$.id_token").isNotEmpty()) + .andExpect(header().string("Authorization", not(nullValue()))) + .andExpect(header().string("Authorization", not(isEmptyString()))); + } + + @Test + public void testAuthorizeFails() throws Exception { + LoginVM login = new LoginVM(); + login.setUsername("wrong-user"); + login.setPassword("wrong password"); + mockMvc.perform(post("/api/authenticate") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(login))) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.id_token").doesNotExist()) + .andExpect(header().doesNotExist("Authorization")); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/UserJWTControllerIntegrationTest.java similarity index 92% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/UserJWTControllerIntegrationTest.java index 7cfc0e19fc2f..bf62d29f1b54 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserJWTControllerIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/UserJWTControllerIntegrationTest.java @@ -1,11 +1,12 @@ -package com.baeldung.jhipster5.web.rest; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.UserRepository; -import com.baeldung.jhipster5.security.jwt.TokenProvider; -import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; -import com.baeldung.jhipster5.web.rest.vm.LoginVM; +package com.baeldung.jhipster6.web.rest; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.UserRepository; +import com.baeldung.jhipster6.security.jwt.TokenProvider; +import com.baeldung.jhipster6.web.rest.errors.ExceptionTranslator; +import com.baeldung.jhipster6.web.rest.vm.LoginVM; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/UserResourceIT.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/UserResourceIT.java new file mode 100644 index 000000000000..420dcbbd77b0 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/UserResourceIT.java @@ -0,0 +1,592 @@ +package com.baeldung.jhipster6.web.rest; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.domain.Authority; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.UserRepository; +import com.baeldung.jhipster6.security.AuthoritiesConstants; +import com.baeldung.jhipster6.service.MailService; +import com.baeldung.jhipster6.service.UserService; +import com.baeldung.jhipster6.service.dto.UserDTO; +import com.baeldung.jhipster6.service.mapper.UserMapper; +import com.baeldung.jhipster6.web.rest.errors.ExceptionTranslator; +import com.baeldung.jhipster6.web.rest.vm.ManagedUserVM; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.web.PageableHandlerMethodArgumentResolver; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityManager; +import java.time.Instant; +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** + * Integration tests for the {@link UserResource} REST controller. + */ +@SpringBootTest(classes = BookstoreApp.class) +public class UserResourceIT { + + private static final String DEFAULT_LOGIN = "johndoe"; + private static final String UPDATED_LOGIN = "jhipster"; + + private static final Long DEFAULT_ID = 1L; + + private static final String DEFAULT_PASSWORD = "passjohndoe"; + private static final String UPDATED_PASSWORD = "passjhipster"; + + private static final String DEFAULT_EMAIL = "johndoe@localhost"; + private static final String UPDATED_EMAIL = "jhipster@localhost"; + + private static final String DEFAULT_FIRSTNAME = "john"; + private static final String UPDATED_FIRSTNAME = "jhipsterFirstName"; + + private static final String DEFAULT_LASTNAME = "doe"; + private static final String UPDATED_LASTNAME = "jhipsterLastName"; + + private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50"; + private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40"; + + private static final String DEFAULT_LANGKEY = "en"; + private static final String UPDATED_LANGKEY = "fr"; + + @Autowired + private UserRepository userRepository; + + @Autowired + private MailService mailService; + + @Autowired + private UserService userService; + + @Autowired + private UserMapper userMapper; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + private MockMvc restUserMockMvc; + + private User user; + + @BeforeEach + public void setup() { + UserResource userResource = new UserResource(userService, userRepository, mailService); + + this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setMessageConverters(jacksonMessageConverter) + .build(); + } + + /** + * Create a User. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which has a required relationship to the User entity. + */ + public static User createEntity(EntityManager em) { + User user = new User(); + user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5)); + user.setPassword(RandomStringUtils.random(60)); + user.setActivated(true); + user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL); + user.setFirstName(DEFAULT_FIRSTNAME); + user.setLastName(DEFAULT_LASTNAME); + user.setImageUrl(DEFAULT_IMAGEURL); + user.setLangKey(DEFAULT_LANGKEY); + return user; + } + + @BeforeEach + public void initTest() { + user = createEntity(em); + user.setLogin(DEFAULT_LOGIN); + user.setEmail(DEFAULT_EMAIL); + } + + @Test + @Transactional + public void createUser() throws Exception { + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + // Create the User + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setLogin(DEFAULT_LOGIN); + managedUserVM.setPassword(DEFAULT_PASSWORD); + managedUserVM.setFirstName(DEFAULT_FIRSTNAME); + managedUserVM.setLastName(DEFAULT_LASTNAME); + managedUserVM.setEmail(DEFAULT_EMAIL); + managedUserVM.setActivated(true); + managedUserVM.setImageUrl(DEFAULT_IMAGEURL); + managedUserVM.setLangKey(DEFAULT_LANGKEY); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform(post("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isCreated()); + + // Validate the User in the database + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeCreate + 1); + User testUser = userList.get(userList.size() - 1); + assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN); + assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY); + } + + @Test + @Transactional + public void createUserWithExistingId() throws Exception { + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(1L); + managedUserVM.setLogin(DEFAULT_LOGIN); + managedUserVM.setPassword(DEFAULT_PASSWORD); + managedUserVM.setFirstName(DEFAULT_FIRSTNAME); + managedUserVM.setLastName(DEFAULT_LASTNAME); + managedUserVM.setEmail(DEFAULT_EMAIL); + managedUserVM.setActivated(true); + managedUserVM.setImageUrl(DEFAULT_IMAGEURL); + managedUserVM.setLangKey(DEFAULT_LANGKEY); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // An entity with an existing ID cannot be created, so this API call must fail + restUserMockMvc.perform(post("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + + // Validate the User in the database + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeCreate); + } + + @Test + @Transactional + public void createUserWithExistingLogin() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setLogin(DEFAULT_LOGIN);// this login should already be used + managedUserVM.setPassword(DEFAULT_PASSWORD); + managedUserVM.setFirstName(DEFAULT_FIRSTNAME); + managedUserVM.setLastName(DEFAULT_LASTNAME); + managedUserVM.setEmail("anothermail@localhost"); + managedUserVM.setActivated(true); + managedUserVM.setImageUrl(DEFAULT_IMAGEURL); + managedUserVM.setLangKey(DEFAULT_LANGKEY); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // Create the User + restUserMockMvc.perform(post("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + + // Validate the User in the database + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeCreate); + } + + @Test + @Transactional + public void createUserWithExistingEmail() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setLogin("anotherlogin"); + managedUserVM.setPassword(DEFAULT_PASSWORD); + managedUserVM.setFirstName(DEFAULT_FIRSTNAME); + managedUserVM.setLastName(DEFAULT_LASTNAME); + managedUserVM.setEmail(DEFAULT_EMAIL);// this email should already be used + managedUserVM.setActivated(true); + managedUserVM.setImageUrl(DEFAULT_IMAGEURL); + managedUserVM.setLangKey(DEFAULT_LANGKEY); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + // Create the User + restUserMockMvc.perform(post("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + + // Validate the User in the database + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeCreate); + } + + @Test + @Transactional + public void getAllUsers() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + // Get all the users + restUserMockMvc.perform(get("/api/users?sort=id,desc") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN))) + .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME))) + .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME))) + .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) + .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL))) + .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY))); + } + + @Test + @Transactional + public void getUser() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + // Get the user + restUserMockMvc.perform(get("/api/users/{login}", user.getLogin())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.login").value(user.getLogin())) + .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME)) + .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME)) + .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL)) + .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL)) + .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY)); + } + + @Test + @Transactional + public void getNonExistingUser() throws Exception { + restUserMockMvc.perform(get("/api/users/unknown")) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateUser() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeUpdate = userRepository.findAll().size(); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).get(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(updatedUser.getId()); + managedUserVM.setLogin(updatedUser.getLogin()); + managedUserVM.setPassword(UPDATED_PASSWORD); + managedUserVM.setFirstName(UPDATED_FIRSTNAME); + managedUserVM.setLastName(UPDATED_LASTNAME); + managedUserVM.setEmail(UPDATED_EMAIL); + managedUserVM.setActivated(updatedUser.getActivated()); + managedUserVM.setImageUrl(UPDATED_IMAGEURL); + managedUserVM.setLangKey(UPDATED_LANGKEY); + managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); + managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); + managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); + managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform(put("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isOk()); + + // Validate the User in the database + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeUpdate); + User testUser = userList.get(userList.size() - 1); + assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); + } + + @Test + @Transactional + public void updateUserLogin() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeUpdate = userRepository.findAll().size(); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).get(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(updatedUser.getId()); + managedUserVM.setLogin(UPDATED_LOGIN); + managedUserVM.setPassword(UPDATED_PASSWORD); + managedUserVM.setFirstName(UPDATED_FIRSTNAME); + managedUserVM.setLastName(UPDATED_LASTNAME); + managedUserVM.setEmail(UPDATED_EMAIL); + managedUserVM.setActivated(updatedUser.getActivated()); + managedUserVM.setImageUrl(UPDATED_IMAGEURL); + managedUserVM.setLangKey(UPDATED_LANGKEY); + managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); + managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); + managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); + managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform(put("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isOk()); + + // Validate the User in the database + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeUpdate); + User testUser = userList.get(userList.size() - 1); + assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN); + assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); + } + + @Test + @Transactional + public void updateUserExistingEmail() throws Exception { + // Initialize the database with 2 users + userRepository.saveAndFlush(user); + + User anotherUser = new User(); + anotherUser.setLogin("jhipster"); + anotherUser.setPassword(RandomStringUtils.random(60)); + anotherUser.setActivated(true); + anotherUser.setEmail("jhipster@localhost"); + anotherUser.setFirstName("java"); + anotherUser.setLastName("hipster"); + anotherUser.setImageUrl(""); + anotherUser.setLangKey("en"); + userRepository.saveAndFlush(anotherUser); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).get(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(updatedUser.getId()); + managedUserVM.setLogin(updatedUser.getLogin()); + managedUserVM.setPassword(updatedUser.getPassword()); + managedUserVM.setFirstName(updatedUser.getFirstName()); + managedUserVM.setLastName(updatedUser.getLastName()); + managedUserVM.setEmail("jhipster@localhost");// this email should already be used by anotherUser + managedUserVM.setActivated(updatedUser.getActivated()); + managedUserVM.setImageUrl(updatedUser.getImageUrl()); + managedUserVM.setLangKey(updatedUser.getLangKey()); + managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); + managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); + managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); + managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform(put("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + } + + @Test + @Transactional + public void updateUserExistingLogin() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + User anotherUser = new User(); + anotherUser.setLogin("jhipster"); + anotherUser.setPassword(RandomStringUtils.random(60)); + anotherUser.setActivated(true); + anotherUser.setEmail("jhipster@localhost"); + anotherUser.setFirstName("java"); + anotherUser.setLastName("hipster"); + anotherUser.setImageUrl(""); + anotherUser.setLangKey("en"); + userRepository.saveAndFlush(anotherUser); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).get(); + + ManagedUserVM managedUserVM = new ManagedUserVM(); + managedUserVM.setId(updatedUser.getId()); + managedUserVM.setLogin("jhipster");// this login should already be used by anotherUser + managedUserVM.setPassword(updatedUser.getPassword()); + managedUserVM.setFirstName(updatedUser.getFirstName()); + managedUserVM.setLastName(updatedUser.getLastName()); + managedUserVM.setEmail(updatedUser.getEmail()); + managedUserVM.setActivated(updatedUser.getActivated()); + managedUserVM.setImageUrl(updatedUser.getImageUrl()); + managedUserVM.setLangKey(updatedUser.getLangKey()); + managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); + managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); + managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); + managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); + managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + restUserMockMvc.perform(put("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); + } + + @Test + @Transactional + public void deleteUser() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeDelete = userRepository.findAll().size(); + + // Delete the user + restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isNoContent()); + + // Validate the database is empty + List userList = userRepository.findAll(); + assertThat(userList).hasSize(databaseSizeBeforeDelete - 1); + } + + @Test + @Transactional + public void getAllAuthorities() throws Exception { + restUserMockMvc.perform(get("/api/users/authorities") + .accept(TestUtil.APPLICATION_JSON_UTF8) + .contentType(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$").isArray()) + .andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN))); + } + + @Test + @Transactional + public void testUserEquals() throws Exception { + TestUtil.equalsVerifier(User.class); + User user1 = new User(); + user1.setId(1L); + User user2 = new User(); + user2.setId(user1.getId()); + assertThat(user1).isEqualTo(user2); + user2.setId(2L); + assertThat(user1).isNotEqualTo(user2); + user1.setId(null); + assertThat(user1).isNotEqualTo(user2); + } + + @Test + public void testUserDTOtoUser() { + UserDTO userDTO = new UserDTO(); + userDTO.setId(DEFAULT_ID); + userDTO.setLogin(DEFAULT_LOGIN); + userDTO.setFirstName(DEFAULT_FIRSTNAME); + userDTO.setLastName(DEFAULT_LASTNAME); + userDTO.setEmail(DEFAULT_EMAIL); + userDTO.setActivated(true); + userDTO.setImageUrl(DEFAULT_IMAGEURL); + userDTO.setLangKey(DEFAULT_LANGKEY); + userDTO.setCreatedBy(DEFAULT_LOGIN); + userDTO.setLastModifiedBy(DEFAULT_LOGIN); + userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + + User user = userMapper.userDTOToUser(userDTO); + assertThat(user.getId()).isEqualTo(DEFAULT_ID); + assertThat(user.getLogin()).isEqualTo(DEFAULT_LOGIN); + assertThat(user.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); + assertThat(user.getLastName()).isEqualTo(DEFAULT_LASTNAME); + assertThat(user.getEmail()).isEqualTo(DEFAULT_EMAIL); + assertThat(user.getActivated()).isEqualTo(true); + assertThat(user.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); + assertThat(user.getLangKey()).isEqualTo(DEFAULT_LANGKEY); + assertThat(user.getCreatedBy()).isNull(); + assertThat(user.getCreatedDate()).isNotNull(); + assertThat(user.getLastModifiedBy()).isNull(); + assertThat(user.getLastModifiedDate()).isNotNull(); + assertThat(user.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER); + } + + @Test + public void testUserToUserDTO() { + user.setId(DEFAULT_ID); + user.setCreatedBy(DEFAULT_LOGIN); + user.setCreatedDate(Instant.now()); + user.setLastModifiedBy(DEFAULT_LOGIN); + user.setLastModifiedDate(Instant.now()); + Set authorities = new HashSet<>(); + Authority authority = new Authority(); + authority.setName(AuthoritiesConstants.USER); + authorities.add(authority); + user.setAuthorities(authorities); + + UserDTO userDTO = userMapper.userToUserDTO(user); + + assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID); + assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN); + assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); + assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME); + assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL); + assertThat(userDTO.isActivated()).isEqualTo(true); + assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); + assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY); + assertThat(userDTO.getCreatedBy()).isEqualTo(DEFAULT_LOGIN); + assertThat(userDTO.getCreatedDate()).isEqualTo(user.getCreatedDate()); + assertThat(userDTO.getLastModifiedBy()).isEqualTo(DEFAULT_LOGIN); + assertThat(userDTO.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate()); + assertThat(userDTO.getAuthorities()).containsExactly(AuthoritiesConstants.USER); + assertThat(userDTO.toString()).isNotNull(); + } + + @Test + public void testAuthorityEquals() { + Authority authorityA = new Authority(); + assertThat(authorityA).isEqualTo(authorityA); + assertThat(authorityA).isNotEqualTo(null); + assertThat(authorityA).isNotEqualTo(new Object()); + assertThat(authorityA.hashCode()).isEqualTo(0); + assertThat(authorityA.toString()).isNotNull(); + + Authority authorityB = new Authority(); + assertThat(authorityA).isEqualTo(authorityB); + + authorityB.setName(AuthoritiesConstants.ADMIN); + assertThat(authorityA).isNotEqualTo(authorityB); + + authorityA.setName(AuthoritiesConstants.USER); + assertThat(authorityA).isNotEqualTo(authorityB); + + authorityB.setName(AuthoritiesConstants.USER); + assertThat(authorityA).isEqualTo(authorityB); + assertThat(authorityA.hashCode()).isEqualTo(authorityB.hashCode()); + } +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/UserResourceIntegrationTest.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/UserResourceIntegrationTest.java index c0abc042fbe9..20d8d4a85cdf 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/UserResourceIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/UserResourceIntegrationTest.java @@ -1,16 +1,17 @@ -package com.baeldung.jhipster5.web.rest; - -import com.baeldung.jhipster5.BookstoreApp; -import com.baeldung.jhipster5.domain.Authority; -import com.baeldung.jhipster5.domain.User; -import com.baeldung.jhipster5.repository.UserRepository; -import com.baeldung.jhipster5.security.AuthoritiesConstants; -import com.baeldung.jhipster5.service.MailService; -import com.baeldung.jhipster5.service.UserService; -import com.baeldung.jhipster5.service.dto.UserDTO; -import com.baeldung.jhipster5.service.mapper.UserMapper; -import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; -import com.baeldung.jhipster5.web.rest.vm.ManagedUserVM; +package com.baeldung.jhipster6.web.rest; + +import com.baeldung.jhipster6.BookstoreApp; +import com.baeldung.jhipster6.domain.Authority; +import com.baeldung.jhipster6.domain.User; +import com.baeldung.jhipster6.repository.UserRepository; +import com.baeldung.jhipster6.security.AuthoritiesConstants; +import com.baeldung.jhipster6.service.MailService; +import com.baeldung.jhipster6.service.UserService; +import com.baeldung.jhipster6.service.dto.UserDTO; +import com.baeldung.jhipster6.service.mapper.UserMapper; +import com.baeldung.jhipster6.web.rest.errors.ExceptionTranslator; +import com.baeldung.jhipster6.web.rest.vm.ManagedUserVM; + import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; diff --git a/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/errors/ExceptionTranslatorIT.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/errors/ExceptionTranslatorIT.java new file mode 100644 index 000000000000..2ecbe7254ed1 --- /dev/null +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/errors/ExceptionTranslatorIT.java @@ -0,0 +1,125 @@ +package com.baeldung.jhipster6.web.rest.errors; + +import com.baeldung.jhipster6.BookstoreApp; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Integration tests {@link ExceptionTranslator} controller advice. + */ +@SpringBootTest(classes = BookstoreApp.class) +public class ExceptionTranslatorIT { + + @Autowired + private ExceptionTranslatorTestController controller; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + mockMvc = MockMvcBuilders.standaloneSetup(controller) + .setControllerAdvice(exceptionTranslator) + .setMessageConverters(jacksonMessageConverter) + .build(); + } + + @Test + public void testConcurrencyFailure() throws Exception { + mockMvc.perform(get("/test/concurrency-failure")) + .andExpect(status().isConflict()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); + } + + @Test + public void testMethodArgumentNotValid() throws Exception { + mockMvc.perform(post("/test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION)) + .andExpect(jsonPath("$.fieldErrors.[0].objectName").value("testDTO")) + .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) + .andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull")); + } + + @Test + public void testMissingServletRequestPartException() throws Exception { + mockMvc.perform(get("/test/missing-servlet-request-part")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")); + } + + @Test + public void testMissingServletRequestParameterException() throws Exception { + mockMvc.perform(get("/test/missing-servlet-request-parameter")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")); + } + + @Test + public void testAccessDenied() throws Exception { + mockMvc.perform(get("/test/access-denied")) + .andExpect(status().isForbidden()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.403")) + .andExpect(jsonPath("$.detail").value("test access denied!")); + } + + @Test + public void testUnauthorized() throws Exception { + mockMvc.perform(get("/test/unauthorized")) + .andExpect(status().isUnauthorized()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.401")) + .andExpect(jsonPath("$.path").value("/test/unauthorized")) + .andExpect(jsonPath("$.detail").value("test authentication failed!")); + } + + @Test + public void testMethodNotSupported() throws Exception { + mockMvc.perform(post("/test/access-denied")) + .andExpect(status().isMethodNotAllowed()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.405")) + .andExpect(jsonPath("$.detail").value("Request method 'POST' not supported")); + } + + @Test + public void testExceptionWithResponseStatus() throws Exception { + mockMvc.perform(get("/test/response-status")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")) + .andExpect(jsonPath("$.title").value("test response status")); + } + + @Test + public void testInternalServerError() throws Exception { + mockMvc.perform(get("/test/internal-server-error")) + .andExpect(status().isInternalServerError()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.500")) + .andExpect(jsonPath("$.title").value("Internal Server Error")); + } + +} diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntegrationTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/errors/ExceptionTranslatorIntegrationTest.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntegrationTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/errors/ExceptionTranslatorIntegrationTest.java index e5ef08ee9cea..7b25b314edc5 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorIntegrationTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/errors/ExceptionTranslatorIntegrationTest.java @@ -1,6 +1,6 @@ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; -import com.baeldung.jhipster5.BookstoreApp; +import com.baeldung.jhipster6.BookstoreApp; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorTestController.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/errors/ExceptionTranslatorTestController.java similarity index 98% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorTestController.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/errors/ExceptionTranslatorTestController.java index f8d84151b903..a0e6e0317804 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/errors/ExceptionTranslatorTestController.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/errors/ExceptionTranslatorTestController.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.errors; +package com.baeldung.jhipster6.web.rest.errors; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.HttpStatus; diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/util/PaginationUtilUnitTest.java b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/util/PaginationUtilUnitTest.java similarity index 97% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/util/PaginationUtilUnitTest.java rename to jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/util/PaginationUtilUnitTest.java index 78b17ee8595a..da7c2ae1f52c 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/util/PaginationUtilUnitTest.java +++ b/jhipster-6/bookstore-monolith/src/test/java/com/baeldung/jhipster6/web/rest/util/PaginationUtilUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jhipster5.web.rest.util; +package com.baeldung.jhipster6.web.rest.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/jest-global-mocks.ts b/jhipster-6/bookstore-monolith/src/test/javascript/jest-global-mocks.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/jest-global-mocks.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/jest-global-mocks.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/jest.conf.js b/jhipster-6/bookstore-monolith/src/test/javascript/jest.conf.js similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/jest.conf.js rename to jhipster-6/bookstore-monolith/src/test/javascript/jest.conf.js diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/jest.ts b/jhipster-6/bookstore-monolith/src/test/javascript/jest.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/jest.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/jest.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/activate/activate.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/activate/activate.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/activate/activate.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/activate/activate.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/password-reset/finish/password-reset-finish.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/password-reset/finish/password-reset-finish.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/password-reset/finish/password-reset-finish.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/password-reset/finish/password-reset-finish.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/password-reset/init/password-reset-init.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/password-reset/init/password-reset-init.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/password-reset/init/password-reset-init.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/password-reset/init/password-reset-init.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/password/password-strength-bar.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/password/password-strength-bar.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/password/password-strength-bar.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/password/password-strength-bar.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/password/password.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/password/password.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/password/password.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/password/password.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/register/register.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/register/register.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/register/register.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/register/register.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/settings/settings.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/settings/settings.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/account/settings/settings.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/account/settings/settings.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/audits/audits.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/audits/audits.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/audits/audits.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/audits/audits.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/audits/audits.service.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/audits/audits.service.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/audits/audits.service.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/audits/audits.service.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/configuration/configuration.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/configuration/configuration.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/configuration/configuration.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/configuration/configuration.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/configuration/configuration.service.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/configuration/configuration.service.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/configuration/configuration.service.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/configuration/configuration.service.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/health/health.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/health/health.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/health/health.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/health/health.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/metrics/metrics.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/metrics/metrics.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/metrics/metrics.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/metrics/metrics.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/metrics/metrics.service.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/metrics/metrics.service.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/metrics/metrics.service.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/metrics/metrics.service.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management-delete-dialog.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management-delete-dialog.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management-delete-dialog.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management-delete-dialog.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management-detail.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management-detail.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management-detail.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management-detail.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management-update.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management-update.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management-update.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management-update.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/admin/user-management/user-management.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/core/user/account.service.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/core/user/account.service.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/core/user/account.service.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/core/user/account.service.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/core/user/user.service.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/core/user/user.service.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/core/user/user.service.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/core/user/user.service.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/entities/book/book-delete-dialog.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/entities/book/book-delete-dialog.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/entities/book/book-delete-dialog.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/entities/book/book-delete-dialog.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/entities/book/book-detail.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/entities/book/book-detail.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/entities/book/book-detail.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/entities/book/book-detail.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/entities/book/book-update.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/entities/book/book-update.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/entities/book/book-update.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/entities/book/book-update.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/entities/book/book.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/entities/book/book.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/entities/book/book.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/entities/book/book.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/entities/book/book.service.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/entities/book/book.service.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/entities/book/book.service.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/entities/book/book.service.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/shared/alert/alert-error.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/shared/alert/alert-error.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/shared/alert/alert-error.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/shared/alert/alert-error.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/shared/login/login.component.spec.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/app/shared/login/login.component.spec.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/app/shared/login/login.component.spec.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/app/shared/login/login.component.spec.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-account.service.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-account.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-account.service.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-account.service.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-active-modal.service.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-active-modal.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-active-modal.service.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-active-modal.service.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-alert.service.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-alert.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-alert.service.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-alert.service.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-event-manager.service.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-event-manager.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-event-manager.service.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-event-manager.service.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-login.service.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-login.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-login.service.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-login.service.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-route.service.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-route.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-route.service.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-route.service.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-state-storage.service.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-state-storage.service.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/mock-state-storage.service.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/mock-state-storage.service.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/spyobject.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/spyobject.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/helpers/spyobject.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/helpers/spyobject.ts diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/test.module.ts b/jhipster-6/bookstore-monolith/src/test/javascript/spec/test.module.ts similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/javascript/spec/test.module.ts rename to jhipster-6/bookstore-monolith/src/test/javascript/spec/test.module.ts diff --git a/jhipster-5/bookstore-monolith/src/test/resources/config/application.yml b/jhipster-6/bookstore-monolith/src/test/resources/config/application.yml similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/resources/config/application.yml rename to jhipster-6/bookstore-monolith/src/test/resources/config/application.yml diff --git a/jhipster-5/bookstore-monolith/src/test/resources/i18n/messages_en.properties b/jhipster-6/bookstore-monolith/src/test/resources/i18n/messages_en.properties similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/resources/i18n/messages_en.properties rename to jhipster-6/bookstore-monolith/src/test/resources/i18n/messages_en.properties diff --git a/jhipster-5/bookstore-monolith/src/test/resources/logback.xml b/jhipster-6/bookstore-monolith/src/test/resources/logback.xml similarity index 97% rename from jhipster-5/bookstore-monolith/src/test/resources/logback.xml rename to jhipster-6/bookstore-monolith/src/test/resources/logback.xml index 6244807dfae0..de8cf57b93c3 100644 --- a/jhipster-5/bookstore-monolith/src/test/resources/logback.xml +++ b/jhipster-6/bookstore-monolith/src/test/resources/logback.xml @@ -10,7 +10,7 @@ - + diff --git a/jhipster-5/bookstore-monolith/src/test/resources/templates/mail/testEmail.html b/jhipster-6/bookstore-monolith/src/test/resources/templates/mail/testEmail.html similarity index 100% rename from jhipster-5/bookstore-monolith/src/test/resources/templates/mail/testEmail.html rename to jhipster-6/bookstore-monolith/src/test/resources/templates/mail/testEmail.html diff --git a/jhipster-5/bookstore-monolith/tsconfig-aot.json b/jhipster-6/bookstore-monolith/tsconfig-aot.json similarity index 100% rename from jhipster-5/bookstore-monolith/tsconfig-aot.json rename to jhipster-6/bookstore-monolith/tsconfig-aot.json diff --git a/jhipster-5/bookstore-monolith/tsconfig.json b/jhipster-6/bookstore-monolith/tsconfig.json similarity index 100% rename from jhipster-5/bookstore-monolith/tsconfig.json rename to jhipster-6/bookstore-monolith/tsconfig.json diff --git a/jhipster-5/bookstore-monolith/tslint.json b/jhipster-6/bookstore-monolith/tslint.json similarity index 100% rename from jhipster-5/bookstore-monolith/tslint.json rename to jhipster-6/bookstore-monolith/tslint.json diff --git a/jhipster-5/bookstore-monolith/webpack/logo-jhipster.png b/jhipster-6/bookstore-monolith/webpack/logo-jhipster.png similarity index 100% rename from jhipster-5/bookstore-monolith/webpack/logo-jhipster.png rename to jhipster-6/bookstore-monolith/webpack/logo-jhipster.png diff --git a/jhipster-5/bookstore-monolith/webpack/utils.js b/jhipster-6/bookstore-monolith/webpack/utils.js similarity index 100% rename from jhipster-5/bookstore-monolith/webpack/utils.js rename to jhipster-6/bookstore-monolith/webpack/utils.js diff --git a/jhipster-5/bookstore-monolith/webpack/webpack.common.js b/jhipster-6/bookstore-monolith/webpack/webpack.common.js similarity index 100% rename from jhipster-5/bookstore-monolith/webpack/webpack.common.js rename to jhipster-6/bookstore-monolith/webpack/webpack.common.js diff --git a/jhipster-5/bookstore-monolith/webpack/webpack.dev.js b/jhipster-6/bookstore-monolith/webpack/webpack.dev.js similarity index 100% rename from jhipster-5/bookstore-monolith/webpack/webpack.dev.js rename to jhipster-6/bookstore-monolith/webpack/webpack.dev.js diff --git a/jhipster-5/bookstore-monolith/webpack/webpack.prod.js b/jhipster-6/bookstore-monolith/webpack/webpack.prod.js similarity index 100% rename from jhipster-5/bookstore-monolith/webpack/webpack.prod.js rename to jhipster-6/bookstore-monolith/webpack/webpack.prod.js diff --git a/jhipster-5/pom.xml b/jhipster-6/pom.xml similarity index 56% rename from jhipster-5/pom.xml rename to jhipster-6/pom.xml index 2a5132e50e2d..b3c5e5831930 100644 --- a/jhipster-5/pom.xml +++ b/jhipster-6/pom.xml @@ -1,11 +1,10 @@ - - + 4.0.0 com.baeldung.jhipster - jhipster-5 + jhipster-6 1.0.0-SNAPSHOT - jhipster-5 + jhipster-6 pom @@ -17,6 +16,6 @@ bookstore-monolith - - + + diff --git a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/UaaTokenEndpointClient.java b/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/UaaTokenEndpointClient.java index 01c8febdb224..296e8cf67a1b 100644 --- a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/UaaTokenEndpointClient.java +++ b/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/security/oauth2/UaaTokenEndpointClient.java @@ -5,11 +5,11 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; -import org.springframework.util.Base64Utils; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import java.nio.charset.StandardCharsets; +import java.util.Base64; /** * Client talking to UAA's token endpoint to do different OAuth2 grants. @@ -34,7 +34,7 @@ protected String getAuthorizationHeader() { String clientId = getClientId(); String clientSecret = getClientSecret(); String authorization = clientId + ":" + clientSecret; - return "Basic " + Base64Utils.encodeToString(authorization.getBytes(StandardCharsets.UTF_8)); + return "Basic " + Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)); } } diff --git a/jib/pom.xml b/jib/pom.xml index bbc9a3c623a8..2bdaa258f5af 100644 --- a/jib/pom.xml +++ b/jib/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 jib - 0.1-SNAPSHOT jib diff --git a/jmeter/pom.xml b/jmeter/pom.xml index 33cd56032e0e..5f4105d2829c 100644 --- a/jmeter/pom.xml +++ b/jmeter/pom.xml @@ -50,13 +50,13 @@ jmeter-maven-plugin ${jmeter-maven-plugin.version} - - - configuration - - configure - - + + + configuration + + configure + + jmeter-tests @@ -72,10 +72,6 @@ - - 3.7.0 - - dashboard @@ -167,4 +163,8 @@ + + 3.7.0 + + \ No newline at end of file diff --git a/jmh/pom.xml b/jmh/pom.xml index 61f62efd5acb..5b98d59002a8 100644 --- a/jmh/pom.xml +++ b/jmh/pom.xml @@ -4,10 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 jmh - 1.0-SNAPSHOT jmh jar - http://maven.apache.org com.baeldung @@ -20,12 +18,12 @@ org.openjdk.jmh jmh-core - ${jmh-core.version} + 1.36 org.openjdk.jmh jmh-generator-annprocess - ${jmh-generator.version} + 1.36 org.openjdk.jol @@ -36,6 +34,15 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + + --add-exports=java.base/jdk.internal.vm.annotation=ALL-UNNAMED + + + org.apache.maven.plugins maven-jar-plugin @@ -76,9 +83,10 @@ - 3.0.2 - 0.10 - 3.2.0 + 3.3.0 + 0.17 + 3.5.0 + 3.11.0 \ No newline at end of file diff --git a/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java b/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java index 71c34a9de34b..1cb55f3f4ec7 100644 --- a/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java +++ b/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java @@ -88,7 +88,7 @@ abstract class Striped64 extends Number { * JVM intrinsics note: It would be possible to use a release-only * form of CAS here, if it were provided. */ - @sun.misc.Contended static final class Cell { + @jdk.internal.vm.annotation.Contended static final class Cell { volatile long value; Cell(long x) { value = x; } final boolean cas(long cmp, long val) { diff --git a/jsf/pom.xml b/jsf/pom.xml index 4e1754055770..81030537fbda 100644 --- a/jsf/pom.xml +++ b/jsf/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 jsf - 0.1-SNAPSHOT jsf war @@ -79,7 +78,7 @@ 3.0.0 3.3.1 - + 1.3.1 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> samMendesMovies = JsonPath.parse(jsonString) + .read("$[?]['director']", directorSamMendesFilter); + assertEquals(samMendesMovies.size(), 2); + } + } \ No newline at end of file diff --git a/json-modules/json/pom.xml b/json-modules/json/pom.xml index 06e67288c59f..8210f026e738 100644 --- a/json-modules/json/pom.xml +++ b/json-modules/json/pom.xml @@ -5,7 +5,6 @@ 4.0.0 org.baeldung json - 0.0.1-SNAPSHOT json @@ -69,7 +68,7 @@ 1.0.72 1.0 1.0.1 - 20211205 + 20230227 2.8.5 1.1.2 2.28.0 diff --git a/json-modules/pom.xml b/json-modules/pom.xml index 2deb53d5337c..15a066daa488 100644 --- a/json-modules/pom.xml +++ b/json-modules/pom.xml @@ -18,6 +18,7 @@ json-2 json-path gson + gson-2 diff --git a/jws/pom.xml b/jws/pom.xml index 3d2f67c691aa..2f01f9072122 100644 --- a/jws/pom.xml +++ b/jws/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.example jws - 0.0.1-SNAPSHOT jws war @@ -67,4 +65,4 @@ 3.0.2 - \ No newline at end of file + diff --git a/kubernetes-modules/k8s-java-heap-dump/pom.xml b/kubernetes-modules/k8s-java-heap-dump/pom.xml index 6c53553b8fd9..70a9e004accd 100644 --- a/kubernetes-modules/k8s-java-heap-dump/pom.xml +++ b/kubernetes-modules/k8s-java-heap-dump/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/xsd/maven-4.0.0.xsd"> 4.0.0 k8s-java-heap-dump 0.0.1-SNAPSHOT diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index daa01108f67f..5e06a5550e4e 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -122,6 +122,11 @@ ${mutabilitydetector.version} test + + javax.annotation + javax.annotation-api + 1.3.2 + @@ -161,42 +166,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.5 - javac-with-errorprone - true - 1.8 - 1.8 - true - - - com.uber.nullaway - nullaway - 0.3.0 - - - - - - - -XepExcludedPaths:(.*)/test/.*|(.*)/jcabi/.* - -XepOpt:NullAway:AnnotatedPackages=com.baeldung.nullaway - + 11 + 11 - - - org.codehaus.plexus - plexus-compiler-javac-errorprone - 2.8 - - - - - com.google.errorprone - error_prone_core - 2.3.4 - - diff --git a/libraries-3/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java b/libraries-3/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java index 222cbfd8ef8a..b9164ed92b9a 100644 --- a/libraries-3/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java +++ b/libraries-3/src/test/java/com/baeldung/immutable/ImmutablePersonUnitTest.java @@ -1,5 +1,6 @@ package com.baeldung.immutable; +import org.junit.Ignore; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -7,6 +8,12 @@ public class ImmutablePersonUnitTest { + /** + * commenting the test case, As after upgrading to java 11 + * assertImmutable is giving exception. Raised the issue to Mutability support team + * https://github.com/MutabilityDetector/MutabilityDetector/issues/196 + */ + @Ignore @Test public void whenModifying_shouldCreateNewInstance() throws Exception { final ImmutablePerson john = ImmutablePerson.builder() diff --git a/libraries-4/pom.xml b/libraries-4/pom.xml index 7d19f6d5041c..3949d508752c 100644 --- a/libraries-4/pom.xml +++ b/libraries-4/pom.xml @@ -99,9 +99,31 @@ javax.el ${glassfish.web.version} + + org.openjfx + javafx-controls + ${javafx.version} + + + org.openjfx + javafx-fxml + ${javafx.version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson-core.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-annotations.version} + + 2.14.2 + 2.14.2 1.2.6 8.2.0 1.1.0 @@ -118,6 +140,8 @@ 3.0.0 2.2.4 1.2.0 + 19 + 10.3.0 \ No newline at end of file diff --git a/libraries-5/pom.xml b/libraries-5/pom.xml index fa1f232d1c25..c98a66c094b9 100644 --- a/libraries-5/pom.xml +++ b/libraries-5/pom.xml @@ -139,7 +139,7 @@ 4.3.8.RELEASE 2.12 2.5.11 - 0.6.5 + 0.8.1 3.0.14 2.5.5 3.0.2 diff --git a/libraries-6/README.md b/libraries-6/README.md index 8ef60b2e5498..bbebcbc1e007 100644 --- a/libraries-6/README.md +++ b/libraries-6/README.md @@ -12,8 +12,8 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Guide to Resilience4j](https://www.baeldung.com/resilience4j) - [Implementing a FTP-Client in Java](https://www.baeldung.com/java-ftp-client) - [Introduction to Functional Java](https://www.baeldung.com/java-functional-library) -- [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library) - [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) +- [Guide to Simple Binary Encoding](https://www.baeldung.com/java-sbe) - [Java-R Integration](https://www.baeldung.com/java-r-integration) - [Using libphonenumber to Validate Phone Numbers](https://www.baeldung.com/java-libphonenumber) - [Apache Commons Collections vs Google Guava](https://www.baeldung.com/apache-commons-collections-vs-guava) diff --git a/libraries-6/pom.xml b/libraries-6/pom.xml index 3b932f2bd290..139edab34fa8 100644 --- a/libraries-6/pom.xml +++ b/libraries-6/pom.xml @@ -53,12 +53,6 @@ ${mockftpserver.version} test - - - org.reflections - reflections - ${reflections.version} - org.apache.commons commons-lang3 @@ -69,6 +63,11 @@ commons-collections4 ${commons-collections4.version} + + com.google.guava + guava + ${guava.version} + commons-net commons-net @@ -106,6 +105,11 @@ modelmapper ${org.modelmapper.version} + + org.agrona + agrona + 1.17.1 + @@ -119,6 +123,60 @@ + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + generate-sources + + java + + + + + false + true + uk.co.real_logic.sbe.SbeTool + + + sbe.output.dir + ${project.build.directory}/generated-sources/java + + + + ${project.basedir}/src/main/resources/schema.xml + + ${project.build.directory}/generated-sources/java + + + + uk.co.real-logic + sbe-tool + 1.27.0 + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + ${project.build.directory}/generated-sources/java/ + + + + + org.apache.maven.plugins maven-compiler-plugin @@ -137,7 +195,6 @@ 1.10.0 - 0.9.11 2.7.1 4.8.1 0.12.1 diff --git a/libraries-7/src/main/java/com/baeldung/sbe/MarketData.java b/libraries-6/src/main/java/com/baeldung/sbe/MarketData.java similarity index 100% rename from libraries-7/src/main/java/com/baeldung/sbe/MarketData.java rename to libraries-6/src/main/java/com/baeldung/sbe/MarketData.java diff --git a/libraries-7/src/main/java/com/baeldung/sbe/MarketDataSource.java b/libraries-6/src/main/java/com/baeldung/sbe/MarketDataSource.java similarity index 100% rename from libraries-7/src/main/java/com/baeldung/sbe/MarketDataSource.java rename to libraries-6/src/main/java/com/baeldung/sbe/MarketDataSource.java diff --git a/libraries-7/src/main/java/com/baeldung/sbe/MarketDataStreamServer.java b/libraries-6/src/main/java/com/baeldung/sbe/MarketDataStreamServer.java similarity index 100% rename from libraries-7/src/main/java/com/baeldung/sbe/MarketDataStreamServer.java rename to libraries-6/src/main/java/com/baeldung/sbe/MarketDataStreamServer.java diff --git a/libraries-7/src/main/java/com/baeldung/sbe/MarketDataUtil.java b/libraries-6/src/main/java/com/baeldung/sbe/MarketDataUtil.java similarity index 100% rename from libraries-7/src/main/java/com/baeldung/sbe/MarketDataUtil.java rename to libraries-6/src/main/java/com/baeldung/sbe/MarketDataUtil.java diff --git a/libraries-7/src/main/resources/schema.xml b/libraries-6/src/main/resources/schema.xml similarity index 100% rename from libraries-7/src/main/resources/schema.xml rename to libraries-6/src/main/resources/schema.xml diff --git a/libraries-6/src/test/java/com/baeldung/r/FastRMeanUnitTest.java b/libraries-6/src/test/java/com/baeldung/r/FastRMeanUnitTest.java index 4e7426b75a0e..2412bb751b65 100644 --- a/libraries-6/src/test/java/com/baeldung/r/FastRMeanUnitTest.java +++ b/libraries-6/src/test/java/com/baeldung/r/FastRMeanUnitTest.java @@ -1,5 +1,6 @@ package com.baeldung.r; + import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; diff --git a/libraries-7/src/test/java/com/baeldung/test/EncodeDecodeMarketDataUnitTest.java b/libraries-6/src/test/java/com/baeldung/test/EncodeDecodeMarketDataUnitTest.java similarity index 100% rename from libraries-7/src/test/java/com/baeldung/test/EncodeDecodeMarketDataUnitTest.java rename to libraries-6/src/test/java/com/baeldung/test/EncodeDecodeMarketDataUnitTest.java diff --git a/libraries-7/pom.xml b/libraries-7/pom.xml deleted file mode 100644 index 67cc2326ebef..000000000000 --- a/libraries-7/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - 4.0.0 - libraries-7 - - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - - - - - org.agrona - agrona - 1.17.1 - - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.6.0 - - - generate-sources - - java - - - - - false - true - uk.co.real_logic.sbe.SbeTool - - - sbe.output.dir - ${project.build.directory}/generated-sources/java - - - - ${project.basedir}/src/main/resources/schema.xml - - ${project.build.directory}/generated-sources/java - - - - uk.co.real-logic - sbe-tool - 1.27.0 - - - - - org.codehaus.mojo - build-helper-maven-plugin - 3.0.0 - - - add-source - generate-sources - - add-source - - - - ${project.build.directory}/generated-sources/java/ - - - - - - - - - \ No newline at end of file diff --git a/libraries-ai/README.md b/libraries-ai/README.md new file mode 100644 index 000000000000..01ec9b1d68ac --- /dev/null +++ b/libraries-ai/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Overview of NLP Libraries in Java](https://www.baeldung.com/java-nlp-libraries) diff --git a/libraries-ai/pom.xml b/libraries-ai/pom.xml new file mode 100644 index 000000000000..48b26e5a3150 --- /dev/null +++ b/libraries-ai/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + libraries-ai + libraries-ai + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + edu.stanford.nlp + stanford-corenlp + ${stanford-corenlp.version} + + + org.apache.opennlp + opennlp-tools + ${opennlp-tools.version} + + + + + 4.5.3 + 2.1.1 + + + \ No newline at end of file diff --git a/libraries-ai/src/test/java/com/baeldung/nlp/CoreNLPTokenizerUnitTest.java b/libraries-ai/src/test/java/com/baeldung/nlp/CoreNLPTokenizerUnitTest.java new file mode 100644 index 000000000000..11c5cd0be8d1 --- /dev/null +++ b/libraries-ai/src/test/java/com/baeldung/nlp/CoreNLPTokenizerUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.nlp; + +import edu.stanford.nlp.ling.CoreAnnotations; +import edu.stanford.nlp.ling.CoreLabel; +import edu.stanford.nlp.pipeline.Annotation; +import edu.stanford.nlp.pipeline.StanfordCoreNLP; +import edu.stanford.nlp.util.CoreMap; +import org.junit.Test; + +import java.util.List; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; + +public class CoreNLPTokenizerUnitTest { + @Test + public void givenSampleText_whenTokenize_thenExpectedTokensReturned() { + + Properties props = new Properties(); + props.setProperty("annotators", "tokenize"); + + StanfordCoreNLP pipeline = new StanfordCoreNLP(props); + String text = "The german shepard display an act of kindness"; + + Annotation document = new Annotation(text); + pipeline.annotate(document); + + List sentences = document.get(CoreAnnotations.SentencesAnnotation.class); + StringBuilder tokens = new StringBuilder(); + + for (CoreMap sentence : sentences) { + for (CoreLabel token : sentence.get(CoreAnnotations.TokensAnnotation.class)) { + String word = token.get(CoreAnnotations.TextAnnotation.class); + tokens.append(word) + .append(" "); + } + } + assertEquals("The german shepard display an act of kindness", tokens.toString() + .trim()); + } +} diff --git a/libraries-ai/src/test/java/com/baeldung/nlp/OpenNLPLanguageDetectorManualTest.java b/libraries-ai/src/test/java/com/baeldung/nlp/OpenNLPLanguageDetectorManualTest.java new file mode 100644 index 000000000000..9c5294a808dc --- /dev/null +++ b/libraries-ai/src/test/java/com/baeldung/nlp/OpenNLPLanguageDetectorManualTest.java @@ -0,0 +1,40 @@ +package com.baeldung.nlp; + +import opennlp.tools.langdetect.Language; +import opennlp.tools.langdetect.LanguageDetectorME; +import opennlp.tools.langdetect.LanguageDetectorModel; +import org.junit.jupiter.api.Test; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class OpenNLPLanguageDetectorManualTest { + + @Test + public void givenTextInEnglish_whenDetectLanguage_thenReturnsEnglishLanguageCode() { + + String text = "the dream my father told me"; + LanguageDetectorModel model; + + /* + To download the pre-built model used in this program, follow these steps: + - Go to https://downloads.apache.org/opennlp/models/langdetect/1.8.3/ and click on the link langdetect-183.bin. + - Once the download is complete, move the downloaded file to the project root directory. + */ + + try (InputStream modelIn = new FileInputStream("langdetect-183.bin")) { + model = new LanguageDetectorModel(modelIn); + } catch (IOException e) { + return; + } + + LanguageDetectorME detector = new LanguageDetectorME(model); + Language language = detector.predictLanguage(text); + + // update the assert statement to assertEquals("eng", language.getLang()); + assertEquals("eng", "eng"); + } +} \ No newline at end of file diff --git a/libraries-apache-commons-io/pom.xml b/libraries-apache-commons-io/pom.xml index 7cac50a8e2d0..ca5cc4574d84 100644 --- a/libraries-apache-commons-io/pom.xml +++ b/libraries-apache-commons-io/pom.xml @@ -23,6 +23,11 @@ commons-io ${commons-io.version} + + org.projectlombok + lombok + ${lombok.version} + diff --git a/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java b/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java index 7481e5a1a30d..ce98e8026eaa 100644 --- a/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java +++ b/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java @@ -22,6 +22,9 @@ import java.io.IOException; import java.nio.charset.Charset; +import lombok.extern.slf4j.Slf4j; + +@Slf4j public class CommonsIOUnitTest { @Test @@ -47,9 +50,9 @@ public void whenUsingFileNameUtils_thenshowdifferentFileOperations() throws IOEx String extension = FilenameUtils.getExtension(path); String baseName = FilenameUtils.getBaseName(path); - System.out.println("full path" + fullPath); - System.out.println("Extension" + extension); - System.out.println("Base name" + baseName); + log.debug("full path: " + fullPath); + log.debug("Extension: " + extension); + log.debug("Base name: " + baseName); } @Test diff --git a/libraries-apache-commons-io/src/test/resources/logback-test.xml b/libraries-apache-commons-io/src/test/resources/logback-test.xml new file mode 100644 index 000000000000..499cc828a2e3 --- /dev/null +++ b/libraries-apache-commons-io/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + %d{yyyy-MM-dd HH:mm:ss} | %-5p | [%thread] %logger{5}:%L - %msg%n + + + + + + + \ No newline at end of file diff --git a/libraries-concurrency/pom.xml b/libraries-concurrency/pom.xml index eb581ce3a0fd..8b0ccdd5eca4 100644 --- a/libraries-concurrency/pom.xml +++ b/libraries-concurrency/pom.xml @@ -58,7 +58,7 @@ -javaagent:${co.paralleluniverse:quasar-core:jar} -classpath - + com.baeldung.quasar.App diff --git a/libraries-data-2/README.md b/libraries-data-2/README.md index ee604acf6bc3..f9464e6bbcf0 100644 --- a/libraries-data-2/README.md +++ b/libraries-data-2/README.md @@ -11,6 +11,7 @@ This module contains articles about libraries for data processing in Java. - [An Introduction to SuanShu](https://www.baeldung.com/suanshu) - [Intro to Derive4J](https://www.baeldung.com/derive4j) - [Univocity Parsers](https://www.baeldung.com/java-univocity-parsers) +- [Guide to Swagger Parser](https://www.baeldung.com/java-swagger-parser) - More articles: [[<-- prev]](/../libraries-data) ##### Building the project diff --git a/libraries-data-2/pom.xml b/libraries-data-2/pom.xml index f673ebd4703e..655bad2e2b04 100644 --- a/libraries-data-2/pom.xml +++ b/libraries-data-2/pom.xml @@ -134,6 +134,11 @@ ${byte-buddy.version} test + + io.swagger.parser.v3 + swagger-parser + ${swagger-parser.version} + @@ -171,6 +176,7 @@ 1.1.0 3.0.0 2.8.4 + 2.1.13 \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/swaggerparser/SwaggerParser.java b/libraries-data-2/src/main/java/com/baeldung/swaggerparser/SwaggerParser.java new file mode 100644 index 000000000000..d1f04e680aae --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/swaggerparser/SwaggerParser.java @@ -0,0 +1,92 @@ +package com.baeldung.swaggerparser; + +import java.util.List; + +import io.swagger.parser.OpenAPIParser; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.Paths; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.responses.ApiResponses; +import io.swagger.v3.oas.models.servers.Server; +import io.swagger.v3.parser.core.models.SwaggerParseResult; + +public class SwaggerParser { + + private static String OPENAPI_SPECIFICATION_STRING = "{\"openapi\":\"3.0.0\",\"info\":{\"title\":\"User APIs\",\"version\":\"1.0\"},\"servers\":[{\"url\":\"https://jsonplaceholder.typicode.com\",\"description\":\"Json Place Holder Service\"}],\"paths\":{\"/users/{id}\":{\"parameters\":[{\"schema\":{\"type\":\"integer\"},\"name\":\"id\",\"in\":\"path\",\"required\":true}],\"get\":{\"summary\":\"Fetch user by ID\",\"tags\":[\"User\"],\"responses\":{\"200\":{\"description\":\"OK\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"},\"name\":{\"type\":\"string\"}}}}}}},\"operationId\":\"get-users-user_id\",\"description\":\"Retrieve a specific user by ID\"}}}}"; + + public static void main(String[] args) { + parseYAMLFile(); + parseJSONFile(); + parseString(); + } + + private static void parseString() { + SwaggerParseResult result = new OpenAPIParser().readContents(OPENAPI_SPECIFICATION_STRING, null, null); + + OpenAPI openAPI = result.getOpenAPI(); + + if (openAPI != null) { + printData(openAPI); + } + } + + private static void parseJSONFile() { + SwaggerParseResult result = new OpenAPIParser().readLocation("sample.yml", null, null); + + OpenAPI openAPI = result.getOpenAPI(); + + if (openAPI != null) { + printData(openAPI); + } + } + + private static void parseYAMLFile() { + SwaggerParseResult result = new OpenAPIParser().readLocation("sample.json", null, null); + + OpenAPI openAPI = result.getOpenAPI(); + + if (openAPI != null) { + printData(openAPI); + } + } + + private static void printData(OpenAPI openAPI) { + System.out.println(openAPI.getSpecVersion()); + + Info info = openAPI.getInfo(); + System.out.println(info.getTitle()); + System.out.println(info.getVersion()); + + List servers = openAPI.getServers(); + for (Server server : servers) { + System.out.println(server.getUrl()); + System.out.println(server.getDescription()); + } + + Paths paths = openAPI.getPaths(); + paths.entrySet() + .forEach(pathEntry -> { + System.out.println(pathEntry.getKey()); + + PathItem path = pathEntry.getValue(); + System.out.println(path.getGet() + .getSummary()); + System.out.println(path.getGet() + .getDescription()); + System.out.println(path.getGet() + .getOperationId()); + + ApiResponses responses = path.getGet() + .getResponses(); + responses.entrySet() + .forEach(responseEntry -> { + System.out.println(responseEntry.getKey()); + + ApiResponse response = responseEntry.getValue(); + System.out.println(response.getDescription()); + }); + }); + } +} diff --git a/libraries-data-2/src/main/resources/sample.json b/libraries-data-2/src/main/resources/sample.json new file mode 100644 index 000000000000..8b59bbb42a12 --- /dev/null +++ b/libraries-data-2/src/main/resources/sample.json @@ -0,0 +1,55 @@ +{ + "openapi": "3.0.0", + "info": { + "title": "User APIs", + "version": "1.0" + }, + "servers": [ + { + "url": "https://jsonplaceholder.typicode.com", + "description": "Json Place Holder Service" + } + ], + "paths": { + "/users/{id}": { + "parameters": [ + { + "schema": { + "type": "integer" + }, + "name": "id", + "in": "path", + "required": true + } + ], + "get": { + "summary": "Fetch user by ID", + "tags": [ + "User" + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + } + } + } + } + } + } + }, + "operationId": "get-users-user_id", + "description": "Retrieve a specific user by ID" + } + } + } +} \ No newline at end of file diff --git a/libraries-data-2/src/main/resources/sample.yml b/libraries-data-2/src/main/resources/sample.yml new file mode 100644 index 000000000000..ddfa06439398 --- /dev/null +++ b/libraries-data-2/src/main/resources/sample.yml @@ -0,0 +1,33 @@ +openapi: 3.0.0 +info: + title: User APIs + version: '1.0' +servers: + - url: https://jsonplaceholder.typicode.com + description: Json Place Holder Service +paths: + /users/{id}: + parameters: + - schema: + type: integer + name: id + in: path + required: true + get: + summary: Fetch user by ID + tags: + - User + responses: + '200': + description: OK + content: + application/json: + schema: + type: object + properties: + id: + type: integer + name: + type: string + operationId: get-users-user_id + description: Retrieve a specific user by ID \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/swaggerparser/SwaggerParserUnitTest.java b/libraries-data-2/src/test/java/com/baeldung/swaggerparser/SwaggerParserUnitTest.java new file mode 100644 index 000000000000..615bd917cba6 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/swaggerparser/SwaggerParserUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.swaggerparser; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +import io.swagger.parser.OpenAPIParser; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.parser.core.models.SwaggerParseResult; + +public class SwaggerParserUnitTest { + + private static String OPENAPI_SPECIFICATION_STRING = "{\"openapi\":\"3.0.0\",\"info\":{\"title\":\"User APIs\",\"version\":\"1.0\"},\"servers\":[{\"url\":\"https://jsonplaceholder.typicode.com\",\"description\":\"Json Place Holder Service\"}],\"paths\":{\"/users/{id}\":{\"parameters\":[{\"schema\":{\"type\":\"integer\"},\"name\":\"id\",\"in\":\"path\",\"required\":true}],\"get\":{\"summary\":\"Fetch user by ID\",\"tags\":[\"User\"],\"responses\":{\"200\":{\"description\":\"OK\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"},\"name\":{\"type\":\"string\"}}}}}}},\"operationId\":\"get-users-user_id\",\"description\":\"Retrieve a specific user by ID\"}}}}"; + + @Test + public void givenAValidOpenAPIYAMLFile_whenParsing_thenCheckIfParsed() { + SwaggerParseResult result = new OpenAPIParser().readLocation("valid-openapi-sample.yml", null, null); + + OpenAPI openAPI = result.getOpenAPI(); + + assertNotNull(openAPI); + } + + @Test + public void givenAValidOpenAPIYAMLFile_whenParsing_thenCheckIfNotErrors() { + SwaggerParseResult result = new OpenAPIParser().readLocation("valid-openapi-sample.yml", null, null); + + List messages = result.getMessages(); + + assertTrue(messages.isEmpty()); + } + + @Test + public void givenAnInvalidOpenAPIYAMLFile_whenParsing_thenCheckIfErrors() { + SwaggerParseResult result = new OpenAPIParser().readLocation("invalid-openapi-sample.yml", null, null); + + List messages = result.getMessages(); + + assertFalse(messages.isEmpty()); + } + + @Test + public void givenAValidOpenAPISpecificationString_whenParsing_thenCheckIfParsed() { + SwaggerParseResult result = new OpenAPIParser().readContents(OPENAPI_SPECIFICATION_STRING, null, null); + + OpenAPI openAPI = result.getOpenAPI(); + + assertNotNull(openAPI); + } + + @Test + public void givenAValidOpenAPISpecificationString_whenParsing_thenCheckIfNotErrors() { + SwaggerParseResult result = new OpenAPIParser().readLocation(OPENAPI_SPECIFICATION_STRING, null, null); + + List messages = result.getMessages(); + + assertNull(messages); + } + +} diff --git a/libraries-data-2/src/test/resources/invalid-openapi-sample.yml b/libraries-data-2/src/test/resources/invalid-openapi-sample.yml new file mode 100644 index 000000000000..eaac64c9a99a --- /dev/null +++ b/libraries-data-2/src/test/resources/invalid-openapi-sample.yml @@ -0,0 +1,32 @@ +openapi: 3.0.0 +info: + title: User APIs + version: '1.0' +servers: + - description: Json Place Holder Service +paths: + /users/{id}: + parameters: + - schema: + type: integer + name: id + in: path + required: true + get: + summary: Fetch user by ID + tags: + - User + responses: + '200': + description: OK + content: + application/json: + schema: + type: object + properties: + id: + type: integer + name: + type: string + operationId: get-users-user_id + description: Retrieve a specific user by ID \ No newline at end of file diff --git a/libraries-data-2/src/test/resources/valid-openapi-sample.yml b/libraries-data-2/src/test/resources/valid-openapi-sample.yml new file mode 100644 index 000000000000..ddfa06439398 --- /dev/null +++ b/libraries-data-2/src/test/resources/valid-openapi-sample.yml @@ -0,0 +1,33 @@ +openapi: 3.0.0 +info: + title: User APIs + version: '1.0' +servers: + - url: https://jsonplaceholder.typicode.com + description: Json Place Holder Service +paths: + /users/{id}: + parameters: + - schema: + type: integer + name: id + in: path + required: true + get: + summary: Fetch user by ID + tags: + - User + responses: + '200': + description: OK + content: + application/json: + schema: + type: object + properties: + id: + type: integer + name: + type: string + operationId: get-users-user_id + description: Retrieve a specific user by ID \ No newline at end of file diff --git a/libraries-data-db/README.md b/libraries-data-db/README.md index 98a83d566946..1062449693e6 100644 --- a/libraries-data-db/README.md +++ b/libraries-data-db/README.md @@ -11,3 +11,5 @@ This module contains articles about database-related data processing libraries. - [Introduction to HikariCP](https://www.baeldung.com/hikaricp) - [Guide to Ebean ORM](https://www.baeldung.com/ebean-orm) - [Introduction to Debezium](https://www.baeldung.com/debezium-intro) +- [Automatically Create Schemas for H2 In-Memory Database](https://www.baeldung.com/java-h2-automatically-create-schemas) +- [A Guide to FlexyPool](https://www.baeldung.com/spring-flexypool-guide) diff --git a/libraries-data-db/log4j.properties b/libraries-data-db/log4j.properties index 2173c5d96f39..d2a3cae499b4 100644 --- a/libraries-data-db/log4j.properties +++ b/libraries-data-db/log4j.properties @@ -1 +1,4 @@ -log4j.rootLogger=INFO, stdout +log4j.rootLogger=INFO,stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout +log4j.logger.org.datanucleus=DEBUG diff --git a/libraries-data-db/pom.xml b/libraries-data-db/pom.xml index 55fd990a8055..ed184d72e021 100644 --- a/libraries-data-db/pom.xml +++ b/libraries-data-db/pom.xml @@ -115,6 +115,24 @@ mysql ${testcontainers-version} + + + com.vladmihalcea.flexy-pool + flexy-micrometer-metrics + ${flexy-pool.version} + + + + com.vladmihalcea.flexy-pool + flexy-hikaricp + ${flexy-pool.version} + + + com.vladmihalcea.flexy-pool + flexy-dropwizard-metrics + + + org.springframework.boot @@ -147,6 +165,7 @@ + org.apache.maven.plugins maven-antrun-plugin ${maven-antrun-plugin.version} @@ -159,23 +178,22 @@ + refid="maven.plugin.classpath"/> + classname="com.gs.fw.common.mithra.generator.MithraGenerator"/> - + nonGeneratedDir="${project.basedir}/src/main/java"/> - + + databaseType="postgres"/> @@ -284,6 +302,7 @@ 5.0.1 13.15.2 2.1.3.Final + 2.2.3 1.17.6 diff --git a/libraries-data-db/src/main/java/com/baeldung/libraries/flexypool/FlexypoolConfig.java b/libraries-data-db/src/main/java/com/baeldung/libraries/flexypool/FlexypoolConfig.java new file mode 100644 index 000000000000..3b6bdca26b6d --- /dev/null +++ b/libraries-data-db/src/main/java/com/baeldung/libraries/flexypool/FlexypoolConfig.java @@ -0,0 +1,109 @@ +package com.baeldung.libraries.flexypool; + +import com.vladmihalcea.flexypool.FlexyPoolDataSource; +import com.vladmihalcea.flexypool.adaptor.HikariCPPoolAdapter; +import com.vladmihalcea.flexypool.config.Configuration; +import com.vladmihalcea.flexypool.connection.ConnectionDecoratorFactoryResolver; +import com.vladmihalcea.flexypool.event.ConnectionAcquireTimeThresholdExceededEvent; +import com.vladmihalcea.flexypool.event.ConnectionAcquireTimeoutEvent; +import com.vladmihalcea.flexypool.event.ConnectionLeaseTimeThresholdExceededEvent; +import com.vladmihalcea.flexypool.event.EventListener; +import com.vladmihalcea.flexypool.metric.micrometer.MicrometerMetrics; +import com.vladmihalcea.flexypool.strategy.IncrementPoolOnTimeoutConnectionAcquiringStrategy; +import com.vladmihalcea.flexypool.strategy.RetryConnectionAcquiringStrategy; +import com.vladmihalcea.flexypool.strategy.UniqueNamingStrategy; +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Bean; + +import java.util.Arrays; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +@org.springframework.context.annotation.Configuration +public class FlexypoolConfig { + + @SuppressWarnings("unchecked") + @Bean(initMethod = "start", destroyMethod = "stop") + public FlexyPoolDataSource flexypoolDataSource() { + Configuration configuration = flexypoolConfiguration(); + return new FlexyPoolDataSource<>(configuration, new IncrementPoolOnTimeoutConnectionAcquiringStrategy.Factory<>(5), new RetryConnectionAcquiringStrategy.Factory<>(2)); + } + + @Bean + public Configuration flexypoolConfiguration() { + + HikariDataSource dataSource = hikariDataSource(); + + return new Configuration.Builder<>(UUID.randomUUID().toString(), dataSource, HikariCPPoolAdapter.FACTORY).setMetricsFactory(MicrometerMetrics::new) + .setConnectionProxyFactory(ConnectionDecoratorFactoryResolver.INSTANCE.resolve()) + .setMetricLogReporterMillis(TimeUnit.SECONDS.toMillis(5)) + .setMetricNamingUniqueName(UniqueNamingStrategy.INSTANCE) + .setJmxEnabled(true) + .setJmxAutoStart(true) + .setConnectionAcquireTimeThresholdMillis(50L) + .setConnectionLeaseTimeThresholdMillis(250L) + .setEventListenerResolver(() -> Arrays.asList(new ConnectionAcquireTimeoutEventListener(), new ConnectionAcquireTimeThresholdExceededEventListener(), new ConnectionLeaseTimeThresholdExceededEventListener())) + .build(); + } + + @Bean + public HikariDataSource hikariDataSource() { + + HikariConfig config = new HikariConfig(); + config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'"); + config.setUsername(""); + config.setPassword(""); + config.addDataSourceProperty("cachePrepStmts", "true"); + config.addDataSourceProperty("prepStmtCacheSize", "250"); + config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); + config.addDataSourceProperty("minimumPoolSize", "1"); + config.addDataSourceProperty("maximumPoolSize", "3"); + config.addDataSourceProperty("connectionTimeout", "1000"); + return new HikariDataSource(config); + } +} + +class ConnectionAcquireTimeThresholdExceededEventListener extends EventListener { + + public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionAcquireTimeThresholdExceededEventListener.class); + + public ConnectionAcquireTimeThresholdExceededEventListener() { + super(ConnectionAcquireTimeThresholdExceededEvent.class); + } + + @Override + public void on(ConnectionAcquireTimeThresholdExceededEvent event) { + LOGGER.info("ConnectionAcquireTimeThresholdExceededEvent Caught event {}", event); + } +} + +class ConnectionLeaseTimeThresholdExceededEventListener extends EventListener { + + public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionLeaseTimeThresholdExceededEventListener.class); + + public ConnectionLeaseTimeThresholdExceededEventListener() { + super(ConnectionLeaseTimeThresholdExceededEvent.class); + } + + @Override + public void on(ConnectionLeaseTimeThresholdExceededEvent event) { + LOGGER.info("ConnectionLeaseTimeThresholdExceededEvent Caught event {}", event); + } +} + +class ConnectionAcquireTimeoutEventListener extends EventListener { + + public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionAcquireTimeoutEventListener.class); + + public ConnectionAcquireTimeoutEventListener() { + super(ConnectionAcquireTimeoutEvent.class); + } + + @Override + public void on(ConnectionAcquireTimeoutEvent event) { + LOGGER.info("ConnectionAcquireTimeoutEvent Caught event {}", event); + } +} \ No newline at end of file diff --git a/libraries-data-db/src/main/java/com/baeldung/libraries/flexypool/FlexypoolDemoApplication.java b/libraries-data-db/src/main/java/com/baeldung/libraries/flexypool/FlexypoolDemoApplication.java new file mode 100644 index 000000000000..16d342f6f930 --- /dev/null +++ b/libraries-data-db/src/main/java/com/baeldung/libraries/flexypool/FlexypoolDemoApplication.java @@ -0,0 +1,53 @@ +package com.baeldung.libraries.flexypool; + +import com.baeldung.libraries.hikaricp.Employee; +import com.vladmihalcea.flexypool.FlexyPoolDataSource; +import com.zaxxer.hikari.HikariDataSource; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +@SpringBootApplication +public class FlexypoolDemoApplication { + + private static FlexyPoolDataSource poolDataSource; + + public FlexypoolDemoApplication(FlexyPoolDataSource poolDataSource) { + FlexypoolDemoApplication.poolDataSource = poolDataSource; + } + + public static List getEmployees() throws SQLException { + String SQL_QUERY = "select * from emp"; + List employees; + try (Connection con = poolDataSource.getConnection(); PreparedStatement pst = con.prepareStatement(SQL_QUERY); ResultSet rs = pst.executeQuery();) { + employees = new ArrayList<>(); + Employee employee; + while (rs.next()) { + employee = new Employee(); + employee.setEmpNo(rs.getInt("empno")); + employee.setEname(rs.getString("ename")); + employee.setJob(rs.getString("job")); + employee.setMgr(rs.getInt("mgr")); + employee.setHiredate(rs.getDate("hiredate")); + employee.setSal(rs.getInt("sal")); + employee.setComm(rs.getInt("comm")); + employee.setDeptno(rs.getInt("deptno")); + employees.add(employee); + } + } + return employees; + } + + public static void main(String[] args) throws SQLException { + SpringApplication.run(FlexypoolDemoApplication.class, args); + List employees = getEmployees(); + System.out.println(employees); + } + +} diff --git a/libraries-data-db/src/main/java/com/baeldung/libraries/h2/H2InitDemoApplication.java b/libraries-data-db/src/main/java/com/baeldung/libraries/h2/H2InitDemoApplication.java new file mode 100644 index 000000000000..36170fb2632b --- /dev/null +++ b/libraries-data-db/src/main/java/com/baeldung/libraries/h2/H2InitDemoApplication.java @@ -0,0 +1,72 @@ +package com.baeldung.libraries.h2; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.DriverManager; + +@SpringBootApplication +public class H2InitDemoApplication { + + public static void main(String[] args) { + ApplicationContext ctx = SpringApplication.run(H2InitDemoApplication.class, args); + initDatabaseUsingPlainJDBCWithURL(); + initDatabaseUsingPlainJDBCWithFile(); + initDatabaseUsingSpring(ctx.getBean(DataSource.class)); + } + + /** + * Initialize in-memory database using plain JDBC and SQL + * statements in the URL. + */ + private static void initDatabaseUsingPlainJDBCWithURL() { + try (Connection conn = DriverManager. + getConnection("jdbc:h2:mem:baeldung;INIT=CREATE SCHEMA IF NOT EXISTS baeldung\\;SET SCHEMA baeldung;", + "admin", + "password")) { + conn.createStatement().execute("create table users (name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL);"); + System.out.println("Created table users"); + conn.createStatement().execute("insert into users (name, email) values ('Mike', 'mike@baeldung.com')"); + System.out.println("Added user mike"); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Initialize in-memory database using plain JDBC and SQL + * statements in a file. + */ + private static void initDatabaseUsingPlainJDBCWithFile() { + try (Connection conn = DriverManager. + getConnection("jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'src/main/resources/h2init.sql';", + "admin", + "password")) { + conn.createStatement().execute("insert into users (name, email) values ('Mike', 'mike@baeldung.com')"); + System.out.println("Added user mike"); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Initialize in-memory database using Spring Boot + * properties. See article for full details of required + * properties for this method to work. + */ + private static void initDatabaseUsingSpring(DataSource ds) { + try (Connection conn = ds.getConnection()) { + conn.createStatement().execute("insert into users (name, email) values ('Mike', 'mike@baeldung.com')"); + System.out.println("Added user mike"); + } + catch (Exception e) { + e.printStackTrace(); + } + } +} + diff --git a/libraries-data-db/src/main/resources/h2init.sql b/libraries-data-db/src/main/resources/h2init.sql new file mode 100644 index 000000000000..c6fb70bcc437 --- /dev/null +++ b/libraries-data-db/src/main/resources/h2init.sql @@ -0,0 +1,3 @@ +CREATE SCHEMA IF NOT EXISTS baeldung; +SET SCHEMA baeldung; +CREATE TABLE users (name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL); diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 6ba48a9d66bc..a721e967d23d 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/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 libraries-data libraries-data diff --git a/libraries-files/pom.xml b/libraries-files/pom.xml index b36dc150a866..e4b3ffcdb27f 100644 --- a/libraries-files/pom.xml +++ b/libraries-files/pom.xml @@ -38,22 +38,24 @@ ${jackson.version} - com.itextpdf - itext7-core - 7.2.4 - pom + com.itextpdf + itext7-core + ${itext7-core.version} + pom - - org.assertj - assertj-core - 3.23.1 - test + + org.assertj + assertj-core + ${assertj-core.version} + test 0.5.4 2.8.0 + 7.2.4 + 3.23.1 \ No newline at end of file diff --git a/libraries-http/pom.xml b/libraries-http/pom.xml index 0077a5047e0e..18ba571f6099 100644 --- a/libraries-http/pom.xml +++ b/libraries-http/pom.xml @@ -52,11 +52,6 @@ async-http-client ${async.http.client.version} - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - com.google.code.gson gson diff --git a/libraries-7/README.md b/libraries-jdk8/README.md similarity index 73% rename from libraries-7/README.md rename to libraries-jdk8/README.md index 6f0a7d2505a8..fa2126c89a97 100644 --- a/libraries-7/README.md +++ b/libraries-jdk8/README.md @@ -1,4 +1,4 @@ -## Libraries-7 +## Libraries-jdk8 This module contains articles about various Java libraries. These are small libraries that are relatively easy to use and do not require any separate module of their own. @@ -8,5 +8,7 @@ The code examples related to different libraries are each in their own module. Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases. ### Relevant articles -- [Guide to Simple Binary Encoding](https://www.baeldung.com/java-sbe) +- [Introduction to Chronicle Queue](https://www.baeldung.com/java-chronicle-queue) +- [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library) + - More articles [[<-- prev]](/libraries-6) diff --git a/libraries-jdk8/pom.xml b/libraries-jdk8/pom.xml new file mode 100644 index 000000000000..31582e0bdd6e --- /dev/null +++ b/libraries-jdk8/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + libraries-jdk8 + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + + org.reflections + reflections + ${reflections.version} + + + + net.openhft + chronicle + ${chronicle.version} + + + com.sun.java + tools + + + + + + + 0.9.11 + 3.6.4 + + + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java b/libraries-jdk8/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java similarity index 100% rename from libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java rename to libraries-jdk8/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java diff --git a/libraries-6/src/main/java/com/baeldung/reflections/ReflectionsApp.java b/libraries-jdk8/src/main/java/reflections/ReflectionsApp.java similarity index 91% rename from libraries-6/src/main/java/com/baeldung/reflections/ReflectionsApp.java rename to libraries-jdk8/src/main/java/reflections/ReflectionsApp.java index 4f5b6dd1830c..39d0fafb1002 100644 --- a/libraries-6/src/main/java/com/baeldung/reflections/ReflectionsApp.java +++ b/libraries-jdk8/src/main/java/reflections/ReflectionsApp.java @@ -1,4 +1,4 @@ -package com.baeldung.reflections; +package reflections; import java.lang.reflect.Constructor; import java.lang.reflect.Method; @@ -30,14 +30,14 @@ public Set> getJDKFunctinalInterfaces() { } public Set getDateDeprecatedMethods() { - Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner()); + Reflections reflections = new Reflections(Date.class, new MethodAnnotationsScanner()); Set deprecatedMethodsSet = reflections.getMethodsAnnotatedWith(Deprecated.class); return deprecatedMethodsSet; } @SuppressWarnings("rawtypes") public Set getDateDeprecatedConstructors() { - Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner()); + Reflections reflections = new Reflections(Date.class, new MethodAnnotationsScanner()); Set constructorsSet = reflections.getConstructorsAnnotatedWith(Deprecated.class); return constructorsSet; } diff --git a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java b/libraries-jdk8/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java similarity index 95% rename from libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java rename to libraries-jdk8/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java index 00e950031870..7e0bcb7d33f0 100644 --- a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java +++ b/libraries-jdk8/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java @@ -8,6 +8,8 @@ import org.junit.Test; +import com.baeldung.chronicle.queue.ChronicleQueue; + import net.openhft.chronicle.Chronicle; import net.openhft.chronicle.ChronicleQueueBuilder; import net.openhft.chronicle.ExcerptTailer; @@ -15,6 +17,7 @@ public class ChronicleQueueIntegrationTest { +// @Ignore @Test public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException { File queueDir = Files.createTempDirectory("chronicle-queue").toFile(); diff --git a/libraries-6/src/test/java/com/baeldung/reflections/ReflectionsUnitTest.java b/libraries-jdk8/src/test/java/reflections/ReflectionsUnitTest.java similarity index 97% rename from libraries-6/src/test/java/com/baeldung/reflections/ReflectionsUnitTest.java rename to libraries-jdk8/src/test/java/reflections/ReflectionsUnitTest.java index b86094b6f4a8..510485520890 100644 --- a/libraries-6/src/test/java/com/baeldung/reflections/ReflectionsUnitTest.java +++ b/libraries-jdk8/src/test/java/reflections/ReflectionsUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.reflections; +package reflections; import static org.junit.jupiter.api.Assertions.assertFalse; diff --git a/libraries-primitive/pom.xml b/libraries-primitive/pom.xml index badcfc443d84..114ec6484830 100644 --- a/libraries-primitive/pom.xml +++ b/libraries-primitive/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 libraries-primitive 1.0-SNAPSHOT libraries-primitive diff --git a/libraries-transform/README.md b/libraries-transform/README.md new file mode 100644 index 000000000000..8d434912dd36 --- /dev/null +++ b/libraries-transform/README.md @@ -0,0 +1,3 @@ + +### Relevant articles +- [Analyze, Generate and Transform Code Using Spoon in Java](https://www.baeldung.com/java-spoon-analyze-generate-transform-code) \ No newline at end of file diff --git a/libraries-transform/pom.xml b/libraries-transform/pom.xml new file mode 100644 index 000000000000..0dd7ebcfae63 --- /dev/null +++ b/libraries-transform/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + libraries-transform + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + fr.inria.gforge.spoon + spoon-core + ${spoon-core.version} + + + + + + 10.3.0 + + + \ No newline at end of file diff --git a/libraries-transform/src/main/java/com/baeldung/spoon/AddCopyrightProcessor.java b/libraries-transform/src/main/java/com/baeldung/spoon/AddCopyrightProcessor.java new file mode 100644 index 000000000000..7298cffa1210 --- /dev/null +++ b/libraries-transform/src/main/java/com/baeldung/spoon/AddCopyrightProcessor.java @@ -0,0 +1,15 @@ +package com.baeldung.spoon; + +import spoon.processing.AbstractProcessor; +import spoon.reflect.code.CtComment; +import spoon.reflect.code.CtComment.CommentType; +import spoon.reflect.declaration.CtClass; + +public class AddCopyrightProcessor extends AbstractProcessor> { + + @Override + public void process(CtClass clazz) { + CtComment comment = getFactory().createComment("Copyright(c) 2023 etc", CommentType.JAVADOC); + clazz.addComment(comment); + } +} diff --git a/libraries-transform/src/main/java/com/baeldung/spoon/AddCopyrightTransformer.java b/libraries-transform/src/main/java/com/baeldung/spoon/AddCopyrightTransformer.java new file mode 100644 index 000000000000..b7f20b6b8516 --- /dev/null +++ b/libraries-transform/src/main/java/com/baeldung/spoon/AddCopyrightTransformer.java @@ -0,0 +1,31 @@ +package com.baeldung.spoon; + +import spoon.Launcher; +import spoon.SpoonAPI; +import spoon.reflect.CtModel; +import spoon.reflect.code.CtComment; +import spoon.reflect.code.CtComment.CommentType; +import spoon.reflect.declaration.CtClass; + +public class AddCopyrightTransformer { + + public void addCopyright(String source) { + + SpoonAPI spoon = new Launcher(); + spoon.addInputResource(source); + spoon.getEnvironment().setLevel("DEBUG"); + CtModel model = spoon.buildModel(); + + model.filterChildren((el) -> el instanceof CtClass) + .forEach((CtClass cl) -> { + CtComment comment = cl.getFactory() + .createComment("Copyright(c) 2023 etc", CommentType.JAVADOC); + cl.addComment(comment); + }); + + spoon.setSourceOutputDirectory("./target"); + spoon.prettyprint(); + } + + +} diff --git a/libraries-transform/src/main/java/com/baeldung/spoon/ClassReporter.java b/libraries-transform/src/main/java/com/baeldung/spoon/ClassReporter.java new file mode 100644 index 000000000000..a532b83be18d --- /dev/null +++ b/libraries-transform/src/main/java/com/baeldung/spoon/ClassReporter.java @@ -0,0 +1,111 @@ +package com.baeldung.spoon; + +import spoon.Launcher; +import spoon.SpoonAPI; +import spoon.reflect.CtModel; +import spoon.reflect.declaration.CtClass; +import spoon.reflect.declaration.CtMethod; +import spoon.support.sniper.SniperJavaPrettyPrinter; + +/** + * Loads a given class and creates a summary o + */ +public class ClassReporter { + + + public MethodSummary generateMethodSummaryReport(String source) { + + SpoonAPI spoon = new Launcher(); + spoon.addInputResource(source); + CtModel model = spoon.buildModel(); + MethodSummary report = new MethodSummary(); + model.filterChildren((el) -> el instanceof CtClass) + .forEach((CtClass clazz) -> processMethods(report,clazz)); + + return report; + } + + private void processMethods(MethodSummary report, CtClass ctClass) { + + ctClass.filterChildren((c) -> c instanceof CtMethod ) + .forEach((CtMethod m) -> { + if (m.isPublic()) { + report.addPublicMethod(); + } + else if ( m.isPrivate()) { + report.addPrivateMethod(); + } + else if ( m.isProtected()) { + report.addProtectedMethod(); + } + else { + report.addPackagePrivateMethod(); + } + }); + } + + + public static class MethodSummary { + private int totalMethodCount; + private int publicMethodCount; + private int protectedMethodCount; + private int packagePrivateMethodCount; + private int privateMethodCount; + + void addPublicMethod() { + totalMethodCount++; + publicMethodCount++; + } + + void addPrivateMethod() { + totalMethodCount++; + privateMethodCount++; + } + + void addProtectedMethod() { + totalMethodCount++; + protectedMethodCount++; + } + + void addPackagePrivateMethod() { + totalMethodCount++; + packagePrivateMethodCount++; + } + + /** + * @return the totalMethodCount + */ + public int getTotalMethodCount() { + return totalMethodCount; + } + + /** + * @return the publicMethodCount + */ + public int getPublicMethodCount() { + return publicMethodCount; + } + + /** + * @return the protectedMethodCount + */ + public int getProtectedMethodCount() { + return protectedMethodCount; + } + + /** + * @return the privateMethodCount + */ + public int getPrivateMethodCount() { + return privateMethodCount; + } + + /** + * @return the privateMethodCount + */ + public int getPackagePrivateMethodCount() { + return packagePrivateMethodCount; + } + + } +} diff --git a/libraries-transform/src/test/java/com/baeldung/spoon/AddCopyrightProcessorUnitTest.java b/libraries-transform/src/test/java/com/baeldung/spoon/AddCopyrightProcessorUnitTest.java new file mode 100644 index 000000000000..44b45342b0ac --- /dev/null +++ b/libraries-transform/src/test/java/com/baeldung/spoon/AddCopyrightProcessorUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.spoon; + +import org.junit.Test; + +import spoon.Launcher; +import spoon.SpoonAPI; + +public class AddCopyrightProcessorUnitTest { + + @Test + public void whenAddCopyright_thenSuccess() { + + SpoonAPI spoon = new Launcher(); + spoon.addProcessor(new AddCopyrightProcessor()); + spoon.addInputResource("src/test/resources/spoon/SpoonClassToTest.java"); + spoon.setSourceOutputDirectory("./target/spoon-processed"); + spoon.buildModel(); + spoon.process(); + spoon.prettyprint(); + + } + +} diff --git a/libraries-transform/src/test/java/com/baeldung/spoon/AddCopyrightTransformerUnitTest.java b/libraries-transform/src/test/java/com/baeldung/spoon/AddCopyrightTransformerUnitTest.java new file mode 100644 index 000000000000..af6ba9e16b3b --- /dev/null +++ b/libraries-transform/src/test/java/com/baeldung/spoon/AddCopyrightTransformerUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.spoon; + +import org.junit.Test; + +public class AddCopyrightTransformerUnitTest { + + + + @Test + public void whenAddCopyright_thenSuccess() { + + AddCopyrightTransformer transformer = new AddCopyrightTransformer(); + transformer.addCopyright("src/test/resources/spoon/SpoonClassToTest.java"); + + } + +} diff --git a/libraries-transform/src/test/java/com/baeldung/spoon/ClassReporterUnitTest.java b/libraries-transform/src/test/java/com/baeldung/spoon/ClassReporterUnitTest.java new file mode 100644 index 000000000000..38e6d8ddc71a --- /dev/null +++ b/libraries-transform/src/test/java/com/baeldung/spoon/ClassReporterUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.spoon; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +import com.baeldung.spoon.ClassReporter.MethodSummary; + +public class ClassReporterUnitTest { + + @Test + public void givenBrokenClass_whenGenerateReport_thenSuccess() { + ClassReporter reporter = new ClassReporter(); + MethodSummary report = reporter.generateMethodSummaryReport("src/test/resources/spoon/BrokenClass.java"); + + assertThat(report).isNotNull(); + assertThat(report.getPrivateMethodCount()).isEqualTo(0); + assertThat(report.getPublicMethodCount()).isEqualTo(1); + assertThat(report.getProtectedMethodCount()).isEqualTo(1); + + } + + @Test + public void whenGenerateReport_thenSuccess() { + + ClassReporter reporter = new ClassReporter(); + MethodSummary report = reporter.generateMethodSummaryReport("src/test/resources/spoon/SpoonClassToTest.java"); + assertThat(report).isNotNull(); + assertThat(report.getPackagePrivateMethodCount()).isEqualTo(1); + assertThat(report.getPublicMethodCount()).isEqualTo(1); + assertThat(report.getPrivateMethodCount()).isEqualTo(1); + } + +} diff --git a/libraries-transform/src/test/resources/spoon/BrokenClass.java b/libraries-transform/src/test/resources/spoon/BrokenClass.java new file mode 100644 index 000000000000..cf603b2afb1c --- /dev/null +++ b/libraries-transform/src/test/resources/spoon/BrokenClass.java @@ -0,0 +1,12 @@ +package spoon; +public class BrokenClass { + + // Syntax error + pluvic void brokenMethod() {} + + // Syntax error + protected void protectedMethod() thraws Exception {} + + // Public method + public void publicMethod() {} +} \ No newline at end of file diff --git a/libraries-transform/src/test/resources/spoon/SpoonClassToTest.java b/libraries-transform/src/test/resources/spoon/SpoonClassToTest.java new file mode 100644 index 000000000000..75f06885c097 --- /dev/null +++ b/libraries-transform/src/test/resources/spoon/SpoonClassToTest.java @@ -0,0 +1,28 @@ +package spoon; + +import some.superduper.HelperClass; +import some.superduper.SomeVO; + +public class SpoonClassToTest { + + private static HelperClass helper; + + public SpoonClassToTest() {} + + public int publicMethod() {} + + private int internalStuff() {} + + protected SomeVO protectedMethod() { + return new SomeVO(); + } + + void packageProtectedMethod() { + + try { + HelperClass.callSomeMethodThatThrows(); + } + catch(Exception ignored) {} + } + +} \ No newline at end of file diff --git a/libraries/pom.xml b/libraries/pom.xml index 7bef56deb02b..2ab345c46989 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -64,7 +64,7 @@ org.datanucleus datanucleus-api-jdo - ${datanucleus.version} + ${datanucleus-api.version} org.datanucleus @@ -86,17 +86,7 @@ datanucleus-jdo-query ${datanucleus-jdo-query.version} - - net.openhft - chronicle - ${chronicle.version} - - - com.sun.java - tools - - - + org.springframework spring-web @@ -180,6 +170,23 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-exports=java.base/jdk.internal.ref=ALL-UNNAMED + --add-exports=java.base/sun.nio.ch=ALL-UNNAMED + --add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + --add-opens=jdk.compiler/com.sun.tools.javac=ALL-UNNAMED + --add-opens=java.base/java.lang=ALL-UNNAMED + --add-opens=java.base/java.lang.reflect=ALL-UNNAMED + --add-opens=java.base/java.io=ALL-UNNAMED + --add-opens=java.base/java.util=ALL-UNNAMED + + + org.datanucleus @@ -273,16 +280,16 @@ 1.15 1.23.0 0.9.4.0006L - 3.2.0-m7 - 5.1.1 - 5.0.2 + 3.2.1 + 6.0.3 + 6.0.1 + 6.0.0-release 5.0.0-release - 5.0.2 - 3.6.4 + 6.0.1 4.3.8.RELEASE 3.0.3 2.3.0 - 3.21.0-GA + 3.29.2-GA 0.9.12 3.0.2 3.6 diff --git a/linux-bash/command-line-arguments/src/main/bash/README.md b/linux-bash-modules/command-line-arguments/src/main/bash/README.md similarity index 100% rename from linux-bash/command-line-arguments/src/main/bash/README.md rename to linux-bash-modules/command-line-arguments/src/main/bash/README.md diff --git a/linux-bash/command-line-arguments/src/main/bash/userReg-flags.sh b/linux-bash-modules/command-line-arguments/src/main/bash/userReg-flags.sh similarity index 100% rename from linux-bash/command-line-arguments/src/main/bash/userReg-flags.sh rename to linux-bash-modules/command-line-arguments/src/main/bash/userReg-flags.sh diff --git a/linux-bash/command-line-arguments/src/main/bash/userReg-positional-parameter.sh b/linux-bash-modules/command-line-arguments/src/main/bash/userReg-positional-parameter.sh similarity index 100% rename from linux-bash/command-line-arguments/src/main/bash/userReg-positional-parameter.sh rename to linux-bash-modules/command-line-arguments/src/main/bash/userReg-positional-parameter.sh diff --git a/linux-bash/command-line-arguments/src/main/bash/users-loop.sh b/linux-bash-modules/command-line-arguments/src/main/bash/users-loop.sh similarity index 100% rename from linux-bash/command-line-arguments/src/main/bash/users-loop.sh rename to linux-bash-modules/command-line-arguments/src/main/bash/users-loop.sh diff --git a/linux-bash/command-line-arguments/src/main/bash/users-shift-operator.sh b/linux-bash-modules/command-line-arguments/src/main/bash/users-shift-operator.sh similarity index 100% rename from linux-bash/command-line-arguments/src/main/bash/users-shift-operator.sh rename to linux-bash-modules/command-line-arguments/src/main/bash/users-shift-operator.sh diff --git a/linux-bash/functions/src/main/bash/README.md b/linux-bash-modules/functions/src/main/bash/README.md similarity index 100% rename from linux-bash/functions/src/main/bash/README.md rename to linux-bash-modules/functions/src/main/bash/README.md diff --git a/linux-bash/functions/src/main/bash/functions.sh b/linux-bash-modules/functions/src/main/bash/functions.sh similarity index 100% rename from linux-bash/functions/src/main/bash/functions.sh rename to linux-bash-modules/functions/src/main/bash/functions.sh diff --git a/linux-bash/functions/src/main/bash/infile b/linux-bash-modules/functions/src/main/bash/infile similarity index 100% rename from linux-bash/functions/src/main/bash/infile rename to linux-bash-modules/functions/src/main/bash/infile diff --git a/linux-bash/json/README.md b/linux-bash-modules/json/README.md similarity index 100% rename from linux-bash/json/README.md rename to linux-bash-modules/json/README.md diff --git a/linux-bash/json/src/main/bash/fruit.json b/linux-bash-modules/json/src/main/bash/fruit.json similarity index 100% rename from linux-bash/json/src/main/bash/fruit.json rename to linux-bash-modules/json/src/main/bash/fruit.json diff --git a/linux-bash/json/src/main/bash/fruits.json b/linux-bash-modules/json/src/main/bash/fruits.json similarity index 100% rename from linux-bash/json/src/main/bash/fruits.json rename to linux-bash-modules/json/src/main/bash/fruits.json diff --git a/linux-bash/json/src/main/bash/jq.sh b/linux-bash-modules/json/src/main/bash/jq.sh similarity index 100% rename from linux-bash/json/src/main/bash/jq.sh rename to linux-bash-modules/json/src/main/bash/jq.sh diff --git a/linux-bash/json/src/main/bash/wikipedia.json b/linux-bash-modules/json/src/main/bash/wikipedia.json similarity index 100% rename from linux-bash/json/src/main/bash/wikipedia.json rename to linux-bash-modules/json/src/main/bash/wikipedia.json diff --git a/linux-bash/loops/README.md b/linux-bash-modules/loops/README.md similarity index 100% rename from linux-bash/loops/README.md rename to linux-bash-modules/loops/README.md diff --git a/linux-bash/loops/src/main/bash/find_directories.sh b/linux-bash-modules/loops/src/main/bash/find_directories.sh similarity index 100% rename from linux-bash/loops/src/main/bash/find_directories.sh rename to linux-bash-modules/loops/src/main/bash/find_directories.sh diff --git a/linux-bash/loops/src/main/bash/loop_directories.sh b/linux-bash-modules/loops/src/main/bash/loop_directories.sh similarity index 100% rename from linux-bash/loops/src/main/bash/loop_directories.sh rename to linux-bash-modules/loops/src/main/bash/loop_directories.sh diff --git a/linux-bash/read/README.md b/linux-bash-modules/read/README.md similarity index 100% rename from linux-bash/read/README.md rename to linux-bash-modules/read/README.md diff --git a/linux-bash/read/src/main/bash/file.csv b/linux-bash-modules/read/src/main/bash/file.csv similarity index 100% rename from linux-bash/read/src/main/bash/file.csv rename to linux-bash-modules/read/src/main/bash/file.csv diff --git a/linux-bash/read/src/main/bash/read_inputs.sh b/linux-bash-modules/read/src/main/bash/read_inputs.sh similarity index 100% rename from linux-bash/read/src/main/bash/read_inputs.sh rename to linux-bash-modules/read/src/main/bash/read_inputs.sh diff --git a/linux-bash/text/README.md b/linux-bash-modules/text/README.md similarity index 100% rename from linux-bash/text/README.md rename to linux-bash-modules/text/README.md diff --git a/linux-bash/text/src/main/bash/append_multiple_lines.sh b/linux-bash-modules/text/src/main/bash/append_multiple_lines.sh similarity index 100% rename from linux-bash/text/src/main/bash/append_multiple_lines.sh rename to linux-bash-modules/text/src/main/bash/append_multiple_lines.sh diff --git a/linux-bash/text/src/main/bash/remove_characters.sh b/linux-bash-modules/text/src/main/bash/remove_characters.sh similarity index 100% rename from linux-bash/text/src/main/bash/remove_characters.sh rename to linux-bash-modules/text/src/main/bash/remove_characters.sh diff --git a/logging-modules/log4j2/pom.xml b/logging-modules/log4j2/pom.xml index 50c71145565b..da2984442c56 100644 --- a/logging-modules/log4j2/pom.xml +++ b/logging-modules/log4j2/pom.xml @@ -63,51 +63,23 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} none + + org.apache.maven.plugins + maven-surefire-plugin + + + json + ${java.io.tmpdir}/${maven.build.timestamp}/logfile.json + + + - - - integration-lite-first - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - json - ${java.io.tmpdir}/${maven.build.timestamp}/logfile.json - - - - - - - 2.9.0 diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java index 3e94e4e43061..06fbb33b9d53 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java @@ -21,7 +21,7 @@ @RunWith(JUnit4.class) public class CustomLoggingIntegrationTest { - + private static String logFilePath = System.getProperty("logging.folder.path"); @BeforeClass @@ -34,7 +34,7 @@ public static void setup() throws Exception { } @Test - public void givenLoggerWithDefaultConfig_whenLogToConsole_thanOK() throws Exception { + public void givenLoggerWithDefaultConfig_whenLogToConsole_thenOK() throws Exception { Logger logger = LogManager.getLogger(getClass()); Exception e = new RuntimeException("This is only a test!"); @@ -43,7 +43,7 @@ public void givenLoggerWithDefaultConfig_whenLogToConsole_thanOK() throws Except } @Test - public void givenLoggerWithConsoleConfig_whenLogToConsoleInColors_thanOK() throws Exception { + public void givenLoggerWithConsoleConfig_whenLogToConsoleInColors_thenOK() throws Exception { Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER"); Exception e = new RuntimeException("This is only a test!"); @@ -56,7 +56,7 @@ public void givenLoggerWithConsoleConfig_whenLogToConsoleInColors_thanOK() throw } @Test - public void givenLoggerWithConsoleConfig_whenFilterByMarker_thanOK() throws Exception { + public void givenLoggerWithConsoleConfig_whenFilterByMarker_thenOK() throws Exception { Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER"); Marker appError = MarkerManager.getMarker("APP_ERROR"); Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE"); @@ -66,7 +66,7 @@ public void givenLoggerWithConsoleConfig_whenFilterByMarker_thanOK() throws Exce } @Test - public void givenLoggerWithConsoleConfig_whenFilterByThreadContext_thanOK() throws Exception { + public void givenLoggerWithConsoleConfig_whenFilterByThreadContext_thenOK() throws Exception { Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_THREAD_CONTEXT"); ThreadContext.put("userId", "1000"); logger.info("This is a log-visible user login. Maybe from an admin account?"); @@ -75,7 +75,7 @@ public void givenLoggerWithConsoleConfig_whenFilterByThreadContext_thanOK() thro } @Test - public void givenLoggerWithAsyncConfig_whenLogToJsonFile_thanOK() throws Exception { + public void givenLoggerWithAsyncConfig_whenLogToJsonFile_thenOK() throws Exception { Logger logger = LogManager.getLogger("ASYNC_JSON_FILE_APPENDER"); final int count = 88; @@ -90,7 +90,7 @@ public void givenLoggerWithAsyncConfig_whenLogToJsonFile_thanOK() throws Excepti } @Test - public void givenLoggerWithFailoverConfig_whenLog_thanOK() throws Exception { + public void givenLoggerWithFailoverConfig_whenLog_thenOK() throws Exception { Logger logger = LogManager.getLogger("FAIL_OVER_SYSLOG_APPENDER"); Exception e = new RuntimeException("This is only a test!"); @@ -103,7 +103,7 @@ public void givenLoggerWithFailoverConfig_whenLog_thanOK() throws Exception { } @Test - public void givenLoggerWithJdbcConfig_whenLogToDataSource_thanOK() throws Exception { + public void givenLoggerWithJdbcConfig_whenLogToDataSource_thenOK() throws Exception { Logger logger = LogManager.getLogger("JDBC_APPENDER"); final int count = 88; @@ -122,7 +122,7 @@ public void givenLoggerWithJdbcConfig_whenLogToDataSource_thanOK() throws Except } @Test - public void givenLoggerWithRollingFileConfig_whenLogToXMLFile_thanOK() throws Exception { + public void givenLoggerWithRollingFileConfig_whenLogToXMLFile_thenOK() throws Exception { Logger logger = LogManager.getLogger("XML_ROLLING_FILE_APPENDER"); final int count = 88; diff --git a/logging-modules/log4j2/src/test/resources/log4j2.xml b/logging-modules/log4j2/src/test/resources/log4j2.xml index 050e0aa705c0..6516d9884ce3 100644 --- a/logging-modules/log4j2/src/test/resources/log4j2.xml +++ b/logging-modules/log4j2/src/test/resources/log4j2.xml @@ -1,5 +1,5 @@ - - + diff --git a/logging-modules/logback/pom.xml b/logging-modules/logback/pom.xml index bef4b25f1bb5..e7313d902a63 100644 --- a/logging-modules/logback/pom.xml +++ b/logging-modules/logback/pom.xml @@ -39,11 +39,11 @@ logback-jackson ${logback.contrib.version} - - org.slf4j - slf4j-api - ${slf4j.version} - + + org.slf4j + slf4j-api + ${slf4j.version} + com.fasterxml.jackson.core jackson-databind diff --git a/lombok-modules/lombok-2/README.md b/lombok-modules/lombok-2/README.md index d3b128734633..fcee23fc82b8 100644 --- a/lombok-modules/lombok-2/README.md +++ b/lombok-modules/lombok-2/README.md @@ -9,4 +9,7 @@ This module contains articles about Project Lombok. - [Lombok Using @With Annotations](https://www.baeldung.com/lombok-with-annotations) - [Lombok’s @ToString Annotation](https://www.baeldung.com/lombok-tostring) - [Jackson’s Deserialization With Lombok](https://www.baeldung.com/java-jackson-deserialization-lombok) +- [Constructor Injection in Spring with Lombok](https://www.baeldung.com/spring-injection-lombok) +- [@StandardException Annotation in Lombok](https://www.baeldung.com/lombok-standardexception-annotation) +- [Lombok EqualsAndHashCode Annotation](https://www.baeldung.com/java-lombok-equalsandhashcode) - More articles: [[<-- prev]](../lombok) diff --git a/lombok-modules/lombok-2/pom.xml b/lombok-modules/lombok-2/pom.xml index 0a7ad27ad63c..88fbaf530fab 100644 --- a/lombok-modules/lombok-2/pom.xml +++ b/lombok-modules/lombok-2/pom.xml @@ -25,6 +25,10 @@ jackson-databind ${jackson.version} + + org.springframework.boot + spring-boot-starter-web + \ No newline at end of file diff --git a/spring-core-4/src/main/java/com/baeldung/lombok/ApologizeService.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/ApologizeService.java similarity index 100% rename from spring-core-4/src/main/java/com/baeldung/lombok/ApologizeService.java rename to lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/ApologizeService.java diff --git a/spring-core-4/src/main/java/com/baeldung/lombok/FarewellService.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/FarewellService.java similarity index 100% rename from spring-core-4/src/main/java/com/baeldung/lombok/FarewellService.java rename to lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/FarewellService.java diff --git a/spring-core-4/src/main/java/com/baeldung/lombok/GreetingService.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/GreetingService.java similarity index 100% rename from spring-core-4/src/main/java/com/baeldung/lombok/GreetingService.java rename to lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/GreetingService.java diff --git a/spring-core-4/src/main/java/com/baeldung/lombok/ThankingService.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/ThankingService.java similarity index 100% rename from spring-core-4/src/main/java/com/baeldung/lombok/ThankingService.java rename to lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/ThankingService.java diff --git a/spring-core-4/src/main/java/com/baeldung/lombok/Translator.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/Translator.java similarity index 100% rename from spring-core-4/src/main/java/com/baeldung/lombok/Translator.java rename to lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/Translator.java diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/Employee.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/Employee.java new file mode 100644 index 000000000000..6f0ac60cca09 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/Employee.java @@ -0,0 +1,14 @@ +package com.baeldung.lombok.equalsandhashcode; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; + +@Getter +@EqualsAndHashCode +@AllArgsConstructor +public class Employee { + private String name; + private int id; + private int age; +} diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/EmployeeDelomboked.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/EmployeeDelomboked.java new file mode 100644 index 000000000000..afae2d4c17a3 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/EmployeeDelomboked.java @@ -0,0 +1,57 @@ +package com.baeldung.lombok.equalsandhashcode; + +import lombok.Getter; + +@Getter +public class EmployeeDelomboked { + + private String name; + private int id; + private int age; + + public EmployeeDelomboked() { + } + + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (!(o instanceof Employee)) { + return false; + } else { + Employee other = (Employee) o; + if (!other.canEqual(this)) { + return false; + } else if (this.getId() != other.getId()) { + return false; + } else if (this.getAge() != other.getAge()) { + return false; + } else { + Object this$name = this.getName(); + Object other$name = other.getName(); + if (this$name == null) { + if (other$name == null) { + return true; + } + } else if (this$name.equals(other$name)) { + return true; + } + + return false; + } + } + } + + protected boolean canEqual(Object other) { + return other instanceof Employee; + } + + public int hashCode() { + final int PRIME = 59; + int result = 1; + result = result * PRIME + this.getId(); + result = result * PRIME + this.getAge(); + Object $name = this.getName(); + result = result * PRIME + ($name == null ? 43 : $name.hashCode()); + return result; + } +} diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/commonissue/Employee.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/commonissue/Employee.java new file mode 100644 index 000000000000..91090a4a8c9c --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/commonissue/Employee.java @@ -0,0 +1,20 @@ +package com.baeldung.lombok.equalsandhashcode.commonissue; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@EqualsAndHashCode +@AllArgsConstructor +@NoArgsConstructor +public class Employee { + private String name; + private int id; + private int age; + private Manager manager; +} + diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/commonissue/EmployeeV2.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/commonissue/EmployeeV2.java new file mode 100644 index 000000000000..02bbbacaedae --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/commonissue/EmployeeV2.java @@ -0,0 +1,17 @@ +package com.baeldung.lombok.equalsandhashcode.commonissue; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@EqualsAndHashCode(exclude = "manager") +@AllArgsConstructor +public class EmployeeV2 { + private String name; + private int id; + private int age; + private ManagerV2 manager; +} diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/commonissue/Manager.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/commonissue/Manager.java new file mode 100644 index 000000000000..aa6221d54a12 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/commonissue/Manager.java @@ -0,0 +1,16 @@ +package com.baeldung.lombok.equalsandhashcode.commonissue; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@EqualsAndHashCode +@AllArgsConstructor +public class Manager { + private String name; + private Employee assistantManager; +} + diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/commonissue/ManagerV2.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/commonissue/ManagerV2.java new file mode 100644 index 000000000000..67068341f3c7 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/commonissue/ManagerV2.java @@ -0,0 +1,16 @@ +package com.baeldung.lombok.equalsandhashcode.commonissue; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@EqualsAndHashCode +@AllArgsConstructor +public class ManagerV2 { + private String name; + private EmployeeV2 assistantManager; +} + diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/exclude/classlevel/Employee.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/exclude/classlevel/Employee.java new file mode 100644 index 000000000000..64c95d0e7b18 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/exclude/classlevel/Employee.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok.equalsandhashcode.exclude.classlevel; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; + +@Getter +@EqualsAndHashCode(exclude = {"id", "age"}) +@AllArgsConstructor +public class Employee { + private String name; + private int id; + private int age; +} + diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/exclude/classlevel/EmployeeDelomboked.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/exclude/classlevel/EmployeeDelomboked.java new file mode 100644 index 000000000000..edf70689e15e --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/exclude/classlevel/EmployeeDelomboked.java @@ -0,0 +1,37 @@ +package com.baeldung.lombok.equalsandhashcode.exclude.classlevel; + + +import lombok.Getter; + +@Getter +public class EmployeeDelomboked { + private String name; + private int id; + private int age; + + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof Employee)) return false; + final Employee other = (Employee) o; + if (!other.canEqual((Object) this)) return false; + final Object this$name = this.getName(); + final Object other$name = other.getName(); + if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; + return true; + } + + protected boolean canEqual(final Object other) { + return other instanceof Employee; + } + + @Override + public int hashCode() { + final int PRIME = 59; + int result = 1; + final Object $name = this.getName(); + result = result * PRIME + ($name == null ? 43 : $name.hashCode()); + return result; + } +} + diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/exclude/fieldlevel/Employee.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/exclude/fieldlevel/Employee.java new file mode 100644 index 000000000000..a03d1fc43aa5 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/exclude/fieldlevel/Employee.java @@ -0,0 +1,18 @@ +package com.baeldung.lombok.equalsandhashcode.exclude.fieldlevel; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; + +@Getter +@EqualsAndHashCode +@AllArgsConstructor +public class Employee { + private String name; + @EqualsAndHashCode.Exclude + private int id; + @EqualsAndHashCode.Exclude + private int age; +} + + diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/exclude/fieldlevel/EmployeeDelomboked.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/exclude/fieldlevel/EmployeeDelomboked.java new file mode 100644 index 000000000000..f30ab6f709d3 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/exclude/fieldlevel/EmployeeDelomboked.java @@ -0,0 +1,31 @@ +package com.baeldung.lombok.equalsandhashcode.exclude.fieldlevel; + + +import lombok.Getter; + +@Getter +public class EmployeeDelomboked { + private String name; + private int id; + private int age; + + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof com.baeldung.lombok.equalsandhashcode.exclude.fieldlevel.Employee)) return false; + final com.baeldung.lombok.equalsandhashcode.exclude.fieldlevel.Employee other = (com.baeldung.lombok.equalsandhashcode.exclude.fieldlevel.Employee) o; + if (!other.canEqual((Object) this)) return false; + final Object this$name = this.getName(); + final Object other$name = other.getName(); + if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; + return true; + } + + public int hashCode() { + final int PRIME = 59; + int result = 1; + final Object $name = this.getName(); + result = result * PRIME + ($name == null ? 43 : $name.hashCode()); + return result; + } +} + diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/include/classlevel/Employee.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/include/classlevel/Employee.java new file mode 100644 index 000000000000..e353c27dfdaf --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/include/classlevel/Employee.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok.equalsandhashcode.include.classlevel; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(of = {"name", "id"}) +@AllArgsConstructor +public class Employee { + private String name; + private int id; + private int age; +} + diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/include/fieldlevel/Employee.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/include/fieldlevel/Employee.java new file mode 100644 index 000000000000..c1d4ab5b0ff6 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/include/fieldlevel/Employee.java @@ -0,0 +1,18 @@ +package com.baeldung.lombok.equalsandhashcode.include.fieldlevel; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; + +@Getter +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +@AllArgsConstructor +public class Employee { + @EqualsAndHashCode.Include + private String name; + @EqualsAndHashCode.Include + private int id; + private int age; +} + + diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/include/methodlevel/Employee.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/include/methodlevel/Employee.java new file mode 100644 index 000000000000..3de8cc2c6930 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/include/methodlevel/Employee.java @@ -0,0 +1,20 @@ +package com.baeldung.lombok.equalsandhashcode.include.methodlevel; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; + +@Getter +@EqualsAndHashCode +@AllArgsConstructor +public class Employee { + private String name; + private int id; + private int age; + + @EqualsAndHashCode.Include + public boolean hasOddId() { + return id % 2 != 0; + } +} + diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/include/methodlevel/EmployeeDelomboked.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/include/methodlevel/EmployeeDelomboked.java new file mode 100644 index 000000000000..f25b996fe1d1 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/include/methodlevel/EmployeeDelomboked.java @@ -0,0 +1,40 @@ +package com.baeldung.lombok.equalsandhashcode.include.methodlevel; + +import lombok.Getter; + +@Getter +public class EmployeeDelomboked { + private String name; + private int id; + private int age; + + public boolean hasOddId() { + return id % 2 != 0; + } + + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof Employee)) return false; + final Employee other = (Employee) o; + if (!other.canEqual((Object) this)) return false; + if (this.getId() != other.getId()) return false; + if (this.getAge() != other.getAge()) return false; + if (this.hasOddId() != other.hasOddId()) return false; + final Object this$name = this.getName(); + final Object other$name = other.getName(); + if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; + return true; + } + + public int hashCode() { + final int PRIME = 59; + int result = 1; + result = result * PRIME + this.getId(); + result = result * PRIME + this.getAge(); + result = result * PRIME + (this.hasOddId() ? 79 : 97); + final Object $name = this.getName(); + result = result * PRIME + ($name == null ? 43 : $name.hashCode()); + return result; + } +} + diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/inheritance/Employee.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/inheritance/Employee.java new file mode 100644 index 000000000000..de63755cfca9 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/inheritance/Employee.java @@ -0,0 +1,16 @@ +package com.baeldung.lombok.equalsandhashcode.inheritance; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@EqualsAndHashCode +@AllArgsConstructor +public class Employee { + private String name; + private int id; + private int age; +} diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/inheritance/Manager.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/inheritance/Manager.java new file mode 100644 index 000000000000..e943940c3238 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/inheritance/Manager.java @@ -0,0 +1,20 @@ +package com.baeldung.lombok.equalsandhashcode.inheritance; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@EqualsAndHashCode(callSuper = true) +public class Manager extends Employee { + private String departmentName; + private int uid; + + public Manager(String departmentName, int uid, String name, int id, int age) { + super(name, id, age); + this.departmentName = departmentName; + this.uid = uid; + } +} diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/inheritance/ManagerDelomboked.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/inheritance/ManagerDelomboked.java new file mode 100644 index 000000000000..e14b4a1f108f --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/inheritance/ManagerDelomboked.java @@ -0,0 +1,37 @@ +package com.baeldung.lombok.equalsandhashcode.inheritance; + +import lombok.Getter; + +@Getter +public class ManagerDelomboked extends Employee { + private String departmentName; + private int uid; + + public ManagerDelomboked(String departmentName, int uid, String name, int id, int age) { + super(name, id, age); + this.departmentName = departmentName; + this.uid = uid; + } + + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof com.baeldung.lombok.equalsandhashcode.inheritance.Manager)) return false; + final com.baeldung.lombok.equalsandhashcode.inheritance.Manager other = (com.baeldung.lombok.equalsandhashcode.inheritance.Manager) o; + if (!other.canEqual((Object) this)) return false; + if (!super.equals(o)) return false; + if (this.getUid() != other.getUid()) return false; + final Object this$departmentName = this.getDepartmentName(); + final Object other$departmentName = other.getDepartmentName(); + if (this$departmentName == null ? other$departmentName != null : !this$departmentName.equals(other$departmentName)) return false; + return true; + } + + public int hashCode() { + final int PRIME = 59; + int result = super.hashCode(); + result = result * PRIME + this.getUid(); + final Object $departmentName = this.getDepartmentName(); + result = result * PRIME + ($departmentName == null ? 43 : $departmentName.hashCode()); + return result; + } +} diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/inheritance/ManagerV2.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/inheritance/ManagerV2.java new file mode 100644 index 000000000000..b5bdfd08912c --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/equalsandhashcode/inheritance/ManagerV2.java @@ -0,0 +1,19 @@ +package com.baeldung.lombok.equalsandhashcode.inheritance; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +public class ManagerV2 extends Employee { + private String departmentName; + private int uid; + + public ManagerV2(String departmentName, int uid, String name, int id, int age) { + super(name, id, age); + this.departmentName = departmentName; + this.uid = uid; + } +} diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/standardexception/CustomException.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/standardexception/CustomException.java new file mode 100644 index 000000000000..bee85b339814 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/standardexception/CustomException.java @@ -0,0 +1,7 @@ +package com.baeldung.lombok.standardexception; + +import lombok.experimental.StandardException; + +@StandardException +public class CustomException extends NumberFormatException { +} diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/standardexception/CustomNumberFormatException.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/standardexception/CustomNumberFormatException.java new file mode 100644 index 000000000000..fbd98cac1643 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/standardexception/CustomNumberFormatException.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.standardexception; + +public class CustomNumberFormatException extends NumberFormatException { + public CustomNumberFormatException() { + super(); + } + + public CustomNumberFormatException(String s) { + super(s); + } +} \ No newline at end of file diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/valvar/ValExample.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/valvar/ValExample.java index b7ecd95fa82f..f436ef81dd8d 100644 --- a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/valvar/ValExample.java +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/valvar/ValExample.java @@ -1,7 +1,6 @@ package com.baeldung.lombok.valvar; import lombok.val; -import lombok.var; import java.util.ArrayList; import java.util.HashMap; diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/valvar/VarExample.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/valvar/VarExample.java index 6fabf66590f0..138264db0925 100644 --- a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/valvar/VarExample.java +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/valvar/VarExample.java @@ -1,6 +1,5 @@ package com.baeldung.lombok.valvar; -import lombok.var; import java.util.ArrayList; import java.util.Arrays; diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringIntegrationTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringIntegrationTest.java similarity index 100% rename from spring-core-4/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringIntegrationTest.java rename to lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringIntegrationTest.java diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/ApologizeServiceIntegrationTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/ApologizeServiceIntegrationTest.java similarity index 100% rename from spring-core-4/src/test/java/com/baeldung/lombok/ApologizeServiceIntegrationTest.java rename to lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/ApologizeServiceIntegrationTest.java diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/FarewellAutowiringIntegrationTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/FarewellAutowiringIntegrationTest.java similarity index 100% rename from spring-core-4/src/test/java/com/baeldung/lombok/FarewellAutowiringIntegrationTest.java rename to lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/FarewellAutowiringIntegrationTest.java diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/FarewellServiceIntegrationTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/FarewellServiceIntegrationTest.java similarity index 100% rename from spring-core-4/src/test/java/com/baeldung/lombok/FarewellServiceIntegrationTest.java rename to lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/FarewellServiceIntegrationTest.java diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/GreetingServiceIntegrationTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/GreetingServiceIntegrationTest.java similarity index 100% rename from spring-core-4/src/test/java/com/baeldung/lombok/GreetingServiceIntegrationTest.java rename to lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/GreetingServiceIntegrationTest.java diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/TestConfig.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/TestConfig.java similarity index 100% rename from spring-core-4/src/test/java/com/baeldung/lombok/TestConfig.java rename to lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/TestConfig.java diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringIntegrationTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringIntegrationTest.java similarity index 100% rename from spring-core-4/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringIntegrationTest.java rename to lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringIntegrationTest.java diff --git a/spring-core-4/src/test/java/com/baeldung/lombok/ThankingServiceIntegrationTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/ThankingServiceIntegrationTest.java similarity index 100% rename from spring-core-4/src/test/java/com/baeldung/lombok/ThankingServiceIntegrationTest.java rename to lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/ThankingServiceIntegrationTest.java diff --git a/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/EqualsAndHashCodeUnitTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/EqualsAndHashCodeUnitTest.java new file mode 100644 index 000000000000..614e94ea595f --- /dev/null +++ b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/EqualsAndHashCodeUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.lombok.equalsandhashcode; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class EqualsAndHashCodeUnitTest { + + @Test + public void whenUsingEqualsAndHashCodeOnClassLevel_thenTwoObjectsAreEqualAndHaveSameHashCodeIfAllFieldsAreSame() { + Employee employee = new Employee("Nimi", 15, 22); + Employee employeeTwo = new Employee("Nimi", 15, 22); + Employee employeeThree = new Employee("Mannat", 15, 22); + assertEquals(employee, employeeTwo); + assertNotEquals(employee, employeeThree); + assertEquals(employee.hashCode(), employeeTwo.hashCode()); + assertNotEquals(employee.hashCode(), employeeThree.hashCode()); + } +} diff --git a/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/commonissue/EqualsAndHashCodeUnitTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/commonissue/EqualsAndHashCodeUnitTest.java new file mode 100644 index 000000000000..207e4e0636f0 --- /dev/null +++ b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/commonissue/EqualsAndHashCodeUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.lombok.equalsandhashcode.commonissue; + +import org.junit.Test; + +public class EqualsAndHashCodeUnitTest { + + @Test(expected = StackOverflowError.class) + public void whenUsingEqualsAndHashInObjectWithCircularDependency_thenCallingEqualsAndHasCodeWillThrowStackOverFlowError() { + Manager manager = new Manager("Mannat", null); + + Employee employee = new Employee("Nimi", 15, 22, manager); + + manager.setAssistantManager(employee); + + employee.setManager(manager); + + int hash = employee.hashCode(); + + } + + @Test + public void whenUsingEqualsAndHashInObjectAndExcludingCircularDependencyField_thenNoStackOverFlowError() { + ManagerV2 manager = new ManagerV2("Mannat", null); + + EmployeeV2 employee = new EmployeeV2("Nimi", 15, 22, manager); + + manager.setAssistantManager(employee); + + employee.setManager(manager); + + int hash = employee.hashCode(); + + } +} diff --git a/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/exclude/classlevel/EqualsAndHashCodeUnitTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/exclude/classlevel/EqualsAndHashCodeUnitTest.java new file mode 100644 index 000000000000..be086ff7dffb --- /dev/null +++ b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/exclude/classlevel/EqualsAndHashCodeUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.lombok.equalsandhashcode.exclude.classlevel; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class EqualsAndHashCodeUnitTest { + + @Test + public void whenUsingEqualsAndHashCodeOnClassLevelAndExcludingFields_thenTwoObjectsAreEqualAndHaveSameHashCodeEvenIfExcludedFieldsAreNotSame() { + Employee employee = new Employee("Nimi", 15, 22); + Employee employeeTwo = new Employee("Nimi", 17, 21); + + assertEquals(employee, employeeTwo); + assertEquals(employee.hashCode(), employeeTwo.hashCode()); + } +} diff --git a/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/exclude/fieldLevel/EqualsAndHashCodeUnitTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/exclude/fieldLevel/EqualsAndHashCodeUnitTest.java new file mode 100644 index 000000000000..832b188509e8 --- /dev/null +++ b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/exclude/fieldLevel/EqualsAndHashCodeUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.lombok.equalsandhashcode.exclude.fieldLevel; + +import com.baeldung.lombok.equalsandhashcode.exclude.fieldlevel.Employee; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class EqualsAndHashCodeUnitTest { + + @Test + public void whenUsingEqualsAndHashCodeWithExcludingFields_thenTwoObjectsAreEqualAndHaveSameHashCodeEvenIfExcludedFieldsAreNotSame() { + Employee employee = new Employee("Nimi", 15, 22); + Employee employeeTwo = new Employee("Nimi", 17, 21); + + assertEquals(employee, employeeTwo); + assertEquals(employee.hashCode(), employeeTwo.hashCode()); + } +} diff --git a/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/include/classlevel/EqualsAndHashCodeUnitTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/include/classlevel/EqualsAndHashCodeUnitTest.java new file mode 100644 index 000000000000..1641966fd218 --- /dev/null +++ b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/include/classlevel/EqualsAndHashCodeUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.lombok.equalsandhashcode.include.classlevel; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class EqualsAndHashCodeUnitTest { + + @Test + public void whenUsingEqualsAndHashCodeOnClassLevelAndIncludeFields_thenTwoObjectsAreEqualAndHaveSameHashCodeIfIncludedFieldsAreSame() { + Employee employee = new Employee("Nimi", 15, 22); + Employee employeeTwo = new Employee("Nimi", 15, 22); + Employee employeeThree = new Employee("Nimi", 15, 23); + + assertEquals(employee, employeeTwo); + assertEquals(employee, employeeThree); + + assertEquals(employee.hashCode(), employeeTwo.hashCode()); + assertEquals(employee.hashCode(), employeeThree.hashCode()); + } +} diff --git a/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/include/fieldlevel/EqualsAndHashCodeUnitTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/include/fieldlevel/EqualsAndHashCodeUnitTest.java new file mode 100644 index 000000000000..dcf6123d2a31 --- /dev/null +++ b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/include/fieldlevel/EqualsAndHashCodeUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.lombok.equalsandhashcode.include.fieldlevel; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class EqualsAndHashCodeUnitTest { + + @Test + public void whenUsingEqualsAndHashCodeOnFieldLevel_thenTwoObjectsAreEqualAndHaveSameHashCodeIfIncludedFieldsAreSame() { + Employee employee = new Employee("Nimi", 15, 22); + Employee employeeTwo = new Employee("Nimi", 15, 22); + Employee employeeThree = new Employee("Nimi", 15, 23); + + assertEquals(employee, employeeTwo); + assertEquals(employee, employeeThree); + + assertEquals(employee.hashCode(), employeeTwo.hashCode()); + assertEquals(employee.hashCode(), employeeThree.hashCode()); + } +} diff --git a/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/include/methodlevel/EqualsAndHashCodeUnitTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/include/methodlevel/EqualsAndHashCodeUnitTest.java new file mode 100644 index 000000000000..79d673b4a424 --- /dev/null +++ b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/include/methodlevel/EqualsAndHashCodeUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.lombok.equalsandhashcode.include.methodlevel; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class EqualsAndHashCodeUnitTest { + + @Test + public void whenUsingEqualsAndHashCodeOnMethodLevel_thenTwoObjectsAreEqualAndHaveSameHashCodeIfMethodsReturnSameValue() { + Employee employee = new Employee("Nimi", 15, 22); + Employee employeeTwo = new Employee("Nimi", 15, 22); + Employee employeeThree = new Employee("Nimi", 15, 23); + + assertEquals(employee, employeeTwo); + assertNotEquals(employee, employeeThree); + + assertEquals(employee.hashCode(), employeeTwo.hashCode()); + assertNotEquals(employee.hashCode(), employeeThree.hashCode()); + } +} diff --git a/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/inheritance/EqualsAndHashCodeUnitTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/inheritance/EqualsAndHashCodeUnitTest.java new file mode 100644 index 000000000000..abf71fe83fdd --- /dev/null +++ b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/equalsandhashcode/inheritance/EqualsAndHashCodeUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.lombok.equalsandhashcode.inheritance; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class EqualsAndHashCodeUnitTest { + + @Test + public void whenUsingEqualsAndHashCodeAndCallSuperIsTrue_thenTwoObjectsAreEqualAndHaveSameHashCodeIfAllFieldsIncludingParentsFieldsAreSame() { + Manager manager = new Manager("Opto", 444, "Nimi", 15, 22); + Manager managerTwo = new Manager("Opto", 444, "Nimi", 15, 22); + Manager managerThree = new Manager("Opto", 444, "Nimi", 15, 23); + + assertEquals(manager, managerTwo); + assertNotEquals(managerTwo, managerThree); + + } + + @Test + public void whenUsingEqualsAndHashCodeAndCallSuperIsFalse_thenTwoObjectsAreEqualAndHaveSameHashCodeEvenIfAllParentsFieldsAreNotSame() { + ManagerV2 manager = new ManagerV2("Opto", 444, "Nimi", 15, 22); + ManagerV2 managerTwo = new ManagerV2("Opto", 444, "Nimi", 15, 22); + ManagerV2 managerThree = new ManagerV2("Opto", 444, "Nimi", 14, 21); + assertEquals(manager, managerTwo); + assertEquals(managerTwo, managerThree); + } +} diff --git a/lombok-modules/lombok-custom/pom.xml b/lombok-modules/lombok-custom/pom.xml index c119900c8ace..1f7f630772b6 100644 --- a/lombok-modules/lombok-custom/pom.xml +++ b/lombok-modules/lombok-custom/pom.xml @@ -53,11 +53,27 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + 1.14.8 1.8 3.3.0-v_771 + 1.8 + 1.8 \ No newline at end of file diff --git a/lombok-modules/lombok/pom.xml b/lombok-modules/lombok/pom.xml index 1be22f0bc2b7..57b2a5a99973 100644 --- a/lombok-modules/lombok/pom.xml +++ b/lombok-modules/lombok/pom.xml @@ -40,41 +40,19 @@ true - - - org.projectlombok - lombok-maven-plugin - ${delombok-maven-plugin.version} - - - delombok - generate-sources - - delombok - - - ${project.basedir}/src/main/java - ${project.build.directory}/delombok - false - - skip - - false - - - - - - - - - + edge-SNAPSHOT 1.0.0.Final 1.18.20.0 23.0.0 + + + projectlombok.org + https://projectlombok.org/edge-releases + + \ No newline at end of file diff --git a/lombok-modules/pom.xml b/lombok-modules/pom.xml index 7ca303af9da2..46d91462fbd7 100644 --- a/lombok-modules/pom.xml +++ b/lombok-modules/pom.xml @@ -18,10 +18,21 @@ lombok lombok-2 - lombok-custom + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + @@ -32,4 +43,9 @@ + + 11 + 11 + + \ No newline at end of file diff --git a/mapstruct/README.md b/mapstruct/README.md index 384bcbaa14d6..46a9f8b2136a 100644 --- a/mapstruct/README.md +++ b/mapstruct/README.md @@ -9,3 +9,4 @@ This module contains articles about MapStruct. - [Using Multiple Source Objects with MapStruct](https://www.baeldung.com/mapstruct-multiple-source-objects) - [Ignoring Unmapped Properties with MapStruct](https://www.baeldung.com/mapstruct-ignore-unmapped-properties) - [Mapping Collections with MapStruct](https://www.baeldung.com/java-mapstruct-mapping-collections) +- [Use Mapper in Another Mapper with Mapstruct and Java](https://www.baeldung.com/java-mapstruct-nested-mapping) diff --git a/mapstruct/src/main/java/com/baeldung/dto/ArticleDTO.java b/mapstruct/src/main/java/com/baeldung/dto/ArticleDTO.java new file mode 100644 index 000000000000..708167de949a --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/dto/ArticleDTO.java @@ -0,0 +1,12 @@ +package com.baeldung.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class ArticleDTO { + private int id; + private String name; + private PersonDTO author; +} diff --git a/mapstruct/src/main/java/com/baeldung/entity/Article.java b/mapstruct/src/main/java/com/baeldung/entity/Article.java new file mode 100644 index 000000000000..4aff8f416673 --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/entity/Article.java @@ -0,0 +1,12 @@ +package com.baeldung.entity; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class Article { + private int id; + private String name; + private Person author; +} diff --git a/mapstruct/src/main/java/com/baeldung/mapper/ArticleMapper.java b/mapstruct/src/main/java/com/baeldung/mapper/ArticleMapper.java new file mode 100644 index 000000000000..b5b47f6b3b51 --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/mapper/ArticleMapper.java @@ -0,0 +1,20 @@ +package com.baeldung.mapper; + +import com.baeldung.dto.ArticleDTO; +import com.baeldung.dto.PersonDTO; +import com.baeldung.entity.Article; +import com.baeldung.entity.Person; +import org.mapstruct.Mapper; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface ArticleMapper { + + ArticleMapper INSTANCE = Mappers.getMapper(ArticleMapper.class); + + ArticleDTO articleToArticleDto(Article article); + + default PersonDTO personToPersonDto(Person person) { + return Mappers.getMapper(PersonMapper.class).personToPersonDTO(person); + } +} diff --git a/mapstruct/src/main/java/com/baeldung/mapper/ArticleUsingPersonMapper.java b/mapstruct/src/main/java/com/baeldung/mapper/ArticleUsingPersonMapper.java new file mode 100644 index 000000000000..c1ea0797ed0f --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/mapper/ArticleUsingPersonMapper.java @@ -0,0 +1,16 @@ +package com.baeldung.mapper; + +import com.baeldung.dto.ArticleDTO; +import com.baeldung.dto.PersonDTO; +import com.baeldung.entity.Article; +import com.baeldung.entity.Person; +import org.mapstruct.Mapper; +import org.mapstruct.factory.Mappers; + +@Mapper(uses = PersonMapper.class) +public interface ArticleUsingPersonMapper { + + ArticleUsingPersonMapper INSTANCE = Mappers.getMapper(ArticleUsingPersonMapper.class); + + ArticleDTO articleToArticleDto(Article article); +} diff --git a/mapstruct/src/test/java/com/baeldung/mapper/ArticleMapperUnitTest.java b/mapstruct/src/test/java/com/baeldung/mapper/ArticleMapperUnitTest.java new file mode 100644 index 000000000000..2470915a0190 --- /dev/null +++ b/mapstruct/src/test/java/com/baeldung/mapper/ArticleMapperUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.mapper; + +import com.baeldung.dto.ArticleDTO; +import com.baeldung.dto.CarDTO; +import com.baeldung.entity.Article; +import com.baeldung.entity.Car; +import com.baeldung.entity.Person; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ArticleMapperUnitTest { + + @Test + public void givenArticle_whenMaps_thenProducesCorrectDto() { + + Article entity = new Article(); + entity.setId(1); + entity.setName("Mapstruct Mapping"); + Person author = new Person(); + author.setId("1"); + author.setName("John"); + entity.setAuthor(author); + + ArticleDTO articleDTO = ArticleMapper.INSTANCE.articleToArticleDto(entity); + + assertEquals(articleDTO.getId(), entity.getId()); + assertEquals(articleDTO.getName(), entity.getName()); + assertEquals(articleDTO.getAuthor().getName(), entity.getAuthor().getName()); + } + + @Test + public void givenArticle_whenMapsWithUses_thenProducesCorrectDto() { + + Article entity = new Article(); + entity.setId(1); + entity.setName("Mapstruct Mapping"); + Person author = new Person(); + author.setId("1"); + author.setName("John"); + entity.setAuthor(author); + + ArticleDTO articleDTO = ArticleUsingPersonMapper.INSTANCE.articleToArticleDto(entity); + + assertEquals(articleDTO.getId(), entity.getId()); + assertEquals(articleDTO.getName(), entity.getName()); + assertEquals(articleDTO.getAuthor().getName(), entity.getAuthor().getName()); + } +} diff --git a/dependency-exclusion/README.md b/maven-modules/dependency-exclusion/README.md similarity index 100% rename from dependency-exclusion/README.md rename to maven-modules/dependency-exclusion/README.md diff --git a/maven-modules/dependency-exclusion/core-java-exclusions/pom.xml b/maven-modules/dependency-exclusion/core-java-exclusions/pom.xml new file mode 100644 index 000000000000..9fd09f83e245 --- /dev/null +++ b/maven-modules/dependency-exclusion/core-java-exclusions/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + core-java-exclusions + core-java-exclusions + jar + + + com.baeldung.dependency-exclusion + dependency-exclusion + 0.0.1-SNAPSHOT + + + + + junit + junit + test + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire-version} + + alphabetical + 1 + + + junit + false + + + + + + + + + + diff --git a/dependency-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java b/maven-modules/dependency-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java similarity index 100% rename from dependency-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java rename to maven-modules/dependency-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java diff --git a/maven-modules/dependency-exclusion/dummy-surefire-junit47/pom.xml b/maven-modules/dependency-exclusion/dummy-surefire-junit47/pom.xml new file mode 100644 index 000000000000..93c5f7591f6d --- /dev/null +++ b/maven-modules/dependency-exclusion/dummy-surefire-junit47/pom.xml @@ -0,0 +1,15 @@ + + + 4.0.0 + org.apache.maven.surefire + surefire-junit47 + dummy + + + com.baeldung.dependency-exclusion + dependency-exclusion + 0.0.1-SNAPSHOT + + diff --git a/dependency-exclusion/pom.xml b/maven-modules/dependency-exclusion/pom.xml similarity index 89% rename from dependency-exclusion/pom.xml rename to maven-modules/dependency-exclusion/pom.xml index ac83cc161a19..6e348377b06e 100644 --- a/dependency-exclusion/pom.xml +++ b/maven-modules/dependency-exclusion/pom.xml @@ -1,7 +1,7 @@ + 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.dependency-exclusion dependency-exclusion @@ -10,9 +10,8 @@ com.baeldung - parent-java + maven-modules 0.0.1-SNAPSHOT - ../parent-java diff --git a/maven-modules/maven-copy-files/maven-antrun-plugin/pom.xml b/maven-modules/maven-copy-files/maven-antrun-plugin/pom.xml index 430d0a1f5b16..93e6dd923157 100644 --- a/maven-modules/maven-copy-files/maven-antrun-plugin/pom.xml +++ b/maven-modules/maven-copy-files/maven-antrun-plugin/pom.xml @@ -22,10 +22,10 @@ generate-sources - + + includes="foo.txt"/> diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml index 2dfa34568e73..28ea8b635905 100644 --- a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml @@ -21,7 +21,7 @@ enforce-file-exists - + diff --git a/maven-modules/maven-plugins/maven-enforcer/pom.xml b/maven-modules/maven-plugins/maven-enforcer/pom.xml index 25c608ee3688..5d7d84579493 100644 --- a/maven-modules/maven-plugins/maven-enforcer/pom.xml +++ b/maven-modules/maven-plugins/maven-enforcer/pom.xml @@ -33,7 +33,7 @@ - + 3.0 Invalid Maven version. It should, at least, be 3.0 diff --git a/maven-modules/maven-pom-types/pom-4.0.0.xml b/maven-modules/maven-pom-types/pom-4.0.0.xml index 24b15984af9e..515ec00cccda 100644 --- a/maven-modules/maven-pom-types/pom-4.0.0.xml +++ b/maven-modules/maven-pom-types/pom-4.0.0.xml @@ -145,4 +145,4 @@ - + diff --git a/maven-modules/maven-printing-plugins/pom.xml b/maven-modules/maven-printing-plugins/pom.xml index 07ddd8d1e81f..683a99fef7c0 100644 --- a/maven-modules/maven-printing-plugins/pom.xml +++ b/maven-modules/maven-printing-plugins/pom.xml @@ -27,12 +27,12 @@ - - + + + level="info"/> + message="Save to file!"/> diff --git a/maven-modules/maven-reactor/patient-data/pom.xml b/maven-modules/maven-reactor/patient-data/pom.xml index 9526549c4867..51f6ff6b72dd 100644 --- a/maven-modules/maven-reactor/patient-data/pom.xml +++ b/maven-modules/maven-reactor/patient-data/pom.xml @@ -1,20 +1,20 @@ - 4.0.0 - patient-data - patient-data - - com.baeldung - maven-reactor - 1.0-SNAPSHOT - - - - com.baeldung - patient-domain - 1.0-SNAPSHOT - - + 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 + patient-data + patient-data + + com.baeldung + maven-reactor + 1.0-SNAPSHOT + + + + com.baeldung + patient-domain + 1.0-SNAPSHOT + + \ No newline at end of file diff --git a/maven-modules/maven-reactor/patient-domain/pom.xml b/maven-modules/maven-reactor/patient-domain/pom.xml index 5cb5abe81efb..62e7b8ca503b 100644 --- a/maven-modules/maven-reactor/patient-domain/pom.xml +++ b/maven-modules/maven-reactor/patient-domain/pom.xml @@ -1,13 +1,13 @@ - 4.0.0 - patient-domain - patient-domain - - com.baeldung - maven-reactor - 1.0-SNAPSHOT - + 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 + patient-domain + patient-domain + + com.baeldung + maven-reactor + 1.0-SNAPSHOT + \ No newline at end of file diff --git a/maven-modules/maven-reactor/patient-web/pom.xml b/maven-modules/maven-reactor/patient-web/pom.xml index 68d797ec633f..9d2ddd819d0c 100644 --- a/maven-modules/maven-reactor/patient-web/pom.xml +++ b/maven-modules/maven-reactor/patient-web/pom.xml @@ -1,27 +1,27 @@ - 4.0.0 - patient-web - 1.0-SNAPSHOT - patient-web - - com.baeldung - maven-reactor + 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 + patient-web 1.0-SNAPSHOT - - - - com.baeldung - patient-data - 1.0-SNAPSHOT - - - com.baeldung - patient-domain - 1.0-SNAPSHOT - - + patient-web + + com.baeldung + maven-reactor + 1.0-SNAPSHOT + + + + com.baeldung + patient-data + 1.0-SNAPSHOT + + + com.baeldung + patient-domain + 1.0-SNAPSHOT + + \ No newline at end of file diff --git a/maven-modules/maven-reactor/pom.xml b/maven-modules/maven-reactor/pom.xml index a41fbd7374f5..ac21b6170cdf 100644 --- a/maven-modules/maven-reactor/pom.xml +++ b/maven-modules/maven-reactor/pom.xml @@ -1,22 +1,22 @@ - 4.0.0 - maven-reactor - 1.0-SNAPSHOT - maven-reactor - pom - Sample multi-module project to explain maven reactor - - com.baeldung - maven-modules - 0.0.1-SNAPSHOT - - - patient-web - patient-data - patient-domain - + 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 + maven-reactor + 1.0-SNAPSHOT + maven-reactor + pom + Sample multi-module project to explain maven reactor + + com.baeldung + maven-modules + 0.0.1-SNAPSHOT + + + patient-web + patient-data + patient-domain + \ No newline at end of file diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml index a7a3522ca805..f7bba3a8fff9 100644 --- a/maven-modules/pom.xml +++ b/maven-modules/pom.xml @@ -16,33 +16,35 @@ animal-sniffer-mvn-plugin - maven-archetype compiler-plugin-java-9 + dependency-exclusion + host-maven-repo-example + maven-archetype + maven-builder-plugin + maven-classifier maven-copy-files maven-custom-plugin maven-exec-plugin maven-generate-war maven-integration-test maven-multi-source + maven-parent-pom-resolution maven-plugins maven-polyglot + maven-printing-plugins maven-properties + maven-reactor + maven-repositories + maven-simple + maven-surefire-plugin maven-unused-dependencies maven-war-plugin + spring-bom optional-dependencies version-collision version-overriding-plugins versions-maven-plugin - maven-printing-plugins - maven-builder-plugin - host-maven-repo-example - maven-surefire-plugin - maven-parent-pom-resolution - maven-simple - maven-classifier - maven-repositories - maven-reactor @@ -62,4 +64,18 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.lang=ALL-UNNAMED + + + + + + \ No newline at end of file diff --git a/spring-bom/README.md b/maven-modules/spring-bom/README.md similarity index 100% rename from spring-bom/README.md rename to maven-modules/spring-bom/README.md diff --git a/spring-bom/pom.xml b/maven-modules/spring-bom/pom.xml similarity index 93% rename from spring-bom/pom.xml rename to maven-modules/spring-bom/pom.xml index 7ba21ee28522..93d0bdc45821 100644 --- a/spring-bom/pom.xml +++ b/maven-modules/spring-bom/pom.xml @@ -10,8 +10,8 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + maven-modules + 0.0.1-SNAPSHOT diff --git a/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldApp.java b/maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldApp.java similarity index 100% rename from spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldApp.java rename to maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldApp.java diff --git a/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldBean.java b/maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldBean.java similarity index 100% rename from spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldBean.java rename to maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldBean.java diff --git a/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldConfig.java b/maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldConfig.java similarity index 100% rename from spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldConfig.java rename to maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldConfig.java diff --git a/spring-bom/src/main/resources/logback.xml b/maven-modules/spring-bom/src/main/resources/logback.xml similarity index 100% rename from spring-bom/src/main/resources/logback.xml rename to maven-modules/spring-bom/src/main/resources/logback.xml diff --git a/spring-bom/src/test/java/com/baeldung/SpringContextTest.java b/maven-modules/spring-bom/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-bom/src/test/java/com/baeldung/SpringContextTest.java rename to maven-modules/spring-bom/src/test/java/com/baeldung/SpringContextTest.java diff --git a/maven-modules/version-collision/dependencyconvergence.xml b/maven-modules/version-collision/dependencyconvergence.xml new file mode 100644 index 000000000000..8f57cbf1d5a2 --- /dev/null +++ b/maven-modules/version-collision/dependencyconvergence.xml @@ -0,0 +1,22 @@ + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.3.0 + + + enforce + + + + + + + enforce + + + + + + \ No newline at end of file diff --git a/maven-modules/version-collision/dependencyconvergence_exclude_scenario.xml b/maven-modules/version-collision/dependencyconvergence_exclude_scenario.xml new file mode 100644 index 000000000000..32b0462a1102 --- /dev/null +++ b/maven-modules/version-collision/dependencyconvergence_exclude_scenario.xml @@ -0,0 +1,26 @@ + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.3.0 + + + enforce + + + + + com.google.guava:guava + + + + + + enforce + + + + + + \ No newline at end of file diff --git a/maven-modules/version-collision/dependencyconvergence_include_scenario.xml b/maven-modules/version-collision/dependencyconvergence_include_scenario.xml new file mode 100644 index 000000000000..9e4680fc912b --- /dev/null +++ b/maven-modules/version-collision/dependencyconvergence_include_scenario.xml @@ -0,0 +1,26 @@ + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.3.0 + + + enforce + + + + + com.google.guava:guava + + + + + + enforce + + + + + + \ No newline at end of file diff --git a/apache-rocketmq/README.md b/messaging-modules/apache-rocketmq/README.md similarity index 100% rename from apache-rocketmq/README.md rename to messaging-modules/apache-rocketmq/README.md diff --git a/apache-rocketmq/pom.xml b/messaging-modules/apache-rocketmq/pom.xml similarity index 90% rename from apache-rocketmq/pom.xml rename to messaging-modules/apache-rocketmq/pom.xml index 48399b6d51c3..a362644de325 100644 --- a/apache-rocketmq/pom.xml +++ b/messaging-modules/apache-rocketmq/pom.xml @@ -9,8 +9,8 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + messaging-modules + 0.0.1-SNAPSHOT diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java b/messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java similarity index 100% rename from apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java rename to messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java b/messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java similarity index 100% rename from apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java rename to messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java b/messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java similarity index 100% rename from apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java rename to messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java b/messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java similarity index 100% rename from apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java rename to messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java diff --git a/apache-rocketmq/src/main/resources/application.properties b/messaging-modules/apache-rocketmq/src/main/resources/application.properties similarity index 100% rename from apache-rocketmq/src/main/resources/application.properties rename to messaging-modules/apache-rocketmq/src/main/resources/application.properties diff --git a/messaging-modules/pom.xml b/messaging-modules/pom.xml index 47e073014817..71ff25d71b4a 100644 --- a/messaging-modules/pom.xml +++ b/messaging-modules/pom.xml @@ -16,6 +16,7 @@ apache-camel + apache-rocketmq jgroups rabbitmq spring-amqp diff --git a/messaging-modules/rabbitmq/README.md b/messaging-modules/rabbitmq/README.md index 93bb795d7b44..8cfcca3378c8 100644 --- a/messaging-modules/rabbitmq/README.md +++ b/messaging-modules/rabbitmq/README.md @@ -9,3 +9,4 @@ This module contains articles about RabbitMQ. - [Channels and Connections in RabbitMQ](https://www.baeldung.com/java-rabbitmq-channels-connections) - [Create Dynamic Queues in RabbitMQ](https://www.baeldung.com/rabbitmq-dynamic-queues) + diff --git a/messaging-modules/spring-apache-camel/pom.xml b/messaging-modules/spring-apache-camel/pom.xml index 65533d76493b..c64d84efdcad 100644 --- a/messaging-modules/spring-apache-camel/pom.xml +++ b/messaging-modules/spring-apache-camel/pom.xml @@ -85,7 +85,7 @@ 3.15.0 - + spring-boot diff --git a/messaging-modules/spring-jms/pom.xml b/messaging-modules/spring-jms/pom.xml index 2dee95136dd3..ef1e0cb3a877 100644 --- a/messaging-modules/spring-jms/pom.xml +++ b/messaging-modules/spring-jms/pom.xml @@ -44,19 +44,19 @@ org.mockito mockito-core - 4.6.1 + ${mockito-core.version} test org.apache.activemq.tooling activemq-junit - 5.16.5 + ${activemq-junit.version} test org.testcontainers testcontainers - 1.17.3 + ${testcontainers.version} test @@ -83,6 +83,9 @@ 5.14.1 1.5.10.RELEASE 3.3.2 + 4.6.1 + 5.16.5 + 1.17.3 \ No newline at end of file diff --git a/microservices-modules/micronaut/pom.xml b/microservices-modules/micronaut/pom.xml index 2cc91bc51055..716b5497d82e 100644 --- a/microservices-modules/micronaut/pom.xml +++ b/microservices-modules/micronaut/pom.xml @@ -90,7 +90,7 @@ ${exec.mainClass} + implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/> @@ -103,7 +103,7 @@ java -classpath - + ${exec.mainClass} diff --git a/microservices-modules/rest-express/pom.xml b/microservices-modules/rest-express/pom.xml index e3fed19e2906..e92607aec7ce 100644 --- a/microservices-modules/rest-express/pom.xml +++ b/microservices-modules/rest-express/pom.xml @@ -1,6 +1,7 @@ - + microservices-modules com.baeldung @@ -23,15 +24,6 @@ rest-express jar - - 0.3.3 - 3.1.2 - 2.6 - 0.11.3 - 1.0 - 0.4.8 - 4.11 - @@ -98,7 +90,7 @@ org.codehaus.mojo exec-maven-plugin - 1.2.1 + ${exec-maven-plugin.version} com.baeldung.restexpress.Main @@ -106,7 +98,7 @@ org.apache.maven.plugins maven-shade-plugin - 2.4.1 + ${maven-shade-plugin.version} false @@ -124,7 +116,7 @@ + implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> com.baeldung.restexpress.Main @@ -140,8 +132,22 @@ org.codehaus.mojo versions-maven-plugin - 2.0 + ${versions-maven-plugin.version} + + + 0.3.3 + 3.1.2 + 2.6 + 0.11.3 + 1.0 + 0.4.8 + 4.11 + 1.2.1 + 2.4.1 + 2.0 + + diff --git a/osgi/pom.xml b/osgi/pom.xml index 3fa2dcdf027f..ecc8758ef90d 100644 --- a/osgi/pom.xml +++ b/osgi/pom.xml @@ -67,6 +67,17 @@ + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + @@ -84,6 +95,8 @@ 1.1 6.0.0 3.3.0 + 11 + 11 \ No newline at end of file diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index a1f16c4a64d4..3f6ad8ef8af2 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -94,7 +94,7 @@ 3.3.0 1.0.22.RELEASE - 2.7.8 + 2.7.11 1.9.1 8.0.31 diff --git a/parent-boot-3/pom.xml b/parent-boot-3/pom.xml index 44f7d973106d..dcb5e179bb7b 100644 --- a/parent-boot-3/pom.xml +++ b/parent-boot-3/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 parent-boot-3 0.0.1-SNAPSHOT diff --git a/parent-spring-6/README.md b/parent-spring-6/README.md new file mode 100644 index 000000000000..d43bba4513a9 --- /dev/null +++ b/parent-spring-6/README.md @@ -0,0 +1,3 @@ +## Parent Spring 6 + +This is a parent module for all projects using Spring 6 diff --git a/parent-spring-6/pom.xml b/parent-spring-6/pom.xml new file mode 100644 index 000000000000..d91a12bcc59f --- /dev/null +++ b/parent-spring-6/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + parent-spring-6 + 0.0.1-SNAPSHOT + parent-spring-6 + pom + Parent for all spring 6 core modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + org.springframework + spring-framework-bom + ${spring.version} + pom + import + + + + + + + org.springframework + spring-core + + + + + 6.0.8 + + + diff --git a/patterns-modules/clean-architecture/src/test/java/com/baeldung/pattern/cleanarchitecture/usercreation/UserUnitTest.java b/patterns-modules/clean-architecture/src/test/java/com/baeldung/pattern/cleanarchitecture/usercreation/UserUnitTest.java index 505ea47e3f8a..e2a9cd9d14a4 100644 --- a/patterns-modules/clean-architecture/src/test/java/com/baeldung/pattern/cleanarchitecture/usercreation/UserUnitTest.java +++ b/patterns-modules/clean-architecture/src/test/java/com/baeldung/pattern/cleanarchitecture/usercreation/UserUnitTest.java @@ -1,15 +1,36 @@ package com.baeldung.pattern.cleanarchitecture.usercreation; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.any; import org.junit.jupiter.api.Test; class UserUnitTest { + UserRegisterDsGateway userDsGateway = mock(UserRegisterDsGateway.class); + UserPresenter userPresenter = mock(UserPresenter.class); + UserFactory userFactory = mock(UserFactory.class); + UserInputBoundary interactor = new UserRegisterInteractor(userDsGateway, userPresenter, userFactory); + @Test void given123Password_whenPasswordIsNotValid_thenIsFalse() { User user = new CommonUser("Baeldung", "123"); assertThat(user.passwordIsValid()).isFalse(); } + + @Test + void givenBaeldungUserAnd123456Password_whenCreate_thenSaveItAndPrepareSuccessView() { + + User user = new CommonUser("baeldung", "123456"); + UserRequestModel userRequestModel = new UserRequestModel(user.getName(), user.getPassword()); + when(userFactory.create(anyString(), anyString())).thenReturn(new CommonUser(user.getName(), user.getPassword())); + + interactor.create(userRequestModel); + + verify(userDsGateway, times(1)).save(any(UserDsRequestModel.class)); + verify(userPresenter, times(1)).prepareSuccessView(any(UserResponseModel.class)); + } } diff --git a/patterns-modules/cqrs-es/pom.xml b/patterns-modules/cqrs-es/pom.xml index ee5820ff96bc..9d53d27b4383 100644 --- a/patterns-modules/cqrs-es/pom.xml +++ b/patterns-modules/cqrs-es/pom.xml @@ -18,7 +18,6 @@ lombok ${lombok.version} - \ No newline at end of file diff --git a/patterns-modules/cqrs-es/src/main/java/com/baeldung/patterns/es/service/UserUtility.java b/patterns-modules/cqrs-es/src/main/java/com/baeldung/patterns/es/service/UserUtility.java index e44e40458801..08334575077c 100644 --- a/patterns-modules/cqrs-es/src/main/java/com/baeldung/patterns/es/service/UserUtility.java +++ b/patterns-modules/cqrs-es/src/main/java/com/baeldung/patterns/es/service/UserUtility.java @@ -23,8 +23,7 @@ public static User recreateUserState(EventStore store, String userId) { for (Event event : events) { if (event instanceof UserCreatedEvent) { UserCreatedEvent e = (UserCreatedEvent) event; - user = new User(UUID.randomUUID() - .toString(), e.getFirstName(), e.getLastName()); + user = new User(e.getUserId(), e.getFirstName(), e.getLastName()); } if (event instanceof UserAddressAddedEvent) { UserAddressAddedEvent e = (UserAddressAddedEvent) event; diff --git a/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java b/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java index 2ee6f93f9b94..e06f1291a66e 100644 --- a/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java +++ b/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java @@ -1,5 +1,8 @@ package com.baeldung.templatemethod.model; +import lombok.extern.slf4j.Slf4j; + +@Slf4j public class HighEndComputerBuilder extends ComputerBuilder { @Override @@ -11,7 +14,7 @@ public void addMotherboard() { public void setupMotherboard() { motherboardSetupStatus.add("Screwing the high-end motherboard to the case."); motherboardSetupStatus.add("Pluging in the power supply connectors."); - motherboardSetupStatus.forEach(step -> System.out.println(step)); + motherboardSetupStatus.forEach(step -> log.debug(step)); } @Override diff --git a/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java b/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java index da2c2e9b2d30..f5b953c83062 100644 --- a/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java +++ b/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java @@ -1,5 +1,8 @@ package com.baeldung.templatemethod.model; - + +import lombok.extern.slf4j.Slf4j; + +@Slf4j public class StandardComputerBuilder extends ComputerBuilder { @Override @@ -11,7 +14,7 @@ public void addMotherboard() { public void setupMotherboard() { motherboardSetupStatus.add("Screwing the standard motherboard to the case."); motherboardSetupStatus.add("Pluging in the power supply connectors."); - motherboardSetupStatus.forEach(step -> System.out.println(step)); + motherboardSetupStatus.forEach(step -> log.debug(step)); } @Override diff --git a/patterns-modules/design-patterns-behavioral/src/test/resources/logback-test.xml b/patterns-modules/design-patterns-behavioral/src/test/resources/logback-test.xml new file mode 100644 index 000000000000..499cc828a2e3 --- /dev/null +++ b/patterns-modules/design-patterns-behavioral/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + %d{yyyy-MM-dd HH:mm:ss} | %-5p | [%thread] %logger{5}:%L - %msg%n + + + + + + + \ No newline at end of file diff --git a/patterns-modules/idd/pom.xml b/patterns-modules/idd/pom.xml index e08e058b92f9..5e20a30317aa 100644 --- a/patterns-modules/idd/pom.xml +++ b/patterns-modules/idd/pom.xml @@ -6,9 +6,6 @@ idd 1.0 idd - - - jar diff --git a/pdf-2/pom.xml b/pdf-2/pom.xml index 653b55a206d6..ccbb5c969311 100644 --- a/pdf-2/pom.xml +++ b/pdf-2/pom.xml @@ -28,12 +28,12 @@ com.itextpdf itextpdf - 5.5.13.3 + ${itextpdf.version} org.apache.pdfbox pdfbox - 3.0.0-RC1 + ${pdfbox.version} @@ -48,8 +48,10 @@ + 5.5.13.3 7.2.3 3.0.1 + 3.0.0-RC1 \ No newline at end of file diff --git a/pdf/pom.xml b/pdf/pom.xml index 4bfc7cb6218c..cead1b2dedd2 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -106,7 +106,7 @@ 2.0.25 2.0.1 - 5.5.10 + 5.5.13.3 5.5.10 3.15 1.8 diff --git a/persistence-modules/activejdbc/pom.xml b/persistence-modules/activejdbc/pom.xml index 5fdf27a67900..a661fc3abb52 100644 --- a/persistence-modules/activejdbc/pom.xml +++ b/persistence-modules/activejdbc/pom.xml @@ -74,9 +74,9 @@ - 2.0 + 3.4-j11 development.test,development - 5.1.34 + 8.0.32 \ No newline at end of file diff --git a/persistence-modules/activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java b/persistence-modules/activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java index 8906d3e759f3..ea600b972171 100644 --- a/persistence-modules/activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java +++ b/persistence-modules/activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java @@ -4,6 +4,7 @@ import com.baeldung.model.Employee; import com.baeldung.model.Role; import org.javalite.activejdbc.Base; +import org.javalite.activejdbc.DB; import org.javalite.activejdbc.LazyList; import org.javalite.activejdbc.Model; @@ -11,8 +12,7 @@ public class ActiveJDBCApp { public static void main( String[] args ) { - try { - Base.open(); + try(final DB open = Base.open()) { ActiveJDBCApp app = new ActiveJDBCApp(); app.create(); app.update(); diff --git a/persistence-modules/blaze-persistence/pom.xml b/persistence-modules/blaze-persistence/pom.xml index dfe4a69eab03..1162de67fce3 100644 --- a/persistence-modules/blaze-persistence/pom.xml +++ b/persistence-modules/blaze-persistence/pom.xml @@ -11,7 +11,7 @@ org.springframework.boot spring-boot-starter-parent 2.4.0 - + diff --git a/persistence-modules/core-java-persistence/pom.xml b/persistence-modules/core-java-persistence/pom.xml index 5cc1df483fd5..e8add07fbf15 100644 --- a/persistence-modules/core-java-persistence/pom.xml +++ b/persistence-modules/core-java-persistence/pom.xml @@ -52,14 +52,21 @@ spring-boot-starter ${springframework.boot.spring-boot-starter.version} + + mysql + mysql-connector-java + ${mysql-connector.version} + runtime + - 2.4.0 - 3.2.0 - 0.9.5.2 - 1.5.8.RELEASE - 4.3.4.RELEASE + 2.9.0 + 5.0.1 + 0.9.5.5 + 3.0.4 + 6.0.6 + 8.0.32 \ No newline at end of file diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/DatabaseConfig.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/DatabaseConfig.java index 8ad689041ec2..44cfc75a2b23 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/DatabaseConfig.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/DatabaseConfig.java @@ -1,13 +1,14 @@ package com.baeldung.jdbcmetadata; -import org.apache.log4j.Logger; - import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class DatabaseConfig { - private static final Logger LOG = Logger.getLogger(DatabaseConfig.class); + private static final Logger LOG = LoggerFactory.getLogger(DatabaseConfig.class); private Connection connection; @@ -17,7 +18,7 @@ public DatabaseConfig() { String url = "jdbc:h2:mem:testdb"; connection = DriverManager.getConnection(url, "sa", ""); } catch (ClassNotFoundException | SQLException e) { - LOG.error(e); + LOG.error(e.getMessage()); } } @@ -35,7 +36,7 @@ private void createTables() { connection.createStatement().executeUpdate("create table CUSTOMER (ID int primary key auto_increment, NAME VARCHAR(45))"); connection.createStatement().executeUpdate("create table CUST_ADDRESS (ID VARCHAR(36), CUST_ID int, ADDRESS VARCHAR(45), FOREIGN KEY (CUST_ID) REFERENCES CUSTOMER(ID))"); } catch (SQLException e) { - LOG.error(e); + LOG.error(e.getMessage()); } } @@ -43,7 +44,7 @@ private void createViews() { try { connection.createStatement().executeUpdate("CREATE VIEW CUSTOMER_VIEW AS SELECT * FROM CUSTOMER"); } catch (SQLException e) { - LOG.error(e); + LOG.error(e.getMessage()); } } } diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/JdbcMetadataApplication.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/JdbcMetadataApplication.java index 591a14f3b5df..f85f2273814c 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/JdbcMetadataApplication.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/JdbcMetadataApplication.java @@ -1,12 +1,13 @@ package com.baeldung.jdbcmetadata; -import org.apache.log4j.Logger; - import java.sql.SQLException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class JdbcMetadataApplication { - private static final Logger LOG = Logger.getLogger(JdbcMetadataApplication.class); + private static final Logger LOG = LoggerFactory.getLogger(JdbcMetadataApplication.class); public static void main(String[] args) { DatabaseConfig databaseConfig = new DatabaseConfig(); diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java index 9cfcff468e96..a53c82d3da24 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java @@ -5,10 +5,6 @@ import java.sql.SQLException; import java.sql.Statement; -import javax.sql.rowset.JdbcRowSet; -import javax.sql.rowset.RowSetFactory; -import javax.sql.rowset.RowSetProvider; - import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Configuration; diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java index 72c462ac428c..163b3a3b589d 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java @@ -7,8 +7,6 @@ import java.sql.SQLException; import java.sql.Statement; -import com.sun.rowset.*; - import javax.sql.rowset.CachedRowSet; import javax.sql.rowset.FilteredRowSet; import javax.sql.rowset.JdbcRowSet; @@ -25,7 +23,7 @@ public class JdbcRowsetApplication { public static void main(String[] args) throws Exception { SpringApplication.run(JdbcRowsetApplication.class, args); - Statement stmt = null; + Statement stmt; try { Connection conn = DatabaseConfiguration.geth2Connection(); @@ -41,8 +39,7 @@ public static void main(String[] args) throws Exception { DatabaseConfiguration.initDatabase(stmt); // JdbcRowSet Example String sql = "SELECT * FROM customers"; - JdbcRowSet jdbcRS; - jdbcRS = new JdbcRowSetImpl(conn); + JdbcRowSet jdbcRS = RowSetProvider.newFactory().createJdbcRowSet(); jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE); jdbcRS.setCommand(sql); jdbcRS.execute(); @@ -58,7 +55,8 @@ public static void main(String[] args) throws Exception { String username = "sa"; String password = ""; String url = "jdbc:h2:mem:testdb"; - CachedRowSet crs = new CachedRowSetImpl(); + RowSetFactory aFactory = RowSetProvider.newFactory(); + CachedRowSet crs = aFactory.createCachedRowSet(); crs.setUsername(username); crs.setPassword(password); crs.setUrl(url); @@ -74,7 +72,7 @@ public static void main(String[] args) throws Exception { } // WebRowSet example - WebRowSet wrs = new WebRowSetImpl(); + WebRowSet wrs = RowSetProvider.newFactory().createWebRowSet(); wrs.setUsername(username); wrs.setPassword(password); wrs.setUrl(url); @@ -84,14 +82,14 @@ public static void main(String[] args) throws Exception { wrs.writeXml(ostream); // JoinRowSet example - CachedRowSetImpl customers = new CachedRowSetImpl(); + CachedRowSet customers = aFactory.createCachedRowSet(); customers.setUsername(username); customers.setPassword(password); customers.setUrl(url); customers.setCommand(sql); customers.execute(); - CachedRowSetImpl associates = new CachedRowSetImpl(); + CachedRowSet associates = aFactory.createCachedRowSet(); associates.setUsername(username); associates.setPassword(password); associates.setUrl(url); @@ -99,7 +97,7 @@ public static void main(String[] args) throws Exception { associates.setCommand(associatesSQL); associates.execute(); - JoinRowSet jrs = new JoinRowSetImpl(); + JoinRowSet jrs = RowSetProvider.newFactory().createJoinRowSet(); final String ID = "id"; final String NAME = "name"; jrs.addRowSet(customers, ID); diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java index ebfb4df102e5..2b2b35c42394 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java @@ -19,11 +19,6 @@ import org.junit.Before; import org.junit.Test; -import com.sun.rowset.CachedRowSetImpl; -import com.sun.rowset.JdbcRowSetImpl; -import com.sun.rowset.JoinRowSetImpl; -import com.sun.rowset.WebRowSetImpl; - public class JdbcRowSetLiveTest { Statement stmt = null; String username = "sa"; @@ -51,9 +46,10 @@ public void setup() throws Exception { public void createJdbcRowSet_SelectCustomers_ThenCorrect() throws Exception { String sql = "SELECT * FROM customers"; - JdbcRowSet jdbcRS; - Connection conn = DatabaseConfiguration.geth2Connection(); - jdbcRS = new JdbcRowSetImpl(conn); + JdbcRowSet jdbcRS = RowSetProvider.newFactory().createJdbcRowSet(); + jdbcRS.setUrl("jdbc:h2:mem:testdb"); + jdbcRS.setUsername("sa"); + jdbcRS.setPassword(""); jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE); jdbcRS.setCommand(sql); jdbcRS.execute(); @@ -71,7 +67,7 @@ public void createJdbcRowSet_SelectCustomers_ThenCorrect() throws Exception { @Test public void createCachedRowSet_DeleteRecord_ThenCorrect() throws Exception { - CachedRowSet crs = new CachedRowSetImpl(); + CachedRowSet crs = RowSetProvider.newFactory().createCachedRowSet(); crs.setUsername(username); crs.setPassword(password); crs.setUrl(url); @@ -91,7 +87,7 @@ public void createCachedRowSet_DeleteRecord_ThenCorrect() throws Exception { @Test public void createWebRowSet_SelectCustomers_WritetoXML_ThenCorrect() throws SQLException, IOException { - WebRowSet wrs = new WebRowSetImpl(); + WebRowSet wrs = RowSetProvider.newFactory().createWebRowSet(); wrs.setUsername(username); wrs.setPassword(password); wrs.setUrl(url); @@ -105,14 +101,14 @@ public void createWebRowSet_SelectCustomers_WritetoXML_ThenCorrect() throws SQLE @Test public void createCachedRowSets_DoJoinRowSet_ThenCorrect() throws Exception { - CachedRowSetImpl customers = new CachedRowSetImpl(); + CachedRowSet customers = RowSetProvider.newFactory().createCachedRowSet(); customers.setUsername(username); customers.setPassword(password); customers.setUrl(url); customers.setCommand(sql); customers.execute(); - CachedRowSetImpl associates = new CachedRowSetImpl(); + CachedRowSet associates = RowSetProvider.newFactory().createCachedRowSet(); associates.setUsername(username); associates.setPassword(password); associates.setUrl(url); @@ -120,7 +116,7 @@ public void createCachedRowSets_DoJoinRowSet_ThenCorrect() throws Exception { associates.setCommand(associatesSQL); associates.execute(); - JoinRowSet jrs = new JoinRowSetImpl(); + JoinRowSet jrs = RowSetProvider.newFactory().createJoinRowSet(); final String ID = "id"; final String NAME = "name"; jrs.addRowSet(customers, ID); diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java index c13f94f12afd..fe00ca28dcb5 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java @@ -1,9 +1,10 @@ package com.baeldung.spring.jdbc; -import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.sql.CallableStatement; import java.sql.Connection; @@ -24,7 +25,7 @@ public class JdbcLiveTest { - private static final Logger LOG = Logger.getLogger(JdbcLiveTest.class); + private static final Logger LOG = LoggerFactory.getLogger(JdbcLiveTest.class); private Connection con; diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java index 853e78a68d29..c77e314141b4 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java @@ -13,7 +13,6 @@ import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.FixMethodOrder; @@ -25,8 +24,6 @@ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ResultSetLiveTest { - private static final Logger logger = Logger.getLogger(ResultSetLiveTest.class); - private final Employee expectedEmployee1 = new Employee(1, "John", 1000.0, "Developer"); private final Employee updatedEmployee1 = new Employee(1, "John", 1100.0, "Developer"); diff --git a/persistence-modules/hbase/pom.xml b/persistence-modules/hbase/pom.xml index e38b73e137b3..3e6cfe27be5b 100644 --- a/persistence-modules/hbase/pom.xml +++ b/persistence-modules/hbase/pom.xml @@ -33,7 +33,7 @@ - 1.3.1 + 2.5.3 \ No newline at end of file diff --git a/persistence-modules/hbase/src/main/java/com/baeldung/hbase/HbaseClientExample.java b/persistence-modules/hbase/src/main/java/com/baeldung/hbase/HbaseClientExample.java index 5546f15e365e..3a137a60198f 100644 --- a/persistence-modules/hbase/src/main/java/com/baeldung/hbase/HbaseClientExample.java +++ b/persistence-modules/hbase/src/main/java/com/baeldung/hbase/HbaseClientExample.java @@ -1,7 +1,5 @@ package com.baeldung.hbase; - -import com.google.protobuf.ServiceException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; @@ -13,11 +11,11 @@ //install hbase locally & hbase master start public class HbaseClientExample { - public static void main(String[] args) throws IOException, ServiceException { + public static void main(String[] args) throws IOException { new HbaseClientExample().connect(); } - private void connect() throws IOException, ServiceException { + private void connect() throws IOException { Configuration config = HBaseConfiguration.create(); String path = this.getClass().getClassLoader().getResource("hbase-site.xml").getPath(); @@ -25,7 +23,7 @@ private void connect() throws IOException, ServiceException { config.addResource(new Path(path)); try { - HBaseAdmin.checkHBaseAvailable(config); + HBaseAdmin.available(config); } catch (MasterNotRunningException e) { System.out.println("HBase is not running." + e.getMessage()); return; diff --git a/persistence-modules/hibernate-annotations/README.md b/persistence-modules/hibernate-annotations/README.md index 9b6857915108..a03fb7e8e3e3 100644 --- a/persistence-modules/hibernate-annotations/README.md +++ b/persistence-modules/hibernate-annotations/README.md @@ -10,3 +10,4 @@ This module contains articles about Annotations used in Hibernate. - [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable) - [Usage of the Hibernate @LazyCollection Annotation](https://www.baeldung.com/hibernate-lazycollection) - [@Immutable in Hibernate](https://www.baeldung.com/hibernate-immutable) +- [Hibernate @CreationTimestamp and @UpdateTimestamp](https://www.baeldung.com/hibernate-creationtimestamp-updatetimestamp) diff --git a/persistence-modules/hibernate-annotations/pom.xml b/persistence-modules/hibernate-annotations/pom.xml index 310b409a00ff..6417421fed4a 100644 --- a/persistence-modules/hibernate-annotations/pom.xml +++ b/persistence-modules/hibernate-annotations/pom.xml @@ -76,13 +76,18 @@ ${org.springframework.version} test + + io.hypersistence + hypersistence-utils-hibernate-60 + 3.3.1 + - 5.0.2.RELEASE - 1.10.6.RELEASE - 5.6.7.Final + 6.0.6 + 3.0.3 + 6.1.7.Final true 9.0.0.M26 diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/creationupdatetimestamp/model/Book.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/creationupdatetimestamp/model/Book.java new file mode 100644 index 000000000000..0484c31ced0c --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/creationupdatetimestamp/model/Book.java @@ -0,0 +1,57 @@ +package com.baeldung.hibernate.creationupdatetimestamp.model; + +import java.time.Instant; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; + +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +@Entity +public class Book { + @Id + @GeneratedValue + private Long id; + private String title; + @CreationTimestamp + private Instant createdOn; + @UpdateTimestamp + private Instant lastUpdatedOn; + + public Book() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Instant getCreatedOn() { + return createdOn; + } + + public void setCreatedOn(Instant createdOn) { + this.createdOn = createdOn; + } + + public Instant getLastUpdatedOn() { + return lastUpdatedOn; + } + + public void setLastUpdatedOn(Instant lastUpdatedOn) { + this.lastUpdatedOn = lastUpdatedOn; + } +} diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java index c10c67df9aab..f50d8fd7cc3e 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java @@ -1,11 +1,11 @@ package com.baeldung.hibernate.customtypes; import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.type.IntegerType; -import org.hibernate.type.StringType; -import org.hibernate.type.Type; +import org.hibernate.metamodel.spi.ValueAccess; import org.hibernate.usertype.CompositeUserType; +import org.hibernate.usertype.UserType; import java.io.Serializable; import java.sql.PreparedStatement; @@ -14,74 +14,51 @@ import java.sql.Types; import java.util.Objects; -public class AddressType implements CompositeUserType { +public class AddressType implements CompositeUserType
, UserType
{ @Override - public String[] getPropertyNames() { - return new String[]{"addressLine1", "addressLine2", - "city", "country", "zipcode"}; - } - - @Override - public Type[] getPropertyTypes() { - return new Type[]{StringType.INSTANCE, StringType.INSTANCE, - StringType.INSTANCE, StringType.INSTANCE, IntegerType.INSTANCE}; - } - - @Override - public Object getPropertyValue(Object component, int property) throws HibernateException { - - Address empAdd = (Address) component; + public Object getPropertyValue(Address component, int property) throws HibernateException { switch (property) { case 0: - return empAdd.getAddressLine1(); + return component.getAddressLine1(); case 1: - return empAdd.getAddressLine2(); + return component.getAddressLine2(); case 2: - return empAdd.getCity(); + return component.getCity(); case 3: - return empAdd.getCountry(); + return component.getCountry(); case 4: - return Integer.valueOf(empAdd.getZipCode()); + return component.getZipCode(); + default: + throw new IllegalArgumentException(property + + " is an invalid property index for class type " + + component.getClass().getName()); } - - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); } @Override - public void setPropertyValue(Object component, int property, Object value) throws HibernateException { - - Address empAdd = (Address) component; - - switch (property) { - case 0: - empAdd.setAddressLine1((String) value); - case 1: - empAdd.setAddressLine2((String) value); - case 2: - empAdd.setCity((String) value); - case 3: - empAdd.setCountry((String) value); - case 4: - empAdd.setZipCode((Integer) value); - } + public Address instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) { + return null; + } - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); + @Override + public Class embeddable() { + return Address.class; + } + @Override + public int getSqlType() { + return Types.VARCHAR; } @Override - public Class returnedClass() { + public Class
returnedClass() { return Address.class; } @Override - public boolean equals(Object x, Object y) throws HibernateException { + public boolean equals(Address x, Address y) { if (x == y) return true; @@ -92,57 +69,52 @@ public boolean equals(Object x, Object y) throws HibernateException { } @Override - public int hashCode(Object x) throws HibernateException { + public int hashCode(Address x) { return x.hashCode(); } @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - + public Address nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { Address empAdd = new Address(); - empAdd.setAddressLine1(rs.getString(names[0])); + empAdd.setAddressLine1(rs.getString(position)); if (rs.wasNull()) return null; - empAdd.setAddressLine2(rs.getString(names[1])); - empAdd.setCity(rs.getString(names[2])); - empAdd.setCountry(rs.getString(names[3])); - empAdd.setZipCode(rs.getInt(names[4])); + empAdd.setAddressLine2(rs.getString(position)); + empAdd.setCity(rs.getString(position)); + empAdd.setCountry(rs.getString(position)); + empAdd.setZipCode(rs.getInt(position)); return empAdd; } @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { - + public void nullSafeSet(PreparedStatement st, Address value, int index, SharedSessionContractImplementor session) throws SQLException { if (Objects.isNull(value)) st.setNull(index, Types.VARCHAR); else { - Address empAdd = (Address) value; - st.setString(index, empAdd.getAddressLine1()); - st.setString(index + 1, empAdd.getAddressLine2()); - st.setString(index + 2, empAdd.getCity()); - st.setString(index + 3, empAdd.getCountry()); - st.setInt(index + 4, empAdd.getZipCode()); + st.setString(index, value.getAddressLine1()); + st.setString(index + 1, value.getAddressLine2()); + st.setString(index + 2, value.getCity()); + st.setString(index + 3, value.getCountry()); + st.setInt(index + 4, value.getZipCode()); } } @Override - public Object deepCopy(Object value) throws HibernateException { - + public Address deepCopy(Address value) { if (Objects.isNull(value)) return null; - Address oldEmpAdd = (Address) value; Address newEmpAdd = new Address(); - newEmpAdd.setAddressLine1(oldEmpAdd.getAddressLine1()); - newEmpAdd.setAddressLine2(oldEmpAdd.getAddressLine2()); - newEmpAdd.setCity(oldEmpAdd.getCity()); - newEmpAdd.setCountry(oldEmpAdd.getCountry()); - newEmpAdd.setZipCode(oldEmpAdd.getZipCode()); + newEmpAdd.setAddressLine1(value.getAddressLine1()); + newEmpAdd.setAddressLine2(value.getAddressLine2()); + newEmpAdd.setCity(value.getCity()); + newEmpAdd.setCountry(value.getCountry()); + newEmpAdd.setZipCode(value.getZipCode()); return newEmpAdd; } @@ -153,17 +125,27 @@ public boolean isMutable() { } @Override - public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException { + public Serializable disassemble(Address value) { return (Serializable) deepCopy(value); } @Override - public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return deepCopy(cached); + public Address assemble(Serializable cached, Object owner) { + return deepCopy((Address) cached); + } + + @Override + public Address replace(Address detached, Address managed, Object owner) { + return detached; + } + + @Override + public boolean isInstance(Object object, SessionFactoryImplementor sessionFactory) { + return CompositeUserType.super.isInstance(object, sessionFactory); } @Override - public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return original; + public boolean isSameClass(Object object, SessionFactoryImplementor sessionFactory) { + return CompositeUserType.super.isSameClass(object, sessionFactory); } } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java index 56be9e693f54..8f1794b97930 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java @@ -1,14 +1,14 @@ package com.baeldung.hibernate.customtypes; -import org.hibernate.type.LocalDateType; import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; -import org.hibernate.type.descriptor.java.MutabilityPlan; import java.time.LocalDate; +import java.time.format.DateTimeFormatter; -public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor { +import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayTypeDescriptor; + +public class LocalDateStringJavaDescriptor extends AbstractArrayTypeDescriptor { public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor(); @@ -18,12 +18,12 @@ public LocalDateStringJavaDescriptor() { @Override public String toString(LocalDate value) { - return LocalDateType.FORMATTER.format(value); + return DateTimeFormatter.ISO_LOCAL_DATE.format(value); } @Override - public LocalDate fromString(String string) { - return LocalDate.from(LocalDateType.FORMATTER.parse(string)); + public LocalDate fromString(CharSequence string) { + return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse(string)); } @Override @@ -33,7 +33,7 @@ public X unwrap(LocalDate value, Class type, WrapperOptions options) { return null; if (String.class.isAssignableFrom(type)) - return (X) LocalDateType.FORMATTER.format(value); + return (X) DateTimeFormatter.ISO_LOCAL_DATE.format(value); throw unknownUnwrap(type); } @@ -44,7 +44,7 @@ public LocalDate wrap(X value, WrapperOptions options) { return null; if(String.class.isInstance(value)) - return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value)); + return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse((CharSequence) value)); throw unknownWrap(value.getClass()); } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java index c8d37073e896..57a8bcfd08bd 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java @@ -2,18 +2,16 @@ import org.hibernate.dialect.Dialect; import org.hibernate.type.AbstractSingleColumnStandardBasicType; -import org.hibernate.type.DiscriminatorType; -import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor; -import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; +import org.hibernate.type.descriptor.jdbc.VarcharJdbcType; import java.time.LocalDate; -public class LocalDateStringType extends AbstractSingleColumnStandardBasicType implements DiscriminatorType { +public class LocalDateStringType extends AbstractSingleColumnStandardBasicType { public static final LocalDateStringType INSTANCE = new LocalDateStringType(); public LocalDateStringType() { - super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); + super(VarcharJdbcType.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); } @Override @@ -21,14 +19,12 @@ public String getName() { return "LocalDateString"; } - @Override - public LocalDate stringToObject(String xml) throws Exception { + public LocalDate stringToObject(String xml) { return fromString(xml); } - @Override - public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception { - return '\'' + toString(value) + '\''; + public String objectToSQLString(LocalDate value, Dialect dialect) { + return '\'' + LocalDateStringJavaDescriptor.INSTANCE.toString(value) + '\''; } } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java index 1ffeb0b99d9d..1a29182764de 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java @@ -1,20 +1,19 @@ package com.baeldung.hibernate.customtypes; -import org.hibernate.annotations.Columns; +import org.hibernate.annotations.CompositeType; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; +import org.hibernate.usertype.UserTypeLegacyBridge; + +import jakarta.persistence.AttributeOverride; +import jakarta.persistence.AttributeOverrides; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import java.time.LocalDate; -@TypeDef(name = "PhoneNumber", - typeClass = PhoneNumberType.class, - defaultForType = PhoneNumber.class) @Entity @Table(name = "OfficeEmployee") public class OfficeEmployee { @@ -24,25 +23,36 @@ public class OfficeEmployee { private long id; @Column - @Type(type = "LocalDateString") + @Type( + value = UserTypeLegacyBridge.class, + parameters = @Parameter(name = UserTypeLegacyBridge.TYPE_NAME_PARAM_KEY, value = "LocalDateString") + ) private LocalDate dateOfJoining; - @Columns(columns = {@Column(name = "country_code"), - @Column(name = "city_code"), - @Column(name = "number")}) + @AttributeOverrides({ + @AttributeOverride(name = "countryCode", column = @Column(name = "country_code")), + @AttributeOverride(name = "cityCode", column = @Column(name = "city_code")), + @AttributeOverride(name = "number", column = @Column(name = "number")) + }) + @Type(value = PhoneNumberType.class) private PhoneNumber employeeNumber; - @Columns(columns = {@Column(name = "address_line_1"), - @Column(name = "address_line_2"), - @Column(name = "city"), @Column(name = "country"), - @Column(name = "zip_code")}) - @Type(type = "com.baeldung.hibernate.customtypes.AddressType") + @CompositeType(value = com.baeldung.hibernate.customtypes.AddressType.class) + @AttributeOverrides({ + @AttributeOverride(name = "addressLine1", column = @Column(name = "address_line_1")), + @AttributeOverride(name = "addressLine2", column = @Column(name = "address_line_2")), + @AttributeOverride(name = "city", column = @Column(name = "city")), + @AttributeOverride(name = "country", column = @Column(name = "country")), + @AttributeOverride(name = "zipCode", column = @Column(name = "zip_code")) + }) private Address empAddress; - @Type(type = "com.baeldung.hibernate.customtypes.SalaryType", + @Type(value = com.baeldung.hibernate.customtypes.SalaryType.class, parameters = {@Parameter(name = "currency", value = "USD")}) - @Columns(columns = {@Column(name = "amount"), - @Column(name = "currency")}) + @AttributeOverrides({ + @AttributeOverride(name = "amount", column = @Column(name = "amount")), + @AttributeOverride(name = "currency", column = @Column(name = "currency")) + }) private Salary salary; public Salary getSalary() { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java index 0be6cbc91056..a3485ae0dd46 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java @@ -2,11 +2,11 @@ import java.util.Objects; -public final class PhoneNumber { +public class PhoneNumber { - private final int countryCode; - private final int cityCode; - private final int number; + private int countryCode; + private int cityCode; + private int number; public PhoneNumber(int countryCode, int cityCode, int number) { this.countryCode = countryCode; diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java index 79caa3d6fd93..0f8df5f315c9 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java @@ -1,6 +1,5 @@ package com.baeldung.hibernate.customtypes; -import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.usertype.UserType; @@ -11,11 +10,11 @@ import java.sql.Types; import java.util.Objects; +public class PhoneNumberType implements UserType { -public class PhoneNumberType implements UserType { @Override - public int[] sqlTypes() { - return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER}; + public int getSqlType() { + return Types.INTEGER; } @Override @@ -24,7 +23,7 @@ public Class returnedClass() { } @Override - public boolean equals(Object x, Object y) throws HibernateException { + public boolean equals(PhoneNumber x, PhoneNumber y) { if (x == y) return true; if (Objects.isNull(x) || Objects.isNull(y)) @@ -34,48 +33,42 @@ public boolean equals(Object x, Object y) throws HibernateException { } @Override - public int hashCode(Object x) throws HibernateException { + public int hashCode(PhoneNumber x) { return x.hashCode(); } @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - int countryCode = rs.getInt(names[0]); + public PhoneNumber nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { + int countryCode = rs.getInt(position); if (rs.wasNull()) return null; - int cityCode = rs.getInt(names[1]); - int number = rs.getInt(names[2]); - PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number); + int cityCode = rs.getInt(position); + int number = rs.getInt(position); - return employeeNumber; + return new PhoneNumber(countryCode, cityCode, number); } @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { - + public void nullSafeSet(PreparedStatement st, PhoneNumber value, int index, SharedSessionContractImplementor session) throws SQLException { if (Objects.isNull(value)) { st.setNull(index, Types.INTEGER); st.setNull(index+1, Types.INTEGER); st.setNull(index+2, Types.INTEGER); } else { - PhoneNumber employeeNumber = (PhoneNumber) value; - st.setInt(index,employeeNumber.getCountryCode()); - st.setInt(index+1,employeeNumber.getCityCode()); - st.setInt(index+2,employeeNumber.getNumber()); + st.setInt(index, value.getCountryCode()); + st.setInt(index+1, value.getCityCode()); + st.setInt(index+2, value.getNumber()); } } @Override - public Object deepCopy(Object value) throws HibernateException { + public PhoneNumber deepCopy(PhoneNumber value) { if (Objects.isNull(value)) return null; - PhoneNumber empNumber = (PhoneNumber) value; - PhoneNumber newEmpNumber = new PhoneNumber(empNumber.getCountryCode(),empNumber.getCityCode(),empNumber.getNumber()); - - return newEmpNumber; + return new PhoneNumber(value.getCountryCode(), value.getCityCode(), value.getNumber()); } @Override @@ -84,17 +77,17 @@ public boolean isMutable() { } @Override - public Serializable disassemble(Object value) throws HibernateException { + public Serializable disassemble(PhoneNumber value) { return (Serializable) value; } @Override - public Object assemble(Serializable cached, Object owner) throws HibernateException { - return cached; + public PhoneNumber assemble(Serializable cached, Object owner) { + return (PhoneNumber) cached; } @Override - public Object replace(Object original, Object target, Object owner) throws HibernateException { - return original; + public PhoneNumber replace(PhoneNumber detached, PhoneNumber managed, Object owner) { + return detached; } } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java index 266b85140bc2..69e34c136362 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java @@ -1,12 +1,12 @@ package com.baeldung.hibernate.customtypes; import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.type.LongType; -import org.hibernate.type.StringType; -import org.hibernate.type.Type; +import org.hibernate.metamodel.spi.ValueAccess; import org.hibernate.usertype.CompositeUserType; import org.hibernate.usertype.DynamicParameterizedType; +import org.hibernate.usertype.UserType; import java.io.Serializable; import java.sql.PreparedStatement; @@ -16,65 +16,47 @@ import java.util.Objects; import java.util.Properties; -public class SalaryType implements CompositeUserType, DynamicParameterizedType { +public class SalaryType implements UserType, CompositeUserType, DynamicParameterizedType { private String localCurrency; @Override - public String[] getPropertyNames() { - return new String[]{"amount", "currency"}; - } - - @Override - public Type[] getPropertyTypes() { - return new Type[]{LongType.INSTANCE, StringType.INSTANCE}; - } - - @Override - public Object getPropertyValue(Object component, int property) throws HibernateException { - - Salary salary = (Salary) component; + public Object getPropertyValue(Salary component, int property) throws HibernateException { switch (property) { case 0: - return salary.getAmount(); + return component.getAmount(); case 1: - return salary.getCurrency(); + return component.getCurrency(); + default: + throw new IllegalArgumentException(property + + " is an invalid property index for class type " + + component.getClass().getName()); } - - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); - } - @Override - public void setPropertyValue(Object component, int property, Object value) throws HibernateException { - - Salary salary = (Salary) component; - - switch (property) { - case 0: - salary.setAmount((Long) value); - case 1: - salary.setCurrency((String) value); - } + public Salary instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) { + return null; + } - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); + @Override + public Class embeddable() { + return Salary.class; + } + @Override + public int getSqlType() { + return Types.BIGINT; } @Override - public Class returnedClass() { + public Class returnedClass() { return Salary.class; } @Override - public boolean equals(Object x, Object y) throws HibernateException { - + public boolean equals(Salary x, Salary y) { if (x == y) return true; @@ -82,54 +64,48 @@ public boolean equals(Object x, Object y) throws HibernateException { return false; return x.equals(y); - } @Override - public int hashCode(Object x) throws HibernateException { + public int hashCode(Salary x) { return x.hashCode(); } @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - + public Salary nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { Salary salary = new Salary(); - salary.setAmount(rs.getLong(names[0])); + salary.setAmount(rs.getLong(position)); if (rs.wasNull()) return null; - salary.setCurrency(rs.getString(names[1])); + salary.setCurrency(rs.getString(position)); return salary; } @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { - - + public void nullSafeSet(PreparedStatement st, Salary value, int index, SharedSessionContractImplementor session) throws SQLException { if (Objects.isNull(value)) st.setNull(index, Types.BIGINT); else { - Salary salary = (Salary) value; - st.setLong(index, SalaryCurrencyConvertor.convert(salary.getAmount(), - salary.getCurrency(), localCurrency)); - st.setString(index + 1, salary.getCurrency()); + st.setLong(index, SalaryCurrencyConvertor.convert( + value.getAmount(), + value.getCurrency(), localCurrency)); + st.setString(index + 1, value.getCurrency()); } } @Override - public Object deepCopy(Object value) throws HibernateException { - + public Salary deepCopy(Salary value) { if (Objects.isNull(value)) return null; - Salary oldSal = (Salary) value; Salary newSal = new Salary(); - newSal.setAmount(oldSal.getAmount()); - newSal.setCurrency(oldSal.getCurrency()); + newSal.setAmount(value.getAmount()); + newSal.setCurrency(value.getCurrency()); return newSal; } @@ -140,18 +116,18 @@ public boolean isMutable() { } @Override - public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException { + public Serializable disassemble(Salary value) { return (Serializable) deepCopy(value); } @Override - public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return deepCopy(cached); + public Salary assemble(Serializable cached, Object owner) { + return deepCopy((Salary) cached); } @Override - public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return original; + public Salary replace(Salary detached, Salary managed, Object owner) { + return detached; } @Override diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java index ec88d629a603..f16aa68475a3 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java @@ -4,7 +4,7 @@ import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.Immutable; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.Set; @Entity diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java index 33af9313ae9b..6bf4006550fd 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java @@ -3,7 +3,7 @@ import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Immutable; -import javax.persistence.*; +import jakarta.persistence.*; @Entity @Immutable diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java index df07c3cf6950..096faf798472 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java @@ -1,12 +1,12 @@ package com.baeldung.hibernate.joincolumn; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; @Entity public class Email { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java index 9940577761e9..3c6e5f464232 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.joincolumn; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinColumns; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinColumns; +import jakarta.persistence.ManyToOne; @Entity public class Office { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java index cc723db6a280..d80a8be026ca 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java @@ -1,10 +1,10 @@ package com.baeldung.hibernate.joincolumn; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class OfficeAddress { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java index 49c63c7578df..551b52270026 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java @@ -1,12 +1,12 @@ package com.baeldung.hibernate.joincolumn; import java.util.List; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; @Entity public class OfficialEmployee { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Branch.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Branch.java index de88647546e0..9957e2ce7582 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Branch.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Branch.java @@ -3,12 +3,12 @@ import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OrderColumn; -import javax.persistence.OneToMany; -import javax.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OrderColumn; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Entity; import java.util.ArrayList; import java.util.List; diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Employee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Employee.java index 831518a36572..edf89696f5a3 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Employee.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Employee.java @@ -1,11 +1,10 @@ package com.baeldung.hibernate.lazycollection.model; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OrderColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Entity; @Entity public class Employee { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java index ef82c1c9ad20..99410e1f760d 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java @@ -43,8 +43,8 @@ private static SessionFactory buildSessionFactory() { return metadata.buildSessionFactory(); } - private static Map dbSettings() { - Map dbSettings = new HashMap<>(); + private static Map dbSettings() { + Map dbSettings = new HashMap<>(); dbSettings.put(Environment.URL, "jdbc:h2:mem:spring_hibernate_one_to_many"); dbSettings.put(Environment.USER, "sa"); dbSettings.put(Environment.PASS, ""); diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java index 53878af44563..f07f3d388717 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java @@ -2,13 +2,13 @@ import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; @Entity @Table(name = "CART") diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java index 27b28a675352..f279cc4ea68e 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.oneToMany.model; import java.util.Set; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; @Entity @Table(name = "CARTOIO") diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java index a055682d0d13..5babe9c5451d 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.oneToMany.model; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; @Entity @Table(name = "ITEMS") diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java index baaf57b10663..78139da19e7a 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java @@ -1,12 +1,12 @@ package com.baeldung.hibernate.oneToMany.model; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; @Entity @Table(name = "ITEMSOIO") diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java index d923bda5de50..e173aa8b470b 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; import java.io.Serializable; @Entity diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java index 04684eceac5b..2b17c9218db6 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java @@ -3,10 +3,10 @@ import java.util.ArrayList; import java.util.List; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.ManyToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; @Entity(name = "e_group") public class Group { diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java index 3029aae6400f..a517de3cca00 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java @@ -3,12 +3,12 @@ import java.util.ArrayList; import java.util.List; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; import org.hibernate.annotations.WhereJoinTable; diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java index 00dd19699c45..21a0a443c6cb 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java @@ -2,11 +2,11 @@ import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Id; @Entity(name = "r_user_group") public class UserGroupRelation implements Serializable { diff --git a/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml index 474eeb7a4405..291512529528 100644 --- a/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml @@ -7,12 +7,12 @@ Hibernate EntityManager Demo true - + - - - - + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/creationupdatetimestamp/HibernateCreationUpdateTimestampIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/creationupdatetimestamp/HibernateCreationUpdateTimestampIntegrationTest.java new file mode 100644 index 000000000000..a0f3c1ee97b8 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/creationupdatetimestamp/HibernateCreationUpdateTimestampIntegrationTest.java @@ -0,0 +1,124 @@ +package com.baeldung.hibernate.creationupdatetimestamp; + +import static org.hibernate.FlushMode.MANUAL; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.Date; + +import org.h2.Driver; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.dialect.H2Dialect; +import org.hibernate.service.ServiceRegistry; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.baeldung.hibernate.creationupdatetimestamp.model.Book; + +class HibernateCreationUpdateTimestampIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeAll + public static void beforeTests() { + Configuration configuration = new Configuration().addAnnotatedClass(Book.class) + .setProperty("hibernate.dialect", H2Dialect.class.getName()) + .setProperty("hibernate.connection.driver_class", Driver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:h2:mem:test") + .setProperty("hibernate.connection.username", "sa") + .setProperty("hibernate.connection.password", "") + .setProperty("hibernate.hbm2ddl.auto", "update"); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + } + + @Test + void whenCreatingEntity_ThenCreatedOnIsSet() { + session = sessionFactory.openSession(); + session.beginTransaction(); + Book book = new Book(); + + session.save(book); + session.getTransaction() + .commit(); + session.close(); + + assertNotNull(book.getCreatedOn()); + } + + @Test + void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreBothSet() { + session = sessionFactory.openSession(); + session.beginTransaction(); + Book book = new Book(); + + session.save(book); + session.getTransaction() + .commit(); + session.close(); + + assertNotNull(book.getCreatedOn()); + assertNotNull(book.getLastUpdatedOn()); + } + + @Test + void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreEqual() { + session = sessionFactory.openSession(); + session.beginTransaction(); + Book book = new Book(); + + session.save(book); + session.getTransaction().commit(); + session.close(); + + Date createdOn = Date.from(book.getCreatedOn()); + Date lastUpdatedOn = Date.from(book.getLastUpdatedOn()); + SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss"); + + assertEquals(formatter.format(createdOn), formatter.format(lastUpdatedOn)); + } + + @Test + void whenUpdatingEntity_ThenLastUpdatedOnIsUpdatedAndCreatedOnStaysTheSame() { + session = sessionFactory.openSession(); + session.setHibernateFlushMode(MANUAL); + session.beginTransaction(); + Book book = new Book(); + session.save(book); + session.flush(); + Instant createdOnAfterCreation = book.getCreatedOn(); + Instant lastUpdatedOnAfterCreation = book.getLastUpdatedOn(); + + String newName = "newName"; + book.setTitle(newName); + session.save(book); + session.flush(); + session.getTransaction().commit(); + session.close(); + Instant createdOnAfterUpdate = book.getCreatedOn(); + Instant lastUpdatedOnAfterUpdate = book.getLastUpdatedOn(); + + assertEquals(newName, book.getTitle()); + assertNotNull(createdOnAfterUpdate); + assertNotNull(lastUpdatedOnAfterUpdate); + assertEquals(createdOnAfterCreation, createdOnAfterUpdate); + assertNotEquals(lastUpdatedOnAfterCreation, lastUpdatedOnAfterUpdate); + } + + @AfterAll + static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java index 460b65ee1291..9da3a90034b3 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java @@ -6,10 +6,9 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; -import org.junit.Assert; import org.junit.Test; -import javax.persistence.TypedQuery; +import jakarta.persistence.TypedQuery; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; @@ -76,7 +75,7 @@ public void givenEmployee_whenCustomTypeInQuery_thenReturnEntity() { doInHibernate(this::sessionFactory, session -> { session.save(e); - TypedQuery query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode", OfficeEmployee.class); + TypedQuery query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipCode = :pinCode", OfficeEmployee.class); query.setParameter("pinCode",100); int size = query.getResultList().size(); @@ -100,8 +99,8 @@ private SessionFactory sessionFactory() { return metadata.buildSessionFactory(); } - private static Map getProperties() { - Map dbSettings = new HashMap<>(); + private static Map getProperties() { + Map dbSettings = new HashMap<>(); dbSettings.put(Environment.URL, "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1"); dbSettings.put(Environment.USER, "sa"); dbSettings.put(Environment.PASS, ""); diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java index 270a235ef057..f038d2b16d9a 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java @@ -8,7 +8,7 @@ import org.junit.*; import org.junit.rules.ExpectedException; -import javax.persistence.PersistenceException; +import jakarta.persistence.PersistenceException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java index 37125e8b1562..04f061381183 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java @@ -78,8 +78,8 @@ private SessionFactory sessionFactory() { return metadata.buildSessionFactory(); } - private static Map getProperties() { - Map dbSettings = new HashMap<>(); + private static Map getProperties() { + Map dbSettings = new HashMap<>(); dbSettings.put(Environment.URL, "jdbc:h2:mem:mydbJoinColumn;DB_CLOSE_DELAY=-1"); dbSettings.put(Environment.USER, "sa"); dbSettings.put(Environment.PASS, ""); diff --git a/persistence-modules/hibernate-enterprise/pom.xml b/persistence-modules/hibernate-enterprise/pom.xml index 833f19c6734a..eaa7b0e765a8 100644 --- a/persistence-modules/hibernate-enterprise/pom.xml +++ b/persistence-modules/hibernate-enterprise/pom.xml @@ -78,10 +78,11 @@ - 5.3.7.Final - 6.0.6 - 2.2.3 + 6.1.7.Final + 8.0.32 + 2.6.0 0.9 + 1.14.2 \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java index 989fa1281abd..8ef748780473 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.exception; -import javax.persistence.Entity; +import jakarta.persistence.Entity; @Entity public class EntityWithNoId { diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java index 0724ced56b84..b7e80511e623 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.exception; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "PRODUCT") diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductEntity.java index b9c5f5010dd2..a2dcec61e9ba 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductEntity.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductEntity.java @@ -1,8 +1,8 @@ package com.baeldung.hibernate.exception; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "PRODUCT") diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductNotMapped.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductNotMapped.java new file mode 100644 index 000000000000..827ad15e5b68 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductNotMapped.java @@ -0,0 +1,32 @@ +package com.baeldung.hibernate.exception; + +public class ProductNotMapped { + + private int id; + private String name; + private String description; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + 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; + } +} diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java index 9dcf4058a7d8..bc50c11d8149 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.logging; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Employee { diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java index 736abde866b3..23b9a87eef32 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java @@ -1,11 +1,11 @@ package com.baeldung.hibernate.pojo; -import com.vividsolutions.jts.geom.Point; +import org.locationtech.jts.geom.Point; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; @Entity public class PointEntity { diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java index 69208c8cd4d2..32cb146f2371 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java @@ -1,10 +1,10 @@ package com.baeldung.hibernate.pojo; -import com.vividsolutions.jts.geom.Polygon; +import org.locationtech.jts.geom.Polygon; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; @Entity public class PolygonEntity { diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java index 9b26c117ebe1..263908a5fccb 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Student { diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java index 6a95a7acf5bd..37666399756e 100644 --- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java @@ -1,8 +1,8 @@ package com.baeldung.persistence.model; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; @Entity public class Person { diff --git a/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml index 474eeb7a4405..291512529528 100644 --- a/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml @@ -7,12 +7,12 @@ Hibernate EntityManager Demo true - + - - - - + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java index 74f752ab8c0a..e0f13582ab8c 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java @@ -9,23 +9,23 @@ import java.net.URL; import java.util.Properties; -import javax.persistence.Query; +import jakarta.persistence.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.locationtech.jts.geom.Coordinate; +import org.locationtech.jts.io.ParseException; +import org.locationtech.jts.io.WKTReader; +import org.locationtech.jts.geom.Geometry; +import org.locationtech.jts.geom.Point; +import org.locationtech.jts.geom.Polygon; +import org.locationtech.jts.util.GeometricShapeFactory; import com.baeldung.hibernate.pojo.PointEntity; import com.baeldung.hibernate.pojo.PolygonEntity; -import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.Point; -import com.vividsolutions.jts.geom.Polygon; -import com.vividsolutions.jts.io.ParseException; -import com.vividsolutions.jts.io.WKTReader; -import com.vividsolutions.jts.util.GeometricShapeFactory; import geodb.GeoDB; @@ -39,7 +39,7 @@ public void setUp() throws IOException { session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") .openSession(); transaction = session.beginTransaction(); - session.doWork(conn -> { GeoDB.InitGeoDB(conn); }); + session.doWork(GeoDB::InitGeoDB); } @After @@ -135,9 +135,7 @@ private void insertPolygon(String polygon) throws ParseException { private Geometry wktToGeometry(String wellKnownText) throws ParseException { WKTReader fromText = new WKTReader(); - Geometry geom = null; - geom = fromText.read(wellKnownText); - return geom; + return fromText.read(wellKnownText); } private static Geometry createCircle(double x, double y, double radius) { diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java index 891352843d25..37c21d189967 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java @@ -6,28 +6,25 @@ import java.io.IOException; import java.util.List; -import javax.persistence.OptimisticLockException; -import javax.persistence.PersistenceException; +import jakarta.persistence.OptimisticLockException; +import jakarta.persistence.PersistenceException; -import org.hibernate.AnnotationException; import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.NonUniqueObjectException; import org.hibernate.PropertyValueException; import org.hibernate.Session; import org.hibernate.SessionFactory; -import org.hibernate.StaleObjectStateException; import org.hibernate.StaleStateException; import org.hibernate.Transaction; -import org.hibernate.TransactionException; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.DataException; import org.hibernate.exception.SQLGrammarException; -import org.hibernate.hql.internal.ast.QuerySyntaxException; import org.hibernate.id.IdentifierGenerationException; import org.hibernate.query.NativeQuery; +import org.hibernate.query.sqm.UnknownEntityException; import org.hibernate.tool.schema.spi.CommandAcceptanceException; import org.hibernate.tool.schema.spi.SchemaManagementException; import org.junit.Before; @@ -63,12 +60,15 @@ private Configuration getConfiguration() { @Test public void whenQueryExecutedWithUnmappedEntity_thenMappingException() { - thrown.expectCause(isA(MappingException.class)); - thrown.expectMessage("Unknown entity: java.lang.String"); + thrown.expect(isA(MappingException.class)); + thrown.expectMessage("Unable to locate persister: com.baeldung.hibernate.exception.ProductNotMapped"); + + ProductNotMapped product = new ProductNotMapped(); + product.setId(1); + product.setName("test"); Session session = sessionFactory.openSession(); - NativeQuery query = session.createNativeQuery("select name from PRODUCT", String.class); - query.getResultList(); + session.save(product); } @Test @@ -82,8 +82,8 @@ public void whenQueryExecuted_thenOK() { @Test public void whenQueryExecutedWithInvalidClassName_thenQuerySyntaxException() { - thrown.expectCause(isA(QuerySyntaxException.class)); - thrown.expectMessage("PRODUCT is not mapped [from PRODUCT]"); + thrown.expectCause(isA(UnknownEntityException.class)); + thrown.expectMessage("Could not resolve root entity 'PRODUCT"); Session session = sessionFactory.openSession(); List results = session.createQuery("from PRODUCT", Product.class) @@ -92,8 +92,8 @@ public void whenQueryExecutedWithInvalidClassName_thenQuerySyntaxException() { @Test public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() { - thrown.expect(AnnotationException.class); - thrown.expectMessage("No identifier specified for entity"); + thrown.expect(isA(HibernateException.class)); + thrown.expectMessage("Entity 'com.baeldung.hibernate.exception.EntityWithNoId' has no identifier (every '@Entity' class must declare or inherit at least one '@Id' or '@EmbeddedId' property)"); Configuration cfg = getConfiguration(); cfg.addAnnotatedClass(EntityWithNoId.class); @@ -132,9 +132,8 @@ public void whenWrongDialectSpecified_thenCommandAcceptanceException() { @Test public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() { - thrown.expect(isA(PersistenceException.class)); thrown.expectCause(isA(SQLGrammarException.class)); - thrown.expectMessage("SQLGrammarException: could not prepare statement"); + thrown.expectMessage("could not prepare statement"); Configuration cfg = getConfiguration(); cfg.addAnnotatedClass(Product.class); @@ -162,9 +161,8 @@ public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() { @Test public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() { - thrown.expect(isA(PersistenceException.class)); thrown.expectCause(isA(SQLGrammarException.class)); - thrown.expectMessage("SQLGrammarException: could not prepare statement"); + thrown.expectMessage("could not prepare statement"); Session session = sessionFactory.openSession(); NativeQuery query = session.createNativeQuery("select * from NON_EXISTING_TABLE", Product.class); @@ -173,9 +171,8 @@ public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() { @Test public void whenDuplicateIdSaved_thenConstraintViolationException() { - thrown.expect(isA(PersistenceException.class)); thrown.expectCause(isA(ConstraintViolationException.class)); - thrown.expectMessage("ConstraintViolationException: could not execute statement"); + thrown.expectMessage("could not execute statement"); Session session = null; Transaction transaction = null; @@ -253,7 +250,7 @@ public void givenEntityWithoutId_whenCallingSave_thenThrowIdentifierGenerationEx @Test public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() { thrown.expectCause(isA(DataException.class)); - thrown.expectMessage("org.hibernate.exception.DataException: could not prepare statement"); + thrown.expectMessage("could not prepare statement"); Session session = sessionFactory.openSession(); NativeQuery query = session.createNativeQuery("select * from PRODUCT where id='wrongTypeId'", Product.class); @@ -330,9 +327,8 @@ public void whenDeletingADeletedObject_thenOptimisticLockException() { @Test public void whenUpdatingNonExistingObject_thenStaleStateException() { - thrown.expect(isA(OptimisticLockException.class)); - thrown.expectMessage("Row was updated or deleted by another transaction"); - thrown.expectCause(isA(StaleObjectStateException.class)); + thrown.expectCause(isA(StaleStateException.class)); + thrown.expectMessage("Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; statement executed: update PRODUCT set description=?, name=? where id=?"); Session session = null; Transaction transaction = null; @@ -356,7 +352,8 @@ public void whenUpdatingNonExistingObject_thenStaleStateException() { @Test public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() { - thrown.expect(isA(TransactionException.class)); + thrown.expect(isA(IllegalStateException.class)); + thrown.expectMessage("Transaction already active"); Session session = null; Transaction transaction = null; @@ -368,6 +365,7 @@ public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() product1.setId(15); product1.setName("Product1"); session.save(product1); + transaction = session.beginTransaction(); transaction.setRollbackOnly(); transaction.commit(); diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java index 1b6cee7e67c9..3e4895e5e6e7 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java @@ -2,9 +2,9 @@ import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity(name = "Car") @Table(name = "Car") diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java index fdc3f9fa81f7..2dc94172b18f 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java @@ -79,9 +79,9 @@ protected void thenCarNotFound(String brand) { private void createCarTable() { Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); - session.createSQLQuery("drop table Car if exists") + session.createNativeQuery("drop table Car if exists") .executeUpdate(); - session.createSQLQuery("create table Car (brand varchar(255) primary key)") + session.createNativeQuery("create table Car (brand varchar(255) primary key)") .executeUpdate(); tx.commit(); } diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java index 92f477a64685..904805f2ce65 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java @@ -1,7 +1,5 @@ package com.baeldung.hibernate.multitenancy.database; -import java.io.IOException; - import org.junit.Test; import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest; @@ -14,7 +12,7 @@ public String getPropertyFile() { } @Test - public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() throws IOException { + public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() { whenCurrentTenantIs(TenantIdNames.MYDB1); whenAddCar("myCar"); thenCarFound("myCar"); diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java index eb1f410622af..47abf6ff85e9 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java @@ -34,8 +34,13 @@ protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) { private void initConnectionProviderForTenant(String tenantId) throws IOException { Properties properties = new Properties(); properties.load(getClass().getResourceAsStream(String.format("/hibernate-database-%s.properties", tenantId))); + Map configProperties = new HashMap<>(); + for (String key : properties.stringPropertyNames()) { + String value = properties.getProperty(key); + configProperties.put(key, value); + } DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl(); - connectionProvider.configure(properties); + connectionProvider.configure(configProperties); this.connectionProviderMap.put(tenantId, connectionProvider); } diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java index 601eba651c7b..67b838fdf10e 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java @@ -3,6 +3,8 @@ import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; import java.util.Properties; import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; @@ -39,9 +41,14 @@ public Connection getConnection(String tenantIdentifier) throws SQLException { private ConnectionProvider initConnectionProvider() throws IOException { Properties properties = new Properties(); properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties")); + Map configProperties = new HashMap<>(); + for (String key : properties.stringPropertyNames()) { + String value = properties.getProperty(key); + configProperties.put(key, value); + } DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl(); - connectionProvider.configure(properties); + connectionProvider.configure(configProperties); return connectionProvider; } diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java index 8c571428b488..c3d23623394a 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java @@ -7,7 +7,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import javax.persistence.PersistenceException; +import jakarta.persistence.PersistenceException; import org.hibernate.HibernateException; import org.hibernate.Session; diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties index e08a23166d56..1e086f60d497 100644 --- a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties +++ b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties @@ -12,5 +12,3 @@ hibernate.c3p0.min_size=5 hibernate.c3p0.max_size=20 hibernate.c3p0.acquire_increment=5 hibernate.c3p0.timeout=1800 - -hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties index c16666cbf5ea..e156965ce7d9 100644 --- a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties +++ b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties @@ -4,7 +4,7 @@ hibernate.connection.username=sa hibernate.connection.autocommit=true jdbc.password= -hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect +hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=true hibernate.hbm2ddl.auto=create-drop diff --git a/persistence-modules/hibernate-exceptions/pom.xml b/persistence-modules/hibernate-exceptions/pom.xml index 4bef688715b9..670ff4cdb8eb 100644 --- a/persistence-modules/hibernate-exceptions/pom.xml +++ b/persistence-modules/hibernate-exceptions/pom.xml @@ -24,11 +24,6 @@ hibernate-core ${hibernate.version} - - javax.xml.bind - jaxb-api - ${jaxb.version} - com.h2database h2 @@ -37,8 +32,7 @@ - 2.4.0 - 2.3.0 + 2.7.1 2.1.214 diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Category.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Category.java index 25d31d50c77b..cab06ae9cf0a 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Category.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Category.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.entitynotfoundexception; -import javax.persistence.*; +import jakarta.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Item.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Item.java index 3abed00eb85c..2d07178aafd0 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Item.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Item.java @@ -1,9 +1,6 @@ package com.baeldung.hibernate.entitynotfoundexception; -import org.hibernate.annotations.NotFound; -import org.hibernate.annotations.NotFoundAction; - -import javax.persistence.*; +import jakarta.persistence.*; import java.io.Serializable; @Entity diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/User.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/User.java index d89047195c74..8351c5df9687 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/User.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/User.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.entitynotfoundexception; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; @Entity public class User { diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Comment.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Comment.java index 4a3e9739e2a1..e73adfef6b6c 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Comment.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Comment.java @@ -1,10 +1,10 @@ package com.baeldung.hibernate.exception.detachedentity.entity; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; @Entity public class Comment { diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Post.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Post.java index 7d95b4194809..155a1bfe6907 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Post.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Post.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.exception.detachedentity.entity; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Post { diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/Role.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/Role.java index c15e674c52c2..5e613004a380 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/Role.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/Role.java @@ -1,11 +1,11 @@ package com.baeldung.hibernate.exception.lazyinitialization.entity; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "role") diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/User.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/User.java index 5bd7e00801dd..ffae05c0a060 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/User.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/User.java @@ -3,14 +3,14 @@ import java.util.HashSet; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; @Entity @Table(name = "user") diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java index 3c9c7c5b31a5..eb697334ae06 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java @@ -1,10 +1,10 @@ package com.baeldung.hibernate.exception.persistentobject.entity; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; @Entity public class Article { diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java index fa6aaa9abe33..f8dcb82b7e52 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java @@ -2,12 +2,11 @@ import java.util.List; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java index 342da27c77f5..986c7f061f8e 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java @@ -1,11 +1,10 @@ package com.baeldung.hibernate.exception.persistentobject.entity; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Book { diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Address.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Address.java index e450fc3c182e..8d1208e03603 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Address.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Address.java @@ -1,18 +1,12 @@ package com.baeldung.hibernate.exception.transientobject.entity; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; @Entity @Table(name = "address") diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Author.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Author.java index f1a88daa360b..271e810002c0 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Author.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Author.java @@ -3,15 +3,14 @@ import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; import java.util.HashSet; import java.util.Set; diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Book.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Book.java index 91728430eace..0734cccff118 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Book.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Book.java @@ -4,15 +4,14 @@ import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; import java.util.HashSet; import java.util.Set; diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Department.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Department.java index 4b8fa699642b..5bd9a109ab11 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Department.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Department.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.exception.transientobject.entity; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; import java.util.HashSet; import java.util.Set; diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Employee.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Employee.java index 56443cce70ef..6a2ec8b9388b 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Employee.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Employee.java @@ -4,15 +4,14 @@ import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; @Entity @Table(name = "employee") diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/User.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/User.java index eff1a88b513b..cf56afd8b9da 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/User.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/User.java @@ -1,19 +1,14 @@ package com.baeldung.hibernate.exception.transientobject.entity; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; @Entity @Table(name = "user") diff --git a/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java index bcb4e3eb9515..f339afd536de 100644 --- a/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java +++ b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java @@ -4,10 +4,10 @@ import org.junit.Before; import org.junit.Test; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityNotFoundException; -import javax.persistence.Persistence; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.EntityNotFoundException; +import jakarta.persistence.Persistence; import java.io.IOException; public class EntityNotFoundExceptionIntegrationTest { diff --git a/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/detachedentity/DetachedEntityUnitTest.java b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/detachedentity/DetachedEntityUnitTest.java index afb0efae77ec..cb4313c53785 100644 --- a/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/detachedentity/DetachedEntityUnitTest.java +++ b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/detachedentity/DetachedEntityUnitTest.java @@ -3,13 +3,12 @@ import com.baeldung.hibernate.exception.detachedentity.entity.Comment; import com.baeldung.hibernate.exception.detachedentity.entity.Post; -import org.assertj.core.api.Assertions; import org.hibernate.Session; import org.junit.After; import org.junit.Before; import org.junit.Test; -import javax.persistence.PersistenceException; +import jakarta.persistence.PersistenceException; import java.util.List; @@ -43,7 +42,7 @@ public void givenDetachedPost_whenTryingToPersist_thenThrowException() { assertThatThrownBy(() -> session.persist(detachedPost)) .isInstanceOf(PersistenceException.class) - .hasMessageContaining("org.hibernate.PersistentObjectException: detached entity passed to persist"); + .hasMessageContaining("detached entity passed to persist: com.baeldung.hibernate.exception.detachedentity.entity.Post"); } @Test @@ -72,13 +71,13 @@ public void givenDetachedPost_whenPersistingNewCommentWithIt_thenThrowException( assertThatThrownBy(() -> session.persist(detachedPost)) .isInstanceOf(PersistenceException.class) - .hasMessageContaining("org.hibernate.PersistentObjectException: detached entity passed to persist"); + .hasMessageContaining("detached entity passed to persist: com.baeldung.hibernate.exception.detachedentity.entity.Post"); } @Test public void givenDetachedPost_whenMergeAndPersistComment_thenNoExceptionIsThrown() { Comment comment = new Comment("nice article!"); - Post mergedPost = (Post) session.merge(detachedPost); + Post mergedPost = session.merge(detachedPost); comment.setPost(mergedPost); session.persist(comment); diff --git a/persistence-modules/hibernate-jpa/pom.xml b/persistence-modules/hibernate-jpa/pom.xml index f742290884fd..5a99c1c4d0dc 100644 --- a/persistence-modules/hibernate-jpa/pom.xml +++ b/persistence-modules/hibernate-jpa/pom.xml @@ -83,11 +83,12 @@ - 5.3.7.Final - 8.0.13 - 2.2.3 - 2.1.7.RELEASE - 1.4.200 + 8.0.32 + 2.6.0 + 3.0.4 + 2.1.214 + 2.0.7 + 1.4.6 - \ No newline at end of file + diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java index 506e67498463..ec0e2f2e2cd7 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.converters; -import javax.persistence.AttributeConverter; -import javax.persistence.Converter; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; import com.baeldung.hibernate.pojo.PersonName; diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java index ff94f4f849a1..39e69a2b1c0f 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -2,7 +2,7 @@ import java.util.List; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class Department { diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java index 6510e706503e..38519644c5d8 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.entities; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; @org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), - @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where employeeNumber = :employeeNumber"), @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) @org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java index 1de8de032764..5a6f9c7c6c3c 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.entitymanager.getreference; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; @Entity public class Game { diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java index 459a3a00adcd..6e62aeda4548 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java @@ -1,8 +1,8 @@ package com.baeldung.hibernate.entitymanager.getreference; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; @Entity public class Player { diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java index b547a60b06be..6263df4237f8 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java @@ -2,7 +2,7 @@ import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory; import com.baeldung.hibernate.jpabootstrap.entities.User; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; public class Application { @@ -24,8 +24,7 @@ public static void main(String[] args) { } private static class EntityManagerHolder { - private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory( - new Class[]{User.class}).getEntityManager(); + private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory(new Class[]{User.class}).getEntityManager(); } public static EntityManager getJpaEntityManager() { diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java index 3852b44b6449..af01ea630c2f 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java @@ -6,11 +6,11 @@ import java.util.List; import java.util.Properties; import javax.sql.DataSource; -import javax.persistence.SharedCacheMode; -import javax.persistence.ValidationMode; -import javax.persistence.spi.ClassTransformer; -import javax.persistence.spi.PersistenceUnitInfo; -import javax.persistence.spi.PersistenceUnitTransactionType; +import jakarta.persistence.SharedCacheMode; +import jakarta.persistence.ValidationMode; +import jakarta.persistence.spi.ClassTransformer; +import jakarta.persistence.spi.PersistenceUnitInfo; +import jakarta.persistence.spi.PersistenceUnitTransactionType; import org.hibernate.jpa.HibernatePersistenceProvider; public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo { diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java index bc1932af6f73..e115727d673a 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java @@ -7,10 +7,10 @@ import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import javax.sql.DataSource; -import javax.persistence.EntityManagerFactory; -import javax.persistence.spi.PersistenceUnitInfo; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.spi.PersistenceUnitInfo; import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor; diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java index 86ca1dfa19ab..43c99f8d96ea 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java @@ -1,10 +1,10 @@ package com.baeldung.hibernate.jpabootstrap.entities; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "users") diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java index e79168a4519b..9a3216b5eb61 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java @@ -2,13 +2,13 @@ import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaBuilder.In; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; -import javax.persistence.criteria.Subquery; +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaBuilder.In; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.criteria.Subquery; import com.baeldung.hibernate.entities.Department; import com.baeldung.hibernate.entities.DeptEmployee; diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java index e05eb460302a..0c3238cf98f8 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java @@ -1,12 +1,12 @@ package com.baeldung.hibernate.onetoone.foreignkeybased; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; @Entity @Table(name = "address") diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java index dda972f29c1c..14c2a0a28c52 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java @@ -1,14 +1,14 @@ package com.baeldung.hibernate.onetoone.foreignkeybased; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; @Entity @Table(name = "users") diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java index a0bc101b9f32..fc8b9eefec76 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java @@ -1,15 +1,15 @@ package com.baeldung.hibernate.onetoone.jointablebased; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; @Entity @Table(name = "employee") diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java index f530611f6e79..0834b9f9d7e2 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.onetoone.jointablebased; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; @Entity @Table(name = "workstation") diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java index e70c62e77ba4..d738b900bca0 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java @@ -1,12 +1,12 @@ package com.baeldung.hibernate.onetoone.sharedkeybased; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.MapsId; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.MapsId; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; @Entity @Table(name = "address") diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java index 605671a14907..8ce767eaf706 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java @@ -1,15 +1,15 @@ package com.baeldung.hibernate.onetoone.sharedkeybased; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToOne; -import javax.persistence.PrimaryKeyJoinColumn; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; +import jakarta.persistence.PrimaryKeyJoinColumn; +import jakarta.persistence.Table; @Entity @Table(name = "users") diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java index 1af3e3e21b34..b8212a049d64 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.optimisticlocking; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class OptimisticLockingCourse { diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java index b79212ae8d1f..22f11e37fb00 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.optimisticlocking; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.List; @Entity diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java index c889cb612750..7c6d20df4050 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.pessimisticlocking; -import javax.persistence.Embeddable; +import jakarta.persistence.Embeddable; @Embeddable public class Address { diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java index cb73cbc958f9..9f36e3b308e1 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.pessimisticlocking; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.List; @Entity diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java index e491c09eb558..b954c9fdb222 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pessimisticlocking; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; @Entity @Inheritance(strategy = InheritanceType.JOINED) diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java index aea7d5fc87a5..012f3d1d39a5 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.pessimisticlocking; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class PessimisticLockingCourse { diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java index a1328cbdaddc..e5b00f380093 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.pessimisticlocking; -import javax.persistence.Entity; +import jakarta.persistence.Entity; import java.math.BigDecimal; @Entity diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java index e6c5f476b442..c5634ebc242e 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.pessimisticlocking; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.List; @Entity diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java index 5fae7f6a9748..7aeadd4501ea 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java @@ -1,8 +1,8 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "MOVIE") diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java index 390a5954ed22..d0c8b8aa2fd5 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.Convert; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Convert; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; import com.baeldung.hibernate.converters.PersonNameConverter; diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java index 25e51e35d0af..66a68367d711 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "posts") diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java index 9b26c117ebe1..263908a5fccb 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Student { diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Account.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Account.java index b051809ee50d..7070f21c45fc 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Account.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Account.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.serializable; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; @Entity public class Account { diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Email.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Email.java index 11e7c6f1593a..4ba902281a1c 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Email.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Email.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.serializable; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; import java.io.Serializable; @Entity diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/User.java index e7820fe52f32..267155b4db2a 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/User.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/User.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.serializable; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; @Entity public class User { diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/UserId.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/UserId.java index 7d3d382f6787..6fcbeafdd092 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/UserId.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/UserId.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.serializable; -import javax.persistence.Embeddable; +import jakarta.persistence.Embeddable; import java.io.Serializable; @Embeddable diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java index 7252ac46f56a..afdbf067c322 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java @@ -1,9 +1,9 @@ package com.baeldung.persistencecontext.entity; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; -@Entity +@Entity(name = "users") public class User { @Id diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java index ef25aac69fbb..7ad6aae745d6 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java @@ -1,15 +1,15 @@ package com.baeldung.persistencecontext.service; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.transaction.Transactional; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.PersistenceContextType; +import jakarta.transaction.Transactional; -import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; import com.baeldung.persistencecontext.entity.User; -@Component +@Service public class ExtendedPersistenceContextUserService { @PersistenceContext(type = PersistenceContextType.EXTENDED) diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java index 481defcf0831..6b9fd1f14c9b 100644 --- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java @@ -1,20 +1,20 @@ package com.baeldung.persistencecontext.service; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.transaction.Transactional; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.transaction.Transactional; -import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; import com.baeldung.persistencecontext.entity.User; -@Component +@Service public class TransctionPersistenceContextUserService { @PersistenceContext private EntityManager entityManager; - + @Transactional public User insertWithTransaction(User user) { entityManager.persist(user); diff --git a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml index 12b41a497323..1669413289c9 100644 --- a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml @@ -8,12 +8,13 @@ com.baeldung.hibernate.pojo.Movie true - + - - - - + + + + + @@ -34,10 +35,14 @@ - - - - + + + + + + + + @@ -57,16 +62,20 @@ - - - - - + + + + + - - - - + + + + + + + + @@ -87,16 +96,20 @@ - - - - - + + + + + - - - - + + + + + + + + @@ -113,10 +126,16 @@ - - - - + + + + + + + + + + diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java index e8e6aeed7caa..86f059c6d782 100644 --- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java @@ -5,9 +5,9 @@ import org.junit.jupiter.api.*; import org.slf4j.LoggerFactory; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; @@ -87,8 +87,8 @@ public void whenUsingFindMethodToUpdateGame_thenExecutesSelectForGame() { }); StringBuilder expected = new StringBuilder(); - expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); - expected.append("Hibernate: update Game set name=? where id=?\n"); + expected.append("Hibernate: select g1_0.id,g1_0.name from Game g1_0 where g1_0.id=?" + System.lineSeparator()); + expected.append("Hibernate: update Game set name=? where id=?" + System.lineSeparator()); assertEquals(expected.toString(), output.toString()); } @@ -104,8 +104,8 @@ public void whenUsingGetReferenceMethodToUpdateGame_thenExecutesSelectForGame() }); StringBuilder expected = new StringBuilder(); - expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); - expected.append("Hibernate: update Game set name=? where id=?\n"); + expected.append("Hibernate: select g1_0.id,g1_0.name from Game g1_0 where g1_0.id=?" + System.lineSeparator()); + expected.append("Hibernate: update Game set name=? where id=?" + System.lineSeparator()); assertEquals(expected.toString(), output.toString()); } @@ -120,10 +120,9 @@ public void whenUsingFindMethodToDeletePlayer_thenExecutesSelectForPlayer() { StringBuilder expected = new StringBuilder(); expected.append("Hibernate: select "); - expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); - expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); - expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); - expected.append("Hibernate: delete from Player where id=?\n"); + expected.append("p1_0.id,g1_0.id,g1_0.name,p1_0.name "); + expected.append("from Player p1_0 left join Game g1_0 on g1_0.id=p1_0.game_id where p1_0.id=?" + System.lineSeparator()); + expected.append("Hibernate: delete from Player where id=?" + System.lineSeparator()); assertEquals(expected.toString(), output.toString()); } @@ -137,11 +136,7 @@ public void whenUsingGetReferenceMethodToDeletePlayer_thenExecutesSelectForPlaye }); StringBuilder expected = new StringBuilder(); - expected.append("Hibernate: select "); - expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); - expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); - expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); - expected.append("Hibernate: delete from Player where id=?\n"); + expected.append("Hibernate: delete from Player where id=?" + System.lineSeparator()); assertEquals(expected.toString(), output.toString()); } @@ -159,12 +154,11 @@ public void whenUsingFindMethodToUpdatePlayersGame_thenExecutesSelectForGame() { })); StringBuilder expected = new StringBuilder(); - expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: select g1_0.id,g1_0.name from Game g1_0 where g1_0.id=?" + System.lineSeparator()); expected.append("Hibernate: select "); - expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); - expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); - expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); - expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + expected.append("p1_0.id,g1_0.id,g1_0.name,p1_0.name "); + expected.append("from Player p1_0 left join Game g1_0 on g1_0.id=p1_0.game_id where p1_0.id=?" + System.lineSeparator()); + expected.append("Hibernate: update Player set game_id=?,name=? where id=?" + System.lineSeparator()); assertEquals(expected.toString(), output.toString()); } @@ -183,10 +177,9 @@ public void whenUsingGetReferenceMethodToUpdatePlayersGame_thenDoesNotExecuteSel StringBuilder expected = new StringBuilder(); expected.append("Hibernate: select "); - expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); - expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); - expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); - expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + expected.append("p1_0.id,g1_0.id,g1_0.name,p1_0.name "); + expected.append("from Player p1_0 left join Game g1_0 on g1_0.id=p1_0.game_id where p1_0.id=?" + System.lineSeparator()); + expected.append("Hibernate: update Player set game_id=?,name=? where id=?" + System.lineSeparator()); assertEquals(expected.toString(), output.toString()); } diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java index 2b7c5e8119c3..29be19dd681d 100644 --- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java @@ -5,9 +5,9 @@ import org.junit.jupiter.api.*; import org.slf4j.LoggerFactory; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java index 17f6b10b8a06..20a0bca6f10d 100644 --- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java @@ -5,9 +5,9 @@ import org.junit.jupiter.api.*; import org.slf4j.LoggerFactory; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java index 2b12734a1065..16d1057285cb 100644 --- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java @@ -9,7 +9,7 @@ import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.hibernate.HibernateException; import org.hibernate.Session; @@ -81,13 +81,10 @@ public final void teardown() { @Test public final void givenCriteriaQuery_whenSearchedUsingCriteriaBuilderWithListofAuthors_thenResultIsFilteredByAuthorNames() { - List titles = new ArrayList() { - { - add("Manager"); - add("Senior Manager"); - add("Director"); - } - }; + List titles = new ArrayList<>(); + titles.add("Manager"); + titles.add("Senior Manager"); + titles.add("Director"); List result = searchService.filterbyTitleUsingCriteriaBuilder(titles); assertEquals("Number of Employees does not match with expected.", 6, result.size()); assertThat(result.stream() diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java index 37c490f29716..2fa302e27003 100644 --- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java @@ -3,9 +3,9 @@ import java.io.IOException; import java.util.Arrays; -import javax.persistence.EntityManager; -import javax.persistence.LockModeType; -import javax.persistence.OptimisticLockException; +import jakarta.persistence.EntityManager; +import jakarta.persistence.LockModeType; +import jakarta.persistence.OptimisticLockException; import org.hibernate.SessionFactory; import org.junit.After; diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java index 4b9c7720fdba..4085a98dadc5 100644 --- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java @@ -1,14 +1,14 @@ package com.baeldung.hibernate.pessimisticlocking; import com.baeldung.hibernate.HibernateUtil; -import com.vividsolutions.jts.util.Assert; +import org.locationtech.jts.util.Assert; import org.hibernate.SessionFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import javax.persistence.*; +import jakarta.persistence.*; import java.io.IOException; import java.util.Arrays; @@ -46,7 +46,7 @@ public void givenFoundRecordWithPessimisticRead_whenFindingNewOne_PessimisticLoc } @Test - public void givenRecordWithPessimisticReadQuery_whenQueryingNewOne_PessimisticLockExceptionThrown() throws IOException { + public void givenRecordWithPessimisticReadQuery_whenQueryingNewOne_PessimisticLockExceptionThrown() { try { EntityManager entityManager = getEntityManagerWithOpenTransaction(); Query query = entityManager.createQuery("from Student where studentId = :studentId"); diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java index 81cb7d95f8c9..c2f2326159dd 100644 --- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java @@ -6,9 +6,9 @@ import org.junit.AfterClass; import org.junit.Test; -import javax.persistence.EntityManager; -import javax.persistence.LockModeType; -import javax.persistence.PessimisticLockScope; +import jakarta.persistence.EntityManager; +import jakarta.persistence.LockModeType; +import jakarta.persistence.PessimisticLockScope; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; @@ -36,7 +36,7 @@ public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChild // EXTENDED SCOPE Map map = new HashMap<>(); - map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); + map.put("jakarta.persistence", PessimisticLockScope.EXTENDED); EntityManager em3 = getEntityManagerWithOpenTransaction(); foundEmployee = em3.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); @@ -65,7 +65,7 @@ public void givenEntityWithElementCollection_whenLock_thenHibernateExtendedScope // EXTENDED SCOPE Map map = new HashMap<>(); - map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); + map.put("jakarta.persistence", PessimisticLockScope.EXTENDED); EntityManager em3 = getEntityManagerWithOpenTransaction(); foundCustomer = em3.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); @@ -96,7 +96,7 @@ public void givenEntityWithOneToMany_whenLock_thenHibernateExtendedScopeLockOnly // EXTENDED SCOPE Map map = new HashMap<>(); - map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); + map.put("jakarta.persistence", PessimisticLockScope.EXTENDED); EntityManager em3 = getEntityManagerWithOpenTransaction(); foundCourse = em3.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/serializable/JPASerializableIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/serializable/JPASerializableIntegrationTest.java index 696bc23ab013..551275788960 100644 --- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/serializable/JPASerializableIntegrationTest.java +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/serializable/JPASerializableIntegrationTest.java @@ -4,10 +4,9 @@ import org.junit.Before; import org.junit.Test; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import java.io.IOException; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -17,7 +16,7 @@ public class JPASerializableIntegrationTest { private static EntityManager entityManager; @Before - public void setUp() throws IOException { + public void setUp() { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.serializable.h2_persistence_unit"); entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); @@ -63,7 +62,7 @@ public void givenAssociation_whenPersisted_thenMultipleAccountsWillBeFoundByEmai entityManager.persist(account); entityManager.persist(account2); - List userAccounts = entityManager.createQuery("select a from Account a join fetch a.user where a.user.email = :email") + List userAccounts = entityManager.createQuery("select a from Account a join fetch a.user where a.user.email = :email", Account.class) .setParameter("email", email) .getResultList(); assertEquals(2, userAccounts.size()); diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java index 246a7d59f9d4..f64846ba5953 100644 --- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java @@ -2,7 +2,6 @@ import com.baeldung.hibernate.HibernateUtil; import com.baeldung.hibernate.pojo.Post; -import com.baeldung.hibernate.transaction.PostService; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.BeforeClass; @@ -10,7 +9,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java index b299dd583428..37e6e438d862 100644 --- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java @@ -4,8 +4,8 @@ import com.baeldung.persistencecontext.service.ExtendedPersistenceContextUserService; import com.baeldung.persistencecontext.service.TransctionPersistenceContextUserService; -import javax.persistence.EntityExistsException; -import javax.persistence.TransactionRequiredException; +import jakarta.persistence.EntityExistsException; +import jakarta.persistence.TransactionRequiredException; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/persistence-modules/hibernate-mapping-2/README.md b/persistence-modules/hibernate-mapping-2/README.md index 7a811e17cfe8..36c9f8c30431 100644 --- a/persistence-modules/hibernate-mapping-2/README.md +++ b/persistence-modules/hibernate-mapping-2/README.md @@ -4,4 +4,6 @@ This module contains articles about Hibernate Mappings. ### Relevant articles -- [Hibernate Many to Many Annotation Tutorial](https://www.baeldung.com/hibernate-many-to-many) \ No newline at end of file +- [Hibernate Many to Many Annotation Tutorial](https://www.baeldung.com/hibernate-many-to-many) +- [Boolean Converters in Hibernate 6](https://www.baeldung.com/java-hibernate-6-boolean-converters) +- [Generate UUIDs as Primary Keys With Hibernate](https://www.baeldung.com/java-hibernate-uuid-primary-key) diff --git a/persistence-modules/hibernate-mapping-2/pom.xml b/persistence-modules/hibernate-mapping-2/pom.xml index 2a787a0e467b..1b9a3e45d3df 100644 --- a/persistence-modules/hibernate-mapping-2/pom.xml +++ b/persistence-modules/hibernate-mapping-2/pom.xml @@ -55,32 +55,15 @@ h2 ${h2.version} - - com.sun.xml.bind - jaxb-core - ${com.sun.xml.version} - - - javax.xml.bind - jaxb-api - ${javax.xml.bind.version} - - - com.sun.xml.bind - jaxb-impl - ${com.sun.xml.version} - - 5.0.2.RELEASE - 1.10.6.RELEASE + 6.0.6 + 3.0.3 - 5.2.10.Final 9.0.0.M26 - 2.3.0.1 - 2.3.1 + 4.0.2 2.1.214 diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 000000000000..df409ee8889a --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate; + +import static org.hibernate.boot.registry.StandardServiceRegistryBuilder.DEFAULT_CFG_RESOURCE_NAME; + +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.hibernate.booleanconverters.model.Question; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.model.Project; +import com.baeldung.hibernate.uuids.WebSiteUser; +import com.baeldung.hibernate.uuids.Element; +import com.baeldung.hibernate.uuids.Reservation; +import com.baeldung.hibernate.uuids.Sale; + +public class HibernateUtil { + + private static final String DEFAULT_RESOURCE = "manytomany.cfg.xml"; + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class); + + private static SessionFactory buildSessionFactory(String resource) { + try { + // Create the SessionFactory from hibernate-annotation.cfg.xml + Configuration configuration = new Configuration(); + configuration.addAnnotatedClass(Employee.class); + configuration.addAnnotatedClass(Project.class); + configuration.addAnnotatedClass(WebSiteUser.class); + configuration.addAnnotatedClass(Element.class); + configuration.addAnnotatedClass(Reservation.class); + configuration.addAnnotatedClass(Sale.class); + configuration.addAnnotatedClass(Question.class); + configuration.addPackage(Question.class.getPackageName()); + configuration.configure(resource); + LOGGER.debug("Hibernate Annotation Configuration loaded"); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + LOGGER.debug("Hibernate Annotation serviceRegistry created"); + + return configuration.buildSessionFactory(serviceRegistry); + } catch (Throwable ex) { + LOGGER.error("Initial SessionFactory creation failed.", ex); + throw new ExceptionInInitializerError(ex); + } + } + + public static SessionFactory getSessionFactory() { + return buildSessionFactory(DEFAULT_RESOURCE); + } + + public static SessionFactory getSessionFactory(String resource) { + return buildSessionFactory(resource); + } +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/booleanconverters/model/Question.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/booleanconverters/model/Question.java new file mode 100644 index 000000000000..be2990359f45 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/booleanconverters/model/Question.java @@ -0,0 +1,86 @@ +package com.baeldung.hibernate.booleanconverters.model; + +import java.util.UUID; + +import org.hibernate.type.NumericBooleanConverter; +import org.hibernate.type.TrueFalseConverter; +import org.hibernate.type.YesNoConverter; + +import jakarta.persistence.Convert; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +@Entity +public class Question { + + @Id + private UUID id; + private String content; + @Convert(converter = YesNoConverter.class) + private Boolean correctAnswer; + @Convert(converter = TrueFalseConverter.class) + private Boolean shouldBeAsked; + @Convert(converter = NumericBooleanConverter.class) + private Boolean isEasy; + private Boolean wasAskedBefore; + + public Question() { + } + + public Question(UUID id, String content, Boolean correctAnswer, Boolean shouldBeAsked, Boolean isEasy, Boolean wasAskedBefore) { + this.id = id; + this.content = content; + this.correctAnswer = correctAnswer; + this.shouldBeAsked = shouldBeAsked; + this.isEasy = isEasy; + this.wasAskedBefore = wasAskedBefore; + } + + public UUID getId() { + return id; + } + + public String getContent() { + return content; + } + + public Boolean getCorrectAnswer() { + return correctAnswer; + } + + public Boolean getShouldBeAsked() { + return shouldBeAsked; + } + + public Boolean isEasy() { + return isEasy; + } + + public Boolean getWasAskedBefore() { + return wasAskedBefore; + } + + public void setId(UUID id) { + this.id = id; + } + + public void setContent(String content) { + this.content = content; + } + + public void setCorrectAnswer(Boolean correctAnswer) { + this.correctAnswer = correctAnswer; + } + + public void setShouldBeAsked(Boolean shouldBeAsked) { + this.shouldBeAsked = shouldBeAsked; + } + + public void setEasy(Boolean easy) { + isEasy = easy; + } + + public void setWasAskedBefore(Boolean wasAskedBefore) { + this.wasAskedBefore = wasAskedBefore; + } +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/booleanconverters/model/package-info.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/booleanconverters/model/package-info.java new file mode 100644 index 000000000000..d5041b87c0f2 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/booleanconverters/model/package-info.java @@ -0,0 +1,5 @@ +@ConverterRegistration(converter = YesNoConverter.class) +package com.baeldung.hibernate.booleanconverters.model; + +import org.hibernate.annotations.ConverterRegistration; +import org.hibernate.type.YesNoConverter; \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/PersistenceConfig.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/PersistenceConfig.java similarity index 95% rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/PersistenceConfig.java rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/PersistenceConfig.java index 0d7b8bdbcfad..4ec6c9fb7154 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/PersistenceConfig.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/PersistenceConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.manytomany; +package com.baeldung.hibernate.manytomany; import java.util.Properties; @@ -22,7 +22,7 @@ @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-h2.properties" }) -@ComponentScan({ "com.baeldung.manytomany" }) +@ComponentScan({ "com.baeldung.hibernate.manytomany" }) public class PersistenceConfig { @Autowired @@ -32,7 +32,7 @@ public class PersistenceConfig { public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "com.baeldung.manytomany" }); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.manytomany" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/IEmployeeDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/IEmployeeDao.java new file mode 100644 index 000000000000..7bff73ecf4f4 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/IEmployeeDao.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate.manytomany.dao; + +import com.baeldung.hibernate.manytomany.dao.common.IOperations; +import com.baeldung.hibernate.manytomany.model.Employee; + +public interface IEmployeeDao extends IOperations{ + +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/IProjectDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/IProjectDao.java new file mode 100644 index 000000000000..de800ae7832d --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/IProjectDao.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate.manytomany.dao; + +import com.baeldung.hibernate.manytomany.dao.common.IOperations; +import com.baeldung.hibernate.manytomany.model.Project; + +public interface IProjectDao extends IOperations{ + +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/AbstractDao.java similarity index 85% rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractDao.java rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/AbstractDao.java index b37b48e645a9..6ed04a9b2fab 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractDao.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/AbstractDao.java @@ -1,4 +1,4 @@ -package com.baeldung.manytomany.dao.common; +package com.baeldung.hibernate.manytomany.dao.common; import java.io.Serializable; diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractHibernateDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/AbstractHibernateDao.java similarity index 96% rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractHibernateDao.java rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/AbstractHibernateDao.java index 9c8a8faa2e19..67878906ca47 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractHibernateDao.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/AbstractHibernateDao.java @@ -1,4 +1,4 @@ -package com.baeldung.manytomany.dao.common; +package com.baeldung.hibernate.manytomany.dao.common; import java.io.Serializable; import java.util.List; diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/IOperations.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/IOperations.java similarity index 85% rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/IOperations.java rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/IOperations.java index 8a85b52fc950..2be7fdb75e90 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/IOperations.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/IOperations.java @@ -1,4 +1,4 @@ -package com.baeldung.manytomany.dao.common; +package com.baeldung.hibernate.manytomany.dao.common; import java.io.Serializable; import java.util.List; diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/EmployeeDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/impl/EmployeeDao.java similarity index 50% rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/EmployeeDao.java rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/impl/EmployeeDao.java index b24013c56763..d4364c00c248 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/EmployeeDao.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/impl/EmployeeDao.java @@ -1,10 +1,10 @@ -package com.baeldung.manytomany.dao.impl; +package com.baeldung.hibernate.manytomany.dao.impl; import org.springframework.stereotype.Repository; -import com.baeldung.manytomany.dao.IEmployeeDao; -import com.baeldung.manytomany.dao.common.AbstractHibernateDao; -import com.baeldung.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.dao.IEmployeeDao; +import com.baeldung.hibernate.manytomany.dao.common.AbstractHibernateDao; +import com.baeldung.hibernate.manytomany.model.Employee; @Repository public class EmployeeDao extends AbstractHibernateDao implements IEmployeeDao { diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/impl/ProjectDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/impl/ProjectDao.java new file mode 100644 index 000000000000..a221116013c5 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/impl/ProjectDao.java @@ -0,0 +1,17 @@ +package com.baeldung.hibernate.manytomany.dao.impl; + +import org.springframework.stereotype.Repository; + +import com.baeldung.hibernate.manytomany.dao.IProjectDao; +import com.baeldung.hibernate.manytomany.dao.common.AbstractHibernateDao; +import com.baeldung.hibernate.manytomany.model.Project; + +@Repository +public class ProjectDao extends AbstractHibernateDao implements IProjectDao { + + public ProjectDao() { + super(); + + setClazz(Project.class); + } +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Employee.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java similarity index 80% rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Employee.java rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java index 39671c21bcbf..d606f1281cb5 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Employee.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java @@ -1,19 +1,19 @@ -package com.baeldung.manytomany.model; +package com.baeldung.hibernate.manytomany.model; import java.io.Serializable; import java.util.HashSet; import java.util.Set; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; @Entity @Table(name = "Employee") diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Project.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java similarity index 79% rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Project.java rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java index b5dc3cb85678..8ea31dbc5f92 100644 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Project.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java @@ -1,15 +1,15 @@ -package com.baeldung.manytomany.model; +package com.baeldung.hibernate.manytomany.model; import java.io.Serializable; import java.util.HashSet; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.ManyToMany; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; @Entity @Table(name = "Project") diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Element.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Element.java new file mode 100644 index 000000000000..5112c6df0f80 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Element.java @@ -0,0 +1,32 @@ +package com.baeldung.hibernate.uuids; + +import java.util.UUID; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import org.hibernate.annotations.UuidGenerator; + +@Entity +public class Element { + + @Id + @UuidGenerator + private String id; + + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Reservation.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Reservation.java new file mode 100644 index 000000000000..389376e7851e --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Reservation.java @@ -0,0 +1,43 @@ +package com.baeldung.hibernate.uuids; + +import java.util.UUID; +import jakarta.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; + +@Entity +public class Reservation { + + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + private String status; + + private String number; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Sale.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Sale.java new file mode 100644 index 000000000000..8eaab809122f --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Sale.java @@ -0,0 +1,36 @@ +package com.baeldung.hibernate.uuids; + +import jakarta.persistence.Id; +import jakarta.persistence.Entity; +import org.hibernate.annotations.UuidGenerator; + +import java.util.UUID; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import org.hibernate.annotations.UuidGenerator; + +@Entity +public class Sale { + + @Id + @UuidGenerator + private UUID id; + + private boolean completed; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public boolean isCompleted() { + return completed; + } + + public void setCompleted(boolean completed) { + this.completed = completed; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/WebSiteUser.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/WebSiteUser.java new file mode 100644 index 000000000000..b1a115a3b930 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/WebSiteUser.java @@ -0,0 +1,33 @@ +package com.baeldung.hibernate.uuids; + +import java.util.UUID; +import java.time.LocalDate; +import jakarta.persistence.Id; +import jakarta.persistence.Entity; +import org.hibernate.annotations.UuidGenerator; + +@Entity +public class WebSiteUser { + + @Id + @UuidGenerator(style = UuidGenerator.Style.TIME) + private UUID id; + + private LocalDate registrationDate; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public LocalDate getRegistrationDate() { + return registrationDate; + } + + public void setRegistrationDate(LocalDate registrationDate) { + this.registrationDate = registrationDate; + } +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java deleted file mode 100644 index 68bf5d5bad46..000000000000 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.manytomany.dao; - -import com.baeldung.manytomany.dao.common.IOperations; -import com.baeldung.manytomany.model.Employee; - -public interface IEmployeeDao extends IOperations{ - -} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java deleted file mode 100644 index d2645db44ad2..000000000000 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.manytomany.dao; - -import com.baeldung.manytomany.dao.common.IOperations; -import com.baeldung.manytomany.model.Project; - -public interface IProjectDao extends IOperations{ - -} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/ProjectDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/ProjectDao.java deleted file mode 100644 index a70212f5198e..000000000000 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/ProjectDao.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.manytomany.dao.impl; - -import org.springframework.stereotype.Repository; - -import com.baeldung.manytomany.dao.IProjectDao; -import com.baeldung.manytomany.dao.common.AbstractHibernateDao; -import com.baeldung.manytomany.model.Project; - - -@Repository -public class ProjectDao extends AbstractHibernateDao implements IProjectDao { - - public ProjectDao() { - super(); - - setClazz(Project.class); - } -} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/util/HibernateUtil.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/util/HibernateUtil.java deleted file mode 100644 index d42956456467..000000000000 --- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/util/HibernateUtil.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.manytomany.util; - -import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; -import org.hibernate.service.ServiceRegistry; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.baeldung.manytomany.model.Employee; -import com.baeldung.manytomany.model.Project; - -public class HibernateUtil { - - private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class); - private static SessionFactory sessionFactory; - - private static SessionFactory buildSessionFactory() { - try { - // Create the SessionFactory from hibernate-annotation.cfg.xml - Configuration configuration = new Configuration(); - configuration.addAnnotatedClass(Employee.class); - configuration.addAnnotatedClass(Project.class); - configuration.configure("manytomany.cfg.xml"); - LOGGER.debug("Hibernate Annotation Configuration loaded"); - - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) - .build(); - LOGGER.debug("Hibernate Annotation serviceRegistry created"); - - SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); - - return sessionFactory; - } catch (Throwable ex) { - LOGGER.error("Initial SessionFactory creation failed.", ex); - throw new ExceptionInInitializerError(ex); - } - } - - public static SessionFactory getSessionFactory() { - if (sessionFactory == null) { - sessionFactory = buildSessionFactory(); - } - return sessionFactory; - } -} diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java index f1a6f675ce27..e1650dccd2cd 100644 --- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java @@ -6,7 +6,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.baeldung.manytomany.PersistenceConfig; +import com.baeldung.hibernate.manytomany.PersistenceConfig; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/booleanconverters/HibernateBooleanConverterIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/booleanconverters/HibernateBooleanConverterIntegrationTest.java new file mode 100644 index 000000000000..3235485e96a3 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/booleanconverters/HibernateBooleanConverterIntegrationTest.java @@ -0,0 +1,158 @@ +package com.baeldung.hibernate.booleanconverters; + +import static java.lang.String.format; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.UUID; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.booleanconverters.model.Question; + +public class HibernateBooleanConverterIntegrationTest { + + private static final String PROPERTY_FILE_NAME = "booleanconverters.cfg.xml"; + + private static SessionFactory sessionFactory; + private static Session session; + + @BeforeAll + static void createSessionFactory() { + sessionFactory = HibernateUtil.getSessionFactory(PROPERTY_FILE_NAME); + } + + @BeforeEach + void openSessionAndBeginTransaction() { + session = sessionFactory.openSession(); + } + + @AfterAll + static void closeSessionFactory() { + sessionFactory.close(); + } + + @Test + void whenFieldAnnotatedWithYesNoConverter_ThenConversionWorks() { + session.beginTransaction(); + UUID likeJavaQuestionId = UUID.randomUUID(); + UUID sydneyCapitalOfAustraliaQuestionId = UUID.randomUUID(); + session.persist(new QuestionBuilder().id(likeJavaQuestionId) + .content("Do you like Java?") + .correctAnswer(true) + .build()); + session.persist(new QuestionBuilder().id(sydneyCapitalOfAustraliaQuestionId) + .content("Is Sydney the capital of Australia?") + .correctAnswer(false) + .build()); + session.flush(); + + char likeJavaQuestionCorrectAnswerDbValue = session.createNativeQuery(format("SELECT correctAnswer FROM Question WHERE id='%s'", likeJavaQuestionId), Character.class) + .getSingleResult(); + char sydneyCapitalOfAustraliaQuestionCorrectAnswerDbValue = session.createNativeQuery(format("SELECT correctAnswer FROM Question WHERE id='%s'", sydneyCapitalOfAustraliaQuestionId), Character.class) + .getSingleResult(); + session.close(); + + assertEquals('Y', likeJavaQuestionCorrectAnswerDbValue); + assertEquals('N', sydneyCapitalOfAustraliaQuestionCorrectAnswerDbValue); + } + + @Test + void whenFieldAnnotatedWithTrueFalseConverter_ThenConversionWorks() { + session.beginTransaction(); + UUID codeTestedQuestionId = UUID.randomUUID(); + UUID earningsQuestionId = UUID.randomUUID(); + session.persist(new QuestionBuilder().id(codeTestedQuestionId) + .content("Is this code tested?") + .shouldBeAsked(true) + .build()); + session.persist(new QuestionBuilder().id(earningsQuestionId) + .content("How much do you earn?") + .shouldBeAsked(false) + .build()); + session.flush(); + + char codeTestedQuestionShouldBeAskedDbValue = session.createNativeQuery(format("SELECT shouldBeAsked FROM Question WHERE id='%s'", codeTestedQuestionId), Character.class) + .getSingleResult(); + char earningsQuestionsShouldBeAskedDbValue = session.createNativeQuery(format("SELECT shouldBeAsked FROM Question WHERE id='%s'", earningsQuestionId), Character.class) + .getSingleResult(); + session.close(); + + assertEquals('T', codeTestedQuestionShouldBeAskedDbValue); + assertEquals('F', earningsQuestionsShouldBeAskedDbValue); + } + + @Test + void whenFieldAnnotatedWithNumericBooleanConverter_ThenConversionWorks() { + session.beginTransaction(); + UUID earthFlatQuestionId = UUID.randomUUID(); + UUID shouldLearnProgrammingQuestionId = UUID.randomUUID(); + session.persist(new QuestionBuilder().id(earthFlatQuestionId) + .content("Is the Earth flat?") + .isEasy(true) + .build()); + session.persist(new QuestionBuilder().id(shouldLearnProgrammingQuestionId) + .content("Should one learn programming") + .isEasy(false) + .build()); + session.flush(); + + int earthFlatQuestionIsEasyDbValue = session.createNativeQuery(format("SELECT isEasy FROM Question WHERE id='%s'", earthFlatQuestionId), Integer.class) + .getSingleResult(); + int shouldLearnProgrammingQuestionIsEasyDbValue = session.createNativeQuery(format("SELECT isEasy FROM Question WHERE id='%s'", shouldLearnProgrammingQuestionId), Integer.class) + .getSingleResult(); + session.close(); + + assertEquals(1, earthFlatQuestionIsEasyDbValue); + assertEquals(0, shouldLearnProgrammingQuestionIsEasyDbValue); + } + + @Test + void givenFieldAnnotatedWithYesNoConverter_WhenDbValueIsLowercase_ThenDomainModelValueNull() { + session.beginTransaction(); + UUID mappedToNullQuestionId = UUID.randomUUID(); + UUID behaviorIntuitiveQuestionId = UUID.randomUUID(); + session.createNativeMutationQuery(format("INSERT INTO Question (id, content, correctAnswer) VALUES ('%s', 'Will correctAnswer be mapped to null?', 'y')", mappedToNullQuestionId)) + .executeUpdate(); + session.createNativeMutationQuery(format("INSERT INTO Question (id, content, correctAnswer) VALUES ('%s', 'Is this behavior intuitive?', 'n')", behaviorIntuitiveQuestionId)) + .executeUpdate(); + + Question behaviorIntuitiveQuestion = session.get(Question.class, behaviorIntuitiveQuestionId); + Question mappedToNullQuestion = session.get(Question.class, mappedToNullQuestionId); + session.close(); + + assertNull(behaviorIntuitiveQuestion.getCorrectAnswer()); + assertNull(mappedToNullQuestion.getCorrectAnswer()); + } + + @Test + void givenConverterRegisteredToAutoApply_whenFieldIsNotAnnotated_ThenConversionWorks() { + session.beginTransaction(); + UUID likeJavaQuestionId = UUID.randomUUID(); + UUID likeKotlinQuestionId = UUID.randomUUID(); + session.persist(new QuestionBuilder().id(likeJavaQuestionId) + .content("Do you like Java?") + .wasAskedBefore(true) + .build()); + session.persist(new QuestionBuilder().id(likeKotlinQuestionId) + .content("Do you like Kotlin?") + .wasAskedBefore(false) + .build()); + session.flush(); + + char likeJavaQuestionWasAskedBeforeDbValue = session.createNativeQuery(format("SELECT wasAskedBefore FROM Question WHERE id='%s'", likeJavaQuestionId), Character.class) + .getSingleResult(); + char likeKotlinQuestionWasAskedBeforeDbValue = session.createNativeQuery(format("SELECT wasAskedBefore FROM Question WHERE id='%s'", likeKotlinQuestionId), Character.class) + .getSingleResult(); + session.close(); + + assertEquals('Y', likeJavaQuestionWasAskedBeforeDbValue); + assertEquals('N', likeKotlinQuestionWasAskedBeforeDbValue); + } +} diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/booleanconverters/QuestionBuilder.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/booleanconverters/QuestionBuilder.java new file mode 100644 index 000000000000..26fe38c3c857 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/booleanconverters/QuestionBuilder.java @@ -0,0 +1,48 @@ +package com.baeldung.hibernate.booleanconverters; + +import java.util.UUID; + +import com.baeldung.hibernate.booleanconverters.model.Question; + +public class QuestionBuilder { + private UUID id; + private String content; + private Boolean correctAnswer; + private Boolean shouldBeAsked; + private Boolean isEasy; + private Boolean wasAskedBefore; + + public QuestionBuilder id(UUID id) { + this.id = id; + return this; + } + + public QuestionBuilder content(String content) { + this.content = content; + return this; + } + + public QuestionBuilder correctAnswer(Boolean correctAnswer) { + this.correctAnswer = correctAnswer; + return this; + } + + public QuestionBuilder shouldBeAsked(Boolean shouldBeAsked) { + this.shouldBeAsked = shouldBeAsked; + return this; + } + + public QuestionBuilder isEasy(Boolean isEasy) { + this.isEasy = isEasy; + return this; + } + + public QuestionBuilder wasAskedBefore(Boolean wasAskedBefore) { + this.wasAskedBefore = wasAskedBefore; + return this; + } + + public Question build() { + return new Question(id, content, correctAnswer, shouldBeAsked, isEasy, wasAskedBefore); + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java index 69b791b4d4dd..e4fcafcb56ab 100644 --- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java @@ -13,9 +13,9 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.baeldung.manytomany.PersistenceConfig; -import com.baeldung.manytomany.model.Employee; -import com.baeldung.manytomany.model.Project; + +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.model.Project; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java index 5255cb040f97..7c6861e63bbd 100644 --- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java @@ -15,9 +15,9 @@ import org.junit.BeforeClass; import org.junit.Test; -import com.baeldung.manytomany.model.Employee; -import com.baeldung.manytomany.model.Project; -import com.baeldung.manytomany.util.HibernateUtil; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.model.Project; +import com.baeldung.hibernate.HibernateUtil; /** * Configured in: manytomany.cfg.xml diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/uuids/UUIDsHibernateGenerationIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/uuids/UUIDsHibernateGenerationIntegrationTest.java new file mode 100644 index 000000000000..f36a4333c3b3 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/uuids/UUIDsHibernateGenerationIntegrationTest.java @@ -0,0 +1,72 @@ +package com.baeldung.hibernate.uuids; + +import com.baeldung.hibernate.HibernateUtil; + +import org.assertj.core.api.Assertions; +import java.io.IOException; + +import org.hibernate.SessionFactory; +import org.hibernate.Session; +import org.junit.Before; +import org.junit.Test; +import java.util.UUID; +import java.time.LocalDate; + +public class UUIDsHibernateGenerationIntegrationTest { + + private SessionFactory sessionFactory; + + private Session session; + + @Before + public void setUp() throws IOException { + sessionFactory = HibernateUtil.getSessionFactory(); + session = sessionFactory.openSession(); + } + + @Test + public void whenGeneratingUUIDUsingNewJPAGenerationType_thenHibernateGeneratedUUID() throws IOException { + Reservation reservation = new Reservation(); + reservation.setStatus("created"); + reservation.setNumber("12345"); + UUID saved = (UUID) session.save(reservation); + Assertions.assertThat(saved).isNotNull(); + } + + @Test + public void whenGeneratingUUIDUsingNewJPAGenerationType_thenHibernateGeneratedUUIDOfVersion4() throws IOException { + Reservation reservation = new Reservation(); + reservation.setStatus("new"); + reservation.setNumber("012"); + UUID saved = (UUID) session.save(reservation); + Assertions.assertThat(saved).isNotNull(); + Assertions.assertThat(saved.version()).isEqualTo(4); + } + + @Test + public void whenGeneratingUUIDUsingGenericConverter_thenAlsoGetUUIDGeneratedVersion4() throws IOException { + Sale sale = new Sale(); + sale.setCompleted(true); + UUID saved = (UUID) session.save(sale); + Assertions.assertThat(saved).isNotNull(); + Assertions.assertThat(saved.version()).isEqualTo(4); + } + + @Test + public void whenGeneratingTimeBasedUUID_thenUUIDGeneratedVersion1() throws IOException { + WebSiteUser user = new WebSiteUser(); + user.setRegistrationDate(LocalDate.now()); + UUID saved = (UUID) session.save(user); + Assertions.assertThat(saved).isNotNull(); + Assertions.assertThat(saved.version()).isEqualTo(1); + } + + @Test + public void whenGeneratingUUIDAsString_thenUUIDGeneratedVersion1() throws IOException { + Element element = new Element(); + element.setName("a"); + String saved = (String) session.save(element); + Assertions.assertThat(saved).isNotEmpty(); + Assertions.assertThat(UUID.fromString(saved).version()).isEqualTo(4); + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping-2/src/test/resources/booleanconverters.cfg.xml b/persistence-modules/hibernate-mapping-2/src/test/resources/booleanconverters.cfg.xml new file mode 100644 index 000000000000..6ca479b05266 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/test/resources/booleanconverters.cfg.xml @@ -0,0 +1,16 @@ + + + + + org.h2.Driver + + jdbc:h2:mem:booleanconvertersdb;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/test/resources/booleanconverters/init_database.sql' + sa + org.hibernate.dialect.H2Dialect + thread + false + none + + \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping-2/src/test/resources/booleanconverters/init_database.sql b/persistence-modules/hibernate-mapping-2/src/test/resources/booleanconverters/init_database.sql new file mode 100644 index 000000000000..cb0f4f329ce4 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/test/resources/booleanconverters/init_database.sql @@ -0,0 +1,9 @@ +CREATE TABLE Question ( + id UUID, + content VARCHAR, + correctAnswer CHAR, + shouldBeAsked CHAR, + isEasy TINYINT, + wasAskedBefore CHAR, + PRIMARY KEY (id) +) diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index 506283a4fb75..1e3dc8be5f8b 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -26,7 +26,7 @@ com.vladmihalcea - hibernate-types-52 + hibernate-types-60 ${hibernate-types.version} @@ -41,9 +41,9 @@ ${hibernate-validator.version} - org.glassfish - javax.el - ${org.glassfish.javax.el.version} + org.glassfish.expressly + expressly + 5.0.0 javax.money @@ -66,16 +66,27 @@ commons-io ${commons-io.version} + + com.fasterxml.jackson.module + jackson-module-jakarta-xmlbind-annotations + ${jackson-module-jakarta-xmlbind-annotation} + + + org.openjdk.nashorn + nashorn-core + 15.4 + - 1.4.197 - 5.4.12.Final - 2.10.4 - 6.0.16.Final + 2.1.214 + 6.1.7.Final + 2.21.1 + 8.0.0.Final 3.0.1-b11 - 1.0.3 - 1.3 + 1.1 + 1.4.2 + 2.14.2 \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java index fbd8bd487bfb..cbd73832a4e9 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -21,6 +21,7 @@ import com.baeldung.hibernate.pojo.inheritance.Bag; import com.baeldung.hibernate.pojo.inheritance.Book; import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.Laptop; import com.baeldung.hibernate.pojo.inheritance.MyEmployee; import com.baeldung.hibernate.pojo.inheritance.MyProduct; import com.baeldung.hibernate.pojo.inheritance.Pen; @@ -79,6 +80,7 @@ private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); metadataSources.addAnnotatedClass(Animal.class); metadataSources.addAnnotatedClass(Bag.class); + metadataSources.addAnnotatedClass(Laptop.class); metadataSources.addAnnotatedClass(Book.class); metadataSources.addAnnotatedClass(Car.class); metadataSources.addAnnotatedClass(MyEmployee.class); @@ -86,7 +88,6 @@ private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry metadataSources.addAnnotatedClass(Pen.class); metadataSources.addAnnotatedClass(Pet.class); metadataSources.addAnnotatedClass(Vehicle.class); - Metadata metadata = metadataSources.getMetadataBuilder() .build(); diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomIntegerArrayType.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomIntegerArrayType.java index 233bb95dc156..5d3e22bf05be 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomIntegerArrayType.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomIntegerArrayType.java @@ -8,58 +8,56 @@ import java.sql.Types; import java.util.Arrays; -import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.usertype.UserType; -public class CustomIntegerArrayType implements UserType { +public class CustomIntegerArrayType implements UserType { @Override - public int[] sqlTypes() { - return new int[]{Types.ARRAY}; + public int getSqlType() { + return Types.ARRAY; } @Override - public Class returnedClass() { + public Class returnedClass() { return Integer[].class; } @Override - public boolean equals(Object x, Object y) throws HibernateException { + public boolean equals(Integer[] x, Integer[] y) { if (x instanceof Integer[] && y instanceof Integer[]) { - return Arrays.deepEquals((Integer[])x, (Integer[])y); + return Arrays.deepEquals(x, y); } else { return false; } } @Override - public int hashCode(Object x) throws HibernateException { - return Arrays.hashCode((Integer[])x); + public int hashCode(Integer[] x) { + return Arrays.hashCode(x); } @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) - throws HibernateException, SQLException { - Array array = rs.getArray(names[0]); - return array != null ? array.getArray() : null; + public Integer[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { + Array array = rs.getArray(position); + return array != null ? (Integer[]) array.getArray() : null; } @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) - throws HibernateException, SQLException { - if (value != null && st != null) { - Array array = session.connection().createArrayOf("int", (Integer[])value); - st.setArray(index, array); - } else { - st.setNull(index, sqlTypes()[0]); + public void nullSafeSet(PreparedStatement st, Integer[] value, int index, SharedSessionContractImplementor session) throws SQLException { + if (st != null) { + if (value != null) { + Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("int", value); + st.setArray(index, array); + } else { + st.setNull(index, Types.ARRAY); + } } } @Override - public Object deepCopy(Object value) throws HibernateException { - Integer[] a = (Integer[])value; - return Arrays.copyOf(a, a.length); + public Integer[] deepCopy(Integer[] value) { + return value != null ? Arrays.copyOf(value, value.length) : null; } @Override @@ -68,18 +66,18 @@ public boolean isMutable() { } @Override - public Serializable disassemble(Object value) throws HibernateException { - return (Serializable) value; + public Serializable disassemble(Integer[] value) { + return value; } @Override - public Object assemble(Serializable cached, Object owner) throws HibernateException { - return cached; + public Integer[] assemble(Serializable cached, Object owner) { + return (Integer[]) cached; } @Override - public Object replace(Object original, Object target, Object owner) throws HibernateException { - return original; + public Integer[] replace(Integer[] detached, Integer[] managed, Object owner) { + return detached; } } diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomStringArrayType.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomStringArrayType.java index 7bd284def753..31a082fb052c 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomStringArrayType.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomStringArrayType.java @@ -8,58 +8,56 @@ import java.sql.Types; import java.util.Arrays; -import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.usertype.UserType; -public class CustomStringArrayType implements UserType { +public class CustomStringArrayType implements UserType { @Override - public int[] sqlTypes() { - return new int[]{Types.ARRAY}; + public int getSqlType() { + return Types.ARRAY; } @Override - public Class returnedClass() { + public Class returnedClass() { return String[].class; } @Override - public boolean equals(Object x, Object y) throws HibernateException { + public boolean equals(String[] x, String[] y) { if (x instanceof String[] && y instanceof String[]) { - return Arrays.deepEquals((String[])x, (String[])y); + return Arrays.deepEquals(x, y); } else { return false; } } @Override - public int hashCode(Object x) throws HibernateException { - return Arrays.hashCode((String[])x); + public int hashCode(String[] x) { + return Arrays.hashCode(x); } @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) - throws HibernateException, SQLException { - Array array = rs.getArray(names[0]); - return array != null ? array.getArray() : null; + public String[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { + Array array = rs.getArray(position); + return array != null ? (String[]) array.getArray() : null; } @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) - throws HibernateException, SQLException { - if (value != null && st != null) { - Array array = session.connection().createArrayOf("text", (String[])value); - st.setArray(index, array); - } else { - st.setNull(index, sqlTypes()[0]); + public void nullSafeSet(PreparedStatement st, String[] value, int index, SharedSessionContractImplementor session) throws SQLException { + if (st != null) { + if (value != null) { + Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("text", value); + st.setArray(index, array); + } else { + st.setNull(index, Types.ARRAY); + } } } @Override - public Object deepCopy(Object value) throws HibernateException { - String[] a = (String[])value; - return Arrays.copyOf(a, a.length); + public String[] deepCopy(String[] value) { + return value != null ? Arrays.copyOf(value, value.length) : null; } @Override @@ -68,18 +66,18 @@ public boolean isMutable() { } @Override - public Serializable disassemble(Object value) throws HibernateException { - return (Serializable) value; + public Serializable disassemble(String[] value) { + return value; } @Override - public Object assemble(Serializable cached, Object owner) throws HibernateException { - return cached; + public String[] assemble(Serializable cached, Object owner) { + return (String[]) cached; } @Override - public Object replace(Object original, Object target, Object owner) throws HibernateException { - return original; + public String[] replace(String[] detached, String[] managed, Object owner) { + return detached; } } diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/User.java index 018bedc34905..81f2ee89f756 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/User.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/User.java @@ -1,21 +1,13 @@ package com.baeldung.hibernate.arraymapping; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; import org.hibernate.annotations.Type; import com.vladmihalcea.hibernate.type.array.StringArrayType; -import org.hibernate.annotations.*; - -@TypeDefs({ - @TypeDef( - name = "string-array", - typeClass = StringArrayType.class - ) -}) @Entity public class User { @@ -25,14 +17,14 @@ public class User { private String name; @Column(columnDefinition = "text[]") - @Type(type = "com.baeldung.hibernate.arraymapping.CustomStringArrayType") + @Type(value = com.baeldung.hibernate.arraymapping.CustomStringArrayType.class) private String[] roles; @Column(columnDefinition = "int[]") - @Type(type = "com.baeldung.hibernate.arraymapping.CustomIntegerArrayType") + @Type(value = com.baeldung.hibernate.arraymapping.CustomIntegerArrayType.class) private Integer[] locations; - @Type(type = "string-array") + @Type(StringArrayType.class) @Column( name = "phone_numbers", columnDefinition = "text[]" diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/basicannotation/Course.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/basicannotation/Course.java index e816fb0176fe..ca77888f9b6f 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/basicannotation/Course.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/basicannotation/Course.java @@ -1,10 +1,9 @@ package com.baeldung.hibernate.basicannotation; -import javax.persistence.Basic; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Basic; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; @Entity public class Course { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java index ff94f4f849a1..39e69a2b1c0f 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -2,7 +2,7 @@ import java.util.List; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class Department { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java index 6510e706503e..3c4f542ce714 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.entities; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; @org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), - @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where employeeNumber = :designation"), @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) @org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java index 5589601da8ea..b8937c66923c 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java @@ -3,10 +3,10 @@ import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; import java.util.HashSet; import java.util.Set; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java index aa9c51732142..5be65bac0de8 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.fetchMode; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class Order { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java index 21f725b3885e..3c3b748990cc 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.lob.model; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Lob; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Lob; +import jakarta.persistence.Table; @Entity -@Table(name="user") +@Table(name="users") public class User { @Id diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Item.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Item.java index 385ffe93eac4..ff8115f5d900 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Item.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Item.java @@ -2,15 +2,15 @@ import com.baeldung.hibernate.persistmaps.ItemType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; import java.util.Date; import java.util.Objects; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Order.java index 8409cacd6bd9..e42ceda5defb 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Order.java @@ -1,15 +1,15 @@ package com.baeldung.hibernate.persistmaps.mapkey; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.MapKey; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.MapKey; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; import java.util.Map; @Entity diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java index b2ee7e85fe5e..0a9694f43cbe 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java @@ -1,16 +1,15 @@ package com.baeldung.hibernate.persistmaps.mapkey; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.validation.constraints.Size; -import javax.money.MonetaryAmount; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.Size; import org.hibernate.validator.constraints.Length; -import org.hibernate.validator.constraints.CreditCardNumber; -import org.hibernate.validator.constraints.Currency; @Entity +@Table(name="users2") public class User { @Id @Column(length = 3) diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeycolumn/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeycolumn/Order.java index fa092060dae7..3d24c743d780 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeycolumn/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeycolumn/Order.java @@ -1,14 +1,14 @@ package com.baeldung.hibernate.persistmaps.mapkeycolumn; -import javax.persistence.CollectionTable; -import javax.persistence.Column; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.MapKeyColumn; -import javax.persistence.Table; +import jakarta.persistence.CollectionTable; +import jakarta.persistence.Column; +import jakarta.persistence.ElementCollection; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.MapKeyColumn; +import jakarta.persistence.Table; import java.util.Map; @Entity diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyenumerated/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyenumerated/Order.java index e1f62599b80b..19622ea01dc1 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyenumerated/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyenumerated/Order.java @@ -3,17 +3,17 @@ import com.baeldung.hibernate.persistmaps.ItemType; import com.baeldung.hibernate.persistmaps.mapkey.Item; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.MapKeyEnumerated; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.MapKeyEnumerated; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; import java.util.Map; @Entity diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Item.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Item.java index 97bbd5b53929..9ed58305dad9 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Item.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Item.java @@ -2,18 +2,18 @@ import com.baeldung.hibernate.persistmaps.ItemType; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; import java.util.Date; import java.util.Objects; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Order.java index d680d8450188..9d20237860b5 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Order.java @@ -1,15 +1,15 @@ package com.baeldung.hibernate.persistmaps.mapkeyjoincolumn; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.MapKeyJoinColumn; -import javax.persistence.OneToMany; -import javax.persistence.Table; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.MapKeyJoinColumn; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; import java.util.Map; @Entity diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Seller.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Seller.java index 15b08e9fe63e..ca06db241ec6 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Seller.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Seller.java @@ -1,10 +1,10 @@ package com.baeldung.hibernate.persistmaps.mapkeyjoincolumn; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import java.util.Objects; @Entity diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeytemporal/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeytemporal/Order.java index be602c1e9fbf..920d693d1681 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeytemporal/Order.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeytemporal/Order.java @@ -2,17 +2,17 @@ import com.baeldung.hibernate.persistmaps.mapkey.Item; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.MapKeyTemporal; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.persistence.TemporalType; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.MapKeyTemporal; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import jakarta.persistence.TemporalType; import java.util.Date; import java.util.Map; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java index e9732b2b67cb..7d8a254eec1b 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java @@ -2,15 +2,15 @@ import org.hibernate.annotations.*; -import javax.persistence.Entity; -import javax.persistence.*; +import jakarta.persistence.Entity; +import jakarta.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; @Entity @Where(clause = "deleted = false") -@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int")) +@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = Integer.class)) @Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit") public class Employee implements Serializable { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java index 131bb73a8006..29befd80f2ba 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java @@ -1,8 +1,11 @@ package com.baeldung.hibernate.pojo; import org.hibernate.annotations.Any; +import org.hibernate.annotations.AnyDiscriminator; +import org.hibernate.annotations.AnyDiscriminatorValue; +import org.hibernate.annotations.AnyKeyJavaClass; -import javax.persistence.*; +import jakarta.persistence.*; import java.io.Serializable; @Entity @@ -14,10 +17,12 @@ public class EntityDescription implements Serializable { private String description; - @Any( - metaDef = "EntityDescriptionMetaDef", - metaColumn = @Column(name = "entity_type") - ) + @Any + @AnyDiscriminator(DiscriminatorType.STRING) + @AnyDiscriminatorValue(discriminator = "S", entity = Employee.class) + @AnyDiscriminatorValue(discriminator = "I", entity = Phone.class) + @AnyKeyJavaClass(Integer.class) + @Column(name = "entity_type") @JoinColumn(name = "entity_id") private Serializable entity; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java index d923bda5de50..e173aa8b470b 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; import java.io.Serializable; @Entity diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java index f3fe095cae94..0c022884eb1d 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java @@ -1,7 +1,6 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.*; -import java.io.Serializable; +import jakarta.persistence.*; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; @@ -9,7 +8,7 @@ import java.util.Calendar; @Entity -public class TemporalValues implements Serializable { +public class TemporalValues { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -48,7 +47,7 @@ public class TemporalValues implements Serializable { private java.time.LocalDate localDate; @Basic - private java.time.LocalTime localTime; + private java.time.LocalTime localTimeField; @Basic private java.time.OffsetTime offsetTime; @@ -146,11 +145,11 @@ public void setLocalDate(LocalDate localDate) { } public LocalTime getLocalTime() { - return localTime; + return localTimeField; } public void setLocalTime(LocalTime localTime) { - this.localTime = localTime; + this.localTimeField = localTime; } public OffsetTime getOffsetTime() { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java index 6fe7f915fc9f..c44a542b6041 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; @Entity @Inheritance(strategy = InheritanceType.JOINED) diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java index fa6e1b4befa6..707e38786675 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; import org.hibernate.annotations.Polymorphism; import org.hibernate.annotations.PolymorphismType; diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java index 36ca8dd77cc1..286a30cc149d 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; +import jakarta.persistence.DiscriminatorValue; +import jakarta.persistence.Entity; @Entity @DiscriminatorValue("1") diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java index 49d1f7749a63..987e299625be 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Entity; +import jakarta.persistence.Entity; @Entity public class Car extends Vehicle { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Laptop.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Laptop.java new file mode 100644 index 000000000000..cced365d78a2 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Laptop.java @@ -0,0 +1,39 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import org.hibernate.annotations.Polymorphism; +import org.hibernate.annotations.PolymorphismType; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +@Entity +@Polymorphism(type = PolymorphismType.IMPLICIT) +public class Laptop implements Item { + + @Id + private Long id; + + private String type; + + public Laptop(Long id, String type) { + this.id = id; + this.type = type; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java index 9a6bce16cf5f..96958c6e28ad 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java @@ -1,6 +1,6 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Entity; +import jakarta.persistence.Entity; @Entity public class MyEmployee extends Person { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java index 13f04d8904d7..62214fc16eac 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java @@ -1,13 +1,11 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; - -import org.hibernate.annotations.DiscriminatorFormula; +import jakarta.persistence.DiscriminatorColumn; +import jakarta.persistence.DiscriminatorType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java index 32b77e52af5f..2382cab40590 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; +import jakarta.persistence.DiscriminatorValue; +import jakarta.persistence.Entity; @Entity @DiscriminatorValue("2") diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java index 99084b88af6e..9bf8ac254c6d 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Id; -import javax.persistence.MappedSuperclass; +import jakarta.persistence.Id; +import jakarta.persistence.MappedSuperclass; @MappedSuperclass public class Person { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java index 870b3cd68498..b359eb3a21e0 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Entity; -import javax.persistence.PrimaryKeyJoinColumn; +import jakarta.persistence.Entity; +import jakarta.persistence.PrimaryKeyJoinColumn; @Entity @PrimaryKeyJoinColumn(name = "petId") diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java index b2a920573e02..9bdde8c33bed 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo.inheritance; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; @Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java deleted file mode 100644 index 992cda7c1d70..000000000000 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int", - metaValues = { - @MetaValue(value = "Employee", targetEntity = Employee.class), - @MetaValue(value = "Phone", targetEntity = Phone.class) - }) -package com.baeldung.hibernate.pojo; - -import org.hibernate.annotations.AnyMetaDef; -import org.hibernate.annotations.MetaValue; \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java index 7a112200b59b..833c5cc3ffbf 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java @@ -119,8 +119,8 @@ public void givenFilterByIncome_whenIncomeLimitSet_thenFilterIsApplied() throws assertThat(employees).hasSize(2); - Employee employee = session.get(Employee.class, 1); - assertThat(employee.getGrossIncome()).isEqualTo(10_000); + Employee employee = session.get(Employee.class, 2); + assertThat(employee.getGrossIncome()).isEqualTo(12_000); session.disableFilter("incomeLevelFilter"); employees = session.createQuery("from Employee").getResultList(); diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java index 0f35dbb8af51..7f4cac141c96 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java @@ -13,6 +13,7 @@ import com.baeldung.hibernate.pojo.inheritance.Bag; import com.baeldung.hibernate.pojo.inheritance.Book; import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.Laptop; import com.baeldung.hibernate.pojo.inheritance.MyEmployee; import com.baeldung.hibernate.pojo.inheritance.Pen; import com.baeldung.hibernate.pojo.inheritance.Pet; @@ -81,9 +82,12 @@ public void givenSubclasses_whenQueryTablePerClassSuperclass_thenOk() { public void givenSubclasses_whenQueryNonMappedInterface_thenOk() { Bag bag = new Bag(1, "large"); session.save(bag); + + Laptop laptop = new Laptop(1L, "Dell"); + session.save(laptop); assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Item") .getResultList() - .size()).isEqualTo(0); + .size()).isEqualTo(1); } } diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java index 930bea60c55f..6a9a4f095b34 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java @@ -2,7 +2,7 @@ import java.io.IOException; -import javax.persistence.PersistenceException; +import jakarta.persistence.PersistenceException; import org.hibernate.Session; import org.hibernate.SessionFactory; diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java index 0f2a0403e907..17212173ec5e 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java @@ -7,13 +7,12 @@ import java.time.Duration; import java.util.Set; -import javax.money.CurrencyContextBuilder; import javax.money.Monetary; import javax.money.MonetaryAmount; -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.hibernate.validator.constraints.CodePointLength; import org.hibernate.validator.constraints.CreditCardNumber; @@ -21,12 +20,10 @@ import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.LuhnCheck; import org.hibernate.validator.constraints.Range; -import org.hibernate.validator.constraints.SafeHtml; import org.hibernate.validator.constraints.ScriptAssert; import org.hibernate.validator.constraints.URL; import org.hibernate.validator.constraints.time.DurationMax; import org.hibernate.validator.constraints.time.DurationMin; -import org.javamoney.moneta.CurrencyUnitBuilder; import org.javamoney.moneta.Money; import org.junit.BeforeClass; import org.junit.Test; diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserValidationUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserValidationUnitTest.java index e39f324856e5..495ad657be02 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserValidationUnitTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserValidationUnitTest.java @@ -2,11 +2,11 @@ import static org.junit.Assert.assertEquals; import java.util.Set; -import javax.persistence.PersistenceException; -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; +import jakarta.persistence.PersistenceException; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorFactory; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.Before; diff --git a/persistence-modules/hibernate-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml index 68a46b82b1f6..bb60c7b83a29 100644 --- a/persistence-modules/hibernate-queries/pom.xml +++ b/persistence-modules/hibernate-queries/pom.xml @@ -85,15 +85,21 @@ ${testcontainers.mysql.version} test + + io.hypersistence + hypersistence-utils-hibernate-60 + 3.3.1 + - 5.0.2.RELEASE - 1.10.6.RELEASE + 6.0.6 + 3.0.3 9.0.0.M26 - 6.0.6 - 2.2.3 + 8.0.32 + 2.6.0 2.1.214 + 6.1.7.Final 1.17.6 diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java index 8771e02e0b87..9041c6727c05 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java @@ -1,7 +1,7 @@ package com.baeldung.hibernate.criteria.model; import java.io.Serializable; -import javax.persistence.Entity; +import jakarta.persistence.Entity; @org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "Employee_findByEmployeeId", query = "from Employee where id = :employeeId"), diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java index 248f64474a7c..2b782c2a1d70 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java @@ -12,10 +12,10 @@ import java.util.List; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.hibernate.Session; import org.hibernate.query.Query; diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java index f8c525611bd5..9303fd893e60 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java @@ -3,9 +3,9 @@ import com.baeldung.hibernate.criteria.model.Employee; import com.baeldung.hibernate.criteria.util.HibernateUtil; import java.util.List; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.hibernate.Session; import org.hibernate.query.Query; diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java index 314e7ca557be..af6b561091f0 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java @@ -1,11 +1,11 @@ package com.baeldung.hibernate.criteriaquery; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "students") diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java index 56be9e693f54..58d8e8628a82 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java @@ -1,14 +1,15 @@ package com.baeldung.hibernate.customtypes; -import org.hibernate.type.LocalDateType; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; -import org.hibernate.type.descriptor.java.MutabilityPlan; -import java.time.LocalDate; +import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayTypeDescriptor; -public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor { +public class LocalDateStringJavaDescriptor extends AbstractArrayTypeDescriptor { public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor(); @@ -18,12 +19,12 @@ public LocalDateStringJavaDescriptor() { @Override public String toString(LocalDate value) { - return LocalDateType.FORMATTER.format(value); + return DateTimeFormatter.ISO_LOCAL_DATE.format(value); } @Override - public LocalDate fromString(String string) { - return LocalDate.from(LocalDateType.FORMATTER.parse(string)); + public LocalDate fromString(CharSequence string) { + return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse(string)); } @Override @@ -33,7 +34,7 @@ public X unwrap(LocalDate value, Class type, WrapperOptions options) { return null; if (String.class.isAssignableFrom(type)) - return (X) LocalDateType.FORMATTER.format(value); + return (X) DateTimeFormatter.ISO_LOCAL_DATE.format(value); throw unknownUnwrap(type); } @@ -43,8 +44,8 @@ public LocalDate wrap(X value, WrapperOptions options) { if (value == null) return null; - if(String.class.isInstance(value)) - return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value)); + if(value instanceof String) + return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse((CharSequence) value)); throw unknownWrap(value.getClass()); } diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java index c8d37073e896..57a8bcfd08bd 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java @@ -2,18 +2,16 @@ import org.hibernate.dialect.Dialect; import org.hibernate.type.AbstractSingleColumnStandardBasicType; -import org.hibernate.type.DiscriminatorType; -import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor; -import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; +import org.hibernate.type.descriptor.jdbc.VarcharJdbcType; import java.time.LocalDate; -public class LocalDateStringType extends AbstractSingleColumnStandardBasicType implements DiscriminatorType { +public class LocalDateStringType extends AbstractSingleColumnStandardBasicType { public static final LocalDateStringType INSTANCE = new LocalDateStringType(); public LocalDateStringType() { - super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); + super(VarcharJdbcType.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); } @Override @@ -21,14 +19,12 @@ public String getName() { return "LocalDateString"; } - @Override - public LocalDate stringToObject(String xml) throws Exception { + public LocalDate stringToObject(String xml) { return fromString(xml); } - @Override - public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception { - return '\'' + toString(value) + '\''; + public String objectToSQLString(LocalDate value, Dialect dialect) { + return '\'' + LocalDateStringJavaDescriptor.INSTANCE.toString(value) + '\''; } } diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Comment.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Comment.java index 1d155b112eeb..0dd2451d4e75 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Comment.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Comment.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.distinct.entities; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Comment { diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Post.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Post.java index d2608e614cec..6bd21d18400f 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Post.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/distinct/entities/Post.java @@ -2,12 +2,11 @@ import java.util.List; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java index ff94f4f849a1..39e69a2b1c0f 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -2,7 +2,7 @@ import java.util.List; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class Department { diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java index 6510e706503e..38519644c5d8 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -1,13 +1,13 @@ package com.baeldung.hibernate.entities; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; @org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), - @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where employeeNumber = :employeeNumber"), @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) @org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java index cc0c234df046..dc2cb884c702 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java @@ -2,10 +2,10 @@ import java.util.List; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.hibernate.Session; diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/BrokenPhoneOrder.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/BrokenPhoneOrder.java index e045005f2861..f10618b76e0a 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/BrokenPhoneOrder.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/BrokenPhoneOrder.java @@ -2,10 +2,10 @@ import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "broken_phone_order") diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/PhoneOrder.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/PhoneOrder.java index daee57d55360..652fd493495b 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/PhoneOrder.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/PhoneOrder.java @@ -2,10 +2,10 @@ import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "phone_order") diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java index 9b26c117ebe1..263908a5fccb 100644 --- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -1,9 +1,9 @@ package com.baeldung.hibernate.pojo; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Student { diff --git a/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml index 474eeb7a4405..291512529528 100644 --- a/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml @@ -7,12 +7,12 @@ Hibernate EntityManager Demo true - + - - - - + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index a1f88f33875d..c405eb9ebdb4 100644 --- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -15,10 +15,10 @@ import com.baeldung.hibernate.criteria.util.HibernateUtil; import com.baeldung.hibernate.criteria.view.ApplicationView; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaDelete; -import javax.persistence.criteria.CriteriaUpdate; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaDelete; +import jakarta.persistence.criteria.CriteriaUpdate; +import jakarta.persistence.criteria.Root; public class HibernateCriteriaIntegrationTest { diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java index cedba412d9a9..bfcb4301a7a5 100644 --- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.hibernate.criteriaquery; -import com.baeldung.hibernate.criteriaquery.HibernateUtil; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; @@ -10,9 +9,9 @@ import org.junit.BeforeClass; import org.junit.Test; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import java.io.IOException; import java.util.List; diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java index 799439a51bb1..3ce384741f00 100644 --- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java @@ -8,7 +8,6 @@ import org.hibernate.Session; import org.hibernate.Transaction; -import org.hibernate.annotations.QueryHints; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -45,12 +44,12 @@ public void tearDown() { } @Test - public void whenExecutingSelectQuery_thereWillBeDuplicates() { + public void whenExecutingSelectQuery_thereTheInsertedPosts() { String hql = "SELECT p FROM Post p LEFT JOIN FETCH p.comments"; List posts = session.createQuery(hql, Post.class) .getResultList(); - assertThat(posts).hasSize(3); + assertThat(posts).hasSize(1); } @Test @@ -68,8 +67,8 @@ public void whenExecutingSelectDistinctQuery_thereShouldBeNoDuplicates() { @Test public void whenExecutingSelectDistinctQueryWithHint_thereShouldBeNoDuplicates() { String hql = "SELECT DISTINCT p FROM Post p LEFT JOIN FETCH p.comments"; + // From Hibernate ORM 6, distinct is always passed to the SQL query and the flag QueryHints#HINT_PASS_DISTINCT_THROUGH has been removed. List posts = session.createQuery(hql, Post.class) - .setHint(QueryHints.PASS_DISTINCT_THROUGH, false) .getResultList(); assertThat(posts).hasSize(1) diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationManualTest.java similarity index 78% rename from persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationIntegrationTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationManualTest.java index 4282da3de4ba..780a0fd77e8b 100644 --- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationIntegrationTest.java +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationManualTest.java @@ -3,8 +3,6 @@ import static java.util.UUID.randomUUID; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import javax.persistence.PersistenceException; - import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; @@ -13,7 +11,17 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class HibernateKeywordsApplicationIntegrationTest { +import jakarta.persistence.PersistenceException; + +/** + * This test suite uses testcontainers library and therefore + * requires Docker installed on the local system to be able to run it. + * + * When docker is available on the local machine it can be run either by: + * - running it from your favorite IDE + * - or through `mvn test -Dtest=HibernateKeywordsApplicationManualTest` + */ +public class HibernateKeywordsApplicationManualTest { private static SessionFactory sessionFactory; private Session session; diff --git a/persistence-modules/java-jpa-2/pom.xml b/persistence-modules/java-jpa-2/pom.xml index b736b50dd1b3..34e7f9f349ce 100644 --- a/persistence-modules/java-jpa-2/pom.xml +++ b/persistence-modules/java-jpa-2/pom.xml @@ -14,32 +14,44 @@ - org.hibernate + org.hibernate.orm hibernate-core ${hibernate.version} + + + jakarta.xml.bind + jakarta.xml.bind-api + + - org.hibernate + org.hibernate.orm hibernate-jpamodelgen ${hibernate.version} + + + jakarta.xml.bind + jakarta.xml.bind-api + + com.h2database h2 ${h2.version} - - - javax.persistence - javax.persistence-api - ${javax.persistence-api.version} - org.eclipse.persistence eclipselink ${eclipselink.version} runtime + + + jakarta.xml.bind + jakarta.xml.bind-api + + org.postgresql @@ -51,13 +63,25 @@ com.querydsl querydsl-apt ${querydsl.version} + jakarta provided com.querydsl querydsl-jpa + jakarta ${querydsl.version} + + jakarta.xml.bind + jakarta.xml.bind-api + ${jakarta.xml.bind-api.version} + + + javax.annotation + javax.annotation-api + ${javax.annotation.version} + @@ -130,14 +154,15 @@ - 5.4.14.Final - 2.7.4 + 4.0.1 2.2 3.5.1 3.3.3 3.0.0 - 4.3.1 + 5.0.0 1.4.200 + 4.0.0 + 1.3.2 \ No newline at end of file diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/criteria/CustomItemRepositoryImpl.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/criteria/CustomItemRepositoryImpl.java index c64cd14ca54b..a014217b880c 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/criteria/CustomItemRepositoryImpl.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/criteria/CustomItemRepositoryImpl.java @@ -2,13 +2,13 @@ import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; public class CustomItemRepositoryImpl implements CustomItemRepository { diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/criteria/Item.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/criteria/Item.java index f6093e5735ef..3662d4918b68 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/criteria/Item.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/criteria/Item.java @@ -1,8 +1,8 @@ package com.baeldung.jpa.criteria; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Table(name = "item") @Entity diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/defaultvalues/User.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/defaultvalues/User.java index 436c708d4060..b89432c051bc 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/defaultvalues/User.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/defaultvalues/User.java @@ -1,11 +1,10 @@ package com.baeldung.jpa.defaultvalues; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; -@Entity +@Entity(name = "users") public class User { @Id diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/defaultvalues/UserRepository.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/defaultvalues/UserRepository.java index 52f9807cfbea..7639dc74c535 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/defaultvalues/UserRepository.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/defaultvalues/UserRepository.java @@ -1,8 +1,8 @@ package com.baeldung.jpa.defaultvalues; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; public class UserRepository { diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/entity/Article.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/entity/Article.java index 02082c3d9214..9aaa6f3d3487 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/entity/Article.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/entity/Article.java @@ -1,7 +1,7 @@ package com.baeldung.jpa.entity; -import javax.persistence.Entity; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; @Entity(name = "MyArticle") @Table(name = Article.TABLE_NAME) diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/Admin.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/Admin.java index 1c59b33ab85b..b9c50a3e8865 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/Admin.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/Admin.java @@ -1,10 +1,10 @@ package com.baeldung.jpa.generateidvalue; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "app_admin") diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/Article.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/Article.java index 06465de1794f..5ebb812638a5 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/Article.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/Article.java @@ -1,12 +1,12 @@ package com.baeldung.jpa.generateidvalue; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; @Entity @Table(name = "article") diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/IdGenerator.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/IdGenerator.java index 0fac86747f3e..371b844fd639 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/IdGenerator.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/IdGenerator.java @@ -1,11 +1,11 @@ package com.baeldung.jpa.generateidvalue; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Table(name = "id_gen") @Entity diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/Task.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/Task.java index a51ec5341860..e2f67ee0def1 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/Task.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/Task.java @@ -1,12 +1,12 @@ package com.baeldung.jpa.generateidvalue; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.TableGenerator; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.TableGenerator; @Entity @Table(name = "task") diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/User.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/User.java index 88fefe7ba623..7b976c5ee1cb 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/User.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/generateidvalue/User.java @@ -1,11 +1,11 @@ package com.baeldung.jpa.generateidvalue; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "app_user") diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/AllergensAsEntity.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/AllergensAsEntity.java index e5e228d01399..fc1777abe863 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/AllergensAsEntity.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/AllergensAsEntity.java @@ -1,13 +1,13 @@ package com.baeldung.jpa.multipletables.multipleentities; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToOne; -import javax.persistence.PrimaryKeyJoinColumn; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; +import jakarta.persistence.PrimaryKeyJoinColumn; +import jakarta.persistence.Table; import com.baeldung.jpa.multipletables.secondarytable.MealAsSingleEntity; diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/MealWithMultipleEntities.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/MealWithMultipleEntities.java index 74105f8f1f3a..f14540e7ae32 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/MealWithMultipleEntities.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/MealWithMultipleEntities.java @@ -2,13 +2,13 @@ import java.math.BigDecimal; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; @Entity @Table(name = "meal") diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/MealAsSingleEntity.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/MealAsSingleEntity.java index 2929f391a492..d967d7618d0d 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/MealAsSingleEntity.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/MealAsSingleEntity.java @@ -2,14 +2,14 @@ import java.math.BigDecimal; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.PrimaryKeyJoinColumn; -import javax.persistence.SecondaryTable; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.PrimaryKeyJoinColumn; +import jakarta.persistence.SecondaryTable; +import jakarta.persistence.Table; @Entity @Table(name = "meal") diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/AllergensAsEmbeddable.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/AllergensAsEmbeddable.java index 1c1f05890bd0..b95649029ee4 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/AllergensAsEmbeddable.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/AllergensAsEmbeddable.java @@ -1,7 +1,7 @@ package com.baeldung.jpa.multipletables.secondarytable.embeddable; -import javax.persistence.Column; -import javax.persistence.Embeddable; +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; @Embeddable public class AllergensAsEmbeddable { diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/MealWithEmbeddedAllergens.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/MealWithEmbeddedAllergens.java index 87a83157d7bb..ada6328226d4 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/MealWithEmbeddedAllergens.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/MealWithEmbeddedAllergens.java @@ -2,15 +2,15 @@ import java.math.BigDecimal; -import javax.persistence.Column; -import javax.persistence.Embedded; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.PrimaryKeyJoinColumn; -import javax.persistence.SecondaryTable; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Embedded; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.PrimaryKeyJoinColumn; +import jakarta.persistence.SecondaryTable; +import jakarta.persistence.Table; @Entity @Table(name = "meal") diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/projections/Product.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/projections/Product.java index 90f90be0c0a5..b9cb0076ab99 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/projections/Product.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/projections/Product.java @@ -2,10 +2,8 @@ import java.math.BigDecimal; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; @Entity public class Product { diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/projections/ProductRepository.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/projections/ProductRepository.java index bb269e1de670..402e5325ef9c 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/projections/ProductRepository.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/projections/ProductRepository.java @@ -2,14 +2,14 @@ import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.Query; -import javax.persistence.Tuple; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; +import jakarta.persistence.Query; +import jakarta.persistence.Tuple; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; public class ProductRepository { private EntityManager entityManager; diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/queryparams/Employee.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/queryparams/Employee.java index bf3d45953052..ed8788cad68c 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/queryparams/Employee.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/queryparams/Employee.java @@ -1,11 +1,11 @@ package com.baeldung.jpa.queryparams; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "employees") diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/querytypes/QueryTypesExamples.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/querytypes/QueryTypesExamples.java index 523fc348f9a1..9738e0923b80 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/querytypes/QueryTypesExamples.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/querytypes/QueryTypesExamples.java @@ -3,14 +3,14 @@ import java.util.HashMap; import java.util.Map; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.Query; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; +import jakarta.persistence.Query; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; /** * JPA Query Types examples. All using the UserEntity class. diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/querytypes/UserEntity.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/querytypes/UserEntity.java index 1d4a231b316c..14ccc15a9c8d 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/querytypes/UserEntity.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/querytypes/UserEntity.java @@ -1,9 +1,9 @@ package com.baeldung.jpa.querytypes; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.NamedQuery; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.NamedQuery; +import jakarta.persistence.Table; /** * User entity class. Used as an asset for JPA Query Types examples. diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/Exam.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/Exam.java index 8bea8e012146..a674069a6308 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/Exam.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/Exam.java @@ -1,6 +1,6 @@ package com.baeldung.jpa.text; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class Exam { diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/ExamRepository.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/ExamRepository.java index 2ee502bf4cc9..7b783be365e4 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/ExamRepository.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/ExamRepository.java @@ -1,8 +1,8 @@ package com.baeldung.jpa.text; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; public class ExamRepository { diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Cocktail.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Cocktail.java index 96310c1cc5c2..e896efe0ecba 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Cocktail.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Cocktail.java @@ -1,11 +1,9 @@ package com.baeldung.jpa.unrelated.entities; -import org.hibernate.annotations.Fetch; -import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.List; import java.util.Objects; @@ -27,18 +25,17 @@ public class Cocktail { @JoinColumn(name = "cocktail_name", referencedColumnName = "cocktail", insertable = false, updatable = false, - foreignKey = @javax.persistence + foreignKey = @jakarta.persistence .ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) private Recipe recipe; @OneToMany(fetch = FetchType.LAZY) - @NotFound(action = NotFoundAction.IGNORE) @JoinColumn( name = "cocktail", referencedColumnName = "cocktail_name", insertable = false, updatable = false, - foreignKey = @javax.persistence + foreignKey = @jakarta.persistence .ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) private List recipeList; diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/MultipleRecipe.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/MultipleRecipe.java index 8664d6fd7f84..b17860f75575 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/MultipleRecipe.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/MultipleRecipe.java @@ -1,9 +1,9 @@ package com.baeldung.jpa.unrelated.entities; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import java.util.Objects; @Entity diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Recipe.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Recipe.java index 4b3d200b60e7..2cb4839b33c1 100644 --- a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Recipe.java +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/unrelated/entities/Recipe.java @@ -1,9 +1,9 @@ package com.baeldung.jpa.unrelated.entities; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import java.util.Objects; @Entity diff --git a/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml index 3bc81910d992..15d5799c0a04 100644 --- a/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml @@ -1,9 +1,8 @@ - + @@ -11,20 +10,15 @@ com.baeldung.jpa.queryparams.Employee true - - - - - + + + + + - - + + @@ -34,18 +28,14 @@ com.baeldung.jpa.text.Exam true - - - - - + + + + + - + @@ -54,18 +44,14 @@ com.baeldung.jpa.defaultvalues.User true - - - - - + + + + + - + @@ -74,20 +60,15 @@ com.baeldung.jpa.querytypes.UserEntity true - - - - - + + + + + - - + + @@ -96,20 +77,15 @@ com.baeldung.jpa.projections.Product true - - - - - + + + + + - - + + @@ -118,20 +94,15 @@ com.baeldung.jpa.criteria.Item true - - - - - + + + + + - - + + @@ -147,19 +118,15 @@ true - - - - - + + + + + - + @@ -170,18 +137,14 @@ com.baeldung.jpa.unrelated.entities.MultipleRecipe true - - - - - + + + + + - + @@ -194,14 +157,11 @@ com.baeldung.jpa.generateidvalue.User true - - - - - + + + + + diff --git a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/defaultvalues/UserDefaultValuesUnitTest.java b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/defaultvalues/UserDefaultValuesUnitTest.java index dc41ff51f29b..b9c3dffecd16 100644 --- a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/defaultvalues/UserDefaultValuesUnitTest.java +++ b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/defaultvalues/UserDefaultValuesUnitTest.java @@ -1,8 +1,5 @@ package com.baeldung.jpa.defaultvalues; -import com.baeldung.jpa.defaultvalues.User; -import com.baeldung.jpa.defaultvalues.UserRepository; - import org.junit.Test; import org.junit.Ignore; import org.junit.AfterClass; diff --git a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/generateidvalue/PrimaryKeyUnitTest.java b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/generateidvalue/PrimaryKeyUnitTest.java index eead56dbffa7..8691cbca4a2d 100644 --- a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/generateidvalue/PrimaryKeyUnitTest.java +++ b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/generateidvalue/PrimaryKeyUnitTest.java @@ -1,8 +1,8 @@ package com.baeldung.jpa.generateidvalue; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; import org.junit.Assert; import org.junit.BeforeClass; @@ -27,12 +27,10 @@ public void givenIdentityStrategy_whenCommitTransction_thenReturnPrimaryKey() { User user = new User(); user.setName("TestName"); - entityManager.getTransaction() - .begin(); + entityManager.getTransaction().begin(); entityManager.persist(user); Assert.assertNull(user.getId()); - entityManager.getTransaction() - .commit(); + entityManager.getTransaction().commit(); Long expectPrimaryKey = 1L; Assert.assertEquals(expectPrimaryKey, user.getId()); diff --git a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/multipletables/MultipleTablesIntegrationTest.java b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/multipletables/MultipleTablesIntegrationTest.java index 99b2cd69ee45..a2aedbc5bf77 100644 --- a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/multipletables/MultipleTablesIntegrationTest.java +++ b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/multipletables/MultipleTablesIntegrationTest.java @@ -2,9 +2,9 @@ import static org.assertj.core.api.Assertions.*; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; import org.junit.AfterClass; import org.junit.BeforeClass; diff --git a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/projections/HibernateProjectionsIntegrationTest.java b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/projections/HibernateProjectionsIntegrationTest.java index 47cc7cbaec87..b78802bb42f4 100644 --- a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/projections/HibernateProjectionsIntegrationTest.java +++ b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/projections/HibernateProjectionsIntegrationTest.java @@ -5,19 +5,22 @@ import java.util.List; -import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.Projections; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Path; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.metamodel.SingularAttribute; + public class HibernateProjectionsIntegrationTest { private static Session session; private static SessionFactory sessionFactory; @@ -56,16 +59,20 @@ private static Configuration getConfiguration() { cfg.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "thread"); return cfg; } - - + + @SuppressWarnings("deprecation") @Test public void givenProductData_whenIdAndNameProjectionUsingCriteria_thenListOfObjectArrayReturned() { - Criteria criteria = session.createCriteria(Product.class); - criteria = criteria.setProjection(Projections.projectionList() - .add(Projections.id()) - .add(Projections.property("name"))); - List resultList = criteria.list(); + final CriteriaBuilder criteria = session.getCriteriaBuilder(); + final CriteriaQuery criteriaQuery = criteria.createQuery(Object[].class); + final Root root = criteriaQuery.from(Product.class); + final SingularAttribute name = Product_.name; + final SingularAttribute id = Product_.id; + final Path nameProjection = root.get(name); + final Path idProjection = root.get(id); + criteriaQuery.multiselect(idProjection, nameProjection); + final List resultList = session.createQuery(criteriaQuery).getResultList(); assertNotNull(resultList); assertEquals(4, resultList.size()); @@ -82,9 +89,13 @@ public void givenProductData_whenIdAndNameProjectionUsingCriteria_thenListOfObje @Test public void givenProductData_whenNameProjectionUsingCriteria_thenListOfStringReturned() { - Criteria criteria = session.createCriteria(Product.class); - criteria = criteria.setProjection(Projections.property("name")); - List resultList = criteria.list(); + final CriteriaBuilder criteria = session.getCriteriaBuilder(); + final CriteriaQuery criteriaQuery = criteria.createQuery(String.class); + final Root root = criteriaQuery.from(Product.class); + final SingularAttribute name = Product_.name; + final Path nameProjection = root.get(name); + criteriaQuery.select(nameProjection); + final List resultList = session.createQuery(criteriaQuery).getResultList(); assertNotNull(resultList); assertEquals(4, resultList.size()); @@ -96,11 +107,12 @@ public void givenProductData_whenNameProjectionUsingCriteria_thenListOfStringRet @Test public void givenProductData_whenCountByCategoryUsingCriteria_thenOK() { - Criteria criteria = session.createCriteria(Product.class); - criteria = criteria.setProjection(Projections.projectionList() - .add(Projections.groupProperty("category")) - .add(Projections.rowCount())); - List resultList = criteria.list(); + final CriteriaBuilder criteria = session.getCriteriaBuilder(); + final CriteriaQuery criteriaQuery = criteria.createQuery(Object[].class); + final Root root = criteriaQuery.from(Product.class); + criteriaQuery.groupBy(root.get("category")); + criteriaQuery.multiselect(root.get("category"), criteria.count(root)); + final List resultList = session.createQuery(criteriaQuery).getResultList(); assertNotNull(resultList); assertEquals(3, resultList.size()); @@ -114,12 +126,13 @@ public void givenProductData_whenCountByCategoryUsingCriteria_thenOK() { @Test public void givenProductData_whenCountByCategoryWithAliasUsingCriteria_thenOK() { - Criteria criteria = session.createCriteria(Product.class); - criteria = criteria.setProjection(Projections.projectionList() - .add(Projections.groupProperty("category")) - .add(Projections.alias(Projections.rowCount(), "count"))); - criteria.addOrder(Order.asc("count")); - List resultList = criteria.list(); + final CriteriaBuilder criteria = session.getCriteriaBuilder(); + final CriteriaQuery criteriaQuery = criteria.createQuery(Object[].class); + final Root root = criteriaQuery.from(Product.class); + criteriaQuery.groupBy(root.get("category")); + criteriaQuery.multiselect(root.get("category"), criteria.count(root)); + criteriaQuery.orderBy(criteria.asc(criteria.count(root))); + List resultList = session.createQuery(criteriaQuery).getResultList(); assertNotNull(resultList); assertEquals(3, resultList.size()); diff --git a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java index 55ee0e6e59cf..ed047cb45e0f 100644 --- a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java +++ b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java @@ -3,14 +3,14 @@ import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.ParameterExpression; -import javax.persistence.criteria.Root; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.ParameterExpression; +import jakarta.persistence.criteria.Root; import org.junit.Assert; import org.junit.BeforeClass; diff --git a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/text/JPATextUnitTest.java b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/text/JPATextUnitTest.java index f9f355c4648a..f7fcd9117d74 100644 --- a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/text/JPATextUnitTest.java +++ b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/text/JPATextUnitTest.java @@ -2,7 +2,7 @@ import static org.junit.Assert.assertEquals; -import javax.persistence.PersistenceException; +import jakarta.persistence.PersistenceException; import org.junit.BeforeClass; import org.junit.Test; diff --git a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/unrelated/entities/UnrelatedEntitiesUnitTest.java b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/unrelated/entities/UnrelatedEntitiesUnitTest.java index 044e59b16e0a..0fae147b13b5 100644 --- a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/unrelated/entities/UnrelatedEntitiesUnitTest.java +++ b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/unrelated/entities/UnrelatedEntitiesUnitTest.java @@ -1,14 +1,15 @@ package com.baeldung.jpa.unrelated.entities; -import javax.persistence.*; +import jakarta.persistence.*; -import com.querydsl.jpa.impl.JPAQuery; import org.junit.jupiter.api.*; +import static org.junit.jupiter.api.Assertions.*; + import java.util.List; import java.util.function.Consumer; -import static org.junit.jupiter.api.Assertions.*; +import com.querydsl.jpa.impl.JPAQuery; public class UnrelatedEntitiesUnitTest { private static EntityManagerFactory entityManagerFactory; diff --git a/persistence-modules/java-jpa-2/src/test/resources/META-INF/persistence.xml b/persistence-modules/java-jpa-2/src/test/resources/META-INF/persistence.xml index 00c7274dd44b..46ee62b1ca2b 100644 --- a/persistence-modules/java-jpa-2/src/test/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa-2/src/test/resources/META-INF/persistence.xml @@ -1,9 +1,8 @@ - + @@ -11,20 +10,15 @@ com.baeldung.jpa.queryparams.Employee true - - - - - + + + + + - - + + @@ -34,18 +28,14 @@ com.baeldung.jpa.text.Exam true - - - - - + + + + + - + @@ -54,18 +44,14 @@ com.baeldung.jpa.defaultvalues.User true - - - - - + + + + + - + @@ -74,20 +60,15 @@ com.baeldung.jpa.querytypes.UserEntity true - - - - - + + + + + - - + + @@ -96,20 +77,15 @@ com.baeldung.jpa.projections.Product true - - - - - + + + + + - - + + @@ -118,20 +94,15 @@ com.baeldung.jpa.criteria.Item true - - - - - + + + + + - - + + @@ -147,19 +118,15 @@ true - - - - - + + + + + - + @@ -170,18 +137,14 @@ com.baeldung.jpa.unrelated.entities.MultipleRecipe true - - - - - + + + + + - + @@ -194,14 +157,11 @@ com.baeldung.jpa.generateidvalue.User true - - - - - + + + + + diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml index 0c8cec2116f7..b70fd0daec43 100644 --- a/persistence-modules/java-jpa/pom.xml +++ b/persistence-modules/java-jpa/pom.xml @@ -14,32 +14,44 @@ - org.hibernate + org.hibernate.orm hibernate-core ${hibernate.version} + + + jakarta.xml.bind + jakarta.xml.bind-api + + - org.hibernate + org.hibernate.orm hibernate-jpamodelgen ${hibernate.version} + + + jakarta.xml.bind + jakarta.xml.bind-api + + com.h2database h2 ${h2.version} - - - javax.persistence - javax.persistence-api - ${javax.persistence-api.version} - org.eclipse.persistence eclipselink ${eclipselink.version} runtime + + + jakarta.xml.bind + jakarta.xml.bind-api + + org.postgresql @@ -47,6 +59,16 @@ ${postgresql.version} runtime + + jakarta.xml.bind + jakarta.xml.bind-api + ${jakarta.xml.bind-api.version} + + + javax.annotation + javax.annotation-api + ${javax.annotation.version} + @@ -102,12 +124,12 @@ - 5.4.0.Final - 2.7.4 - 2.2 + 4.0.1 3.3.3 3.0.0 2.1.214 + 4.0.0 + 1.3.2 \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/basicannotation/Course.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/basicannotation/Course.java index cc5a83420c83..559076a2adbc 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/basicannotation/Course.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/basicannotation/Course.java @@ -1,9 +1,9 @@ package com.baeldung.jpa.basicannotation; -import javax.persistence.Basic; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.Id; +import jakarta.persistence.Basic; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; @Entity public class Course { diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/convertdates/LocalDateConverter.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/convertdates/LocalDateConverter.java index de6ada23616d..f74aad71e633 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/convertdates/LocalDateConverter.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/convertdates/LocalDateConverter.java @@ -1,7 +1,7 @@ package com.baeldung.jpa.convertdates; -import javax.persistence.AttributeConverter; -import javax.persistence.Converter; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; import java.sql.Date; import java.time.LocalDate; import java.util.Optional; diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/datetime/DateTimeEntityRepository.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/datetime/DateTimeEntityRepository.java index 0bd04da22125..2aa6fa60b6b6 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/datetime/DateTimeEntityRepository.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/datetime/DateTimeEntityRepository.java @@ -1,8 +1,8 @@ package com.baeldung.jpa.datetime; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/datetime/JPA22DateTimeEntity.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/datetime/JPA22DateTimeEntity.java index 065385bd869d..0a4aade78933 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/datetime/JPA22DateTimeEntity.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/datetime/JPA22DateTimeEntity.java @@ -1,6 +1,6 @@ package com.baeldung.jpa.datetime; -import javax.persistence.*; +import jakarta.persistence.*; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Student.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Student.java index 64e7ab586c68..27293147eb90 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Student.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Student.java @@ -2,17 +2,17 @@ import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import jakarta.persistence.Transient; @Entity @Table(name="STUDENT") diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Comment.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Comment.java index 40ecd3262b65..b7c3a6254654 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Comment.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Comment.java @@ -1,6 +1,6 @@ package com.baeldung.jpa.entitygraph.model; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class Comment { diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Post.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Post.java index 59f17ae0c5b8..9d340f4b319e 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Post.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Post.java @@ -1,6 +1,6 @@ package com.baeldung.jpa.entitygraph.model; -import javax.persistence.*; +import jakarta.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/User.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/User.java index b712100d4e1a..37fab8d4da14 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/User.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/User.java @@ -1,9 +1,9 @@ package com.baeldung.jpa.entitygraph.model; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class User { diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/repo/PostRepository.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/repo/PostRepository.java index 28f1e1b93c12..16e7badc6410 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/repo/PostRepository.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/repo/PostRepository.java @@ -2,10 +2,10 @@ import com.baeldung.jpa.entitygraph.model.Post; -import javax.persistence.*; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.*; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import java.util.HashMap; import java.util.Map; @@ -34,7 +34,7 @@ public Post findWithEntityGraph(Long id) { EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph"); Map properties = new HashMap<>(); - properties.put("javax.persistence.fetchgraph", entityGraph); + properties.put("jakarta.persistence.fetchgraph", entityGraph); Post post = entityManager.find(Post.class, id, properties); entityManager.close(); @@ -51,7 +51,7 @@ public Post findWithEntityGraph2(Long id) { .addAttributeNodes("user"); Map properties = new HashMap<>(); - properties.put("javax.persistence.fetchgraph", entityGraph); + properties.put("jakarta.persistence.fetchgraph", entityGraph); Post post = entityManager.find(Post.class, id, properties); entityManager.close(); @@ -64,7 +64,7 @@ public Post findUsingJpql(Long id) { EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph-with-comment-users"); Post post = entityManager.createQuery("Select p from Post p where p.id=:id", Post.class) .setParameter("id", id) - .setHint("javax.persistence.fetchgraph", entityGraph) + .setHint("jakarta.persistence.fetchgraph", entityGraph) .getSingleResult(); entityManager.close(); @@ -80,7 +80,7 @@ public Post findUsingCriteria(Long id) { Root root = criteriaQuery.from(Post.class); criteriaQuery.where(criteriaBuilder.equal(root.get("id"), id)); TypedQuery typedQuery = entityManager.createQuery(criteriaQuery); - typedQuery.setHint("javax.persistence.loadgraph", entityGraph); + typedQuery.setHint("jakarta.persistence.loadgraph", entityGraph); Post post = typedQuery.getSingleResult(); entityManager.close(); diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Article.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Article.java index d534f44e14fd..a516ae16fff4 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Article.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Article.java @@ -1,6 +1,6 @@ package com.baeldung.jpa.enums; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class Article { diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/CategoryConverter.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/CategoryConverter.java index 98960f1569cd..b69fc51afdcd 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/CategoryConverter.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/CategoryConverter.java @@ -1,7 +1,7 @@ package com.baeldung.jpa.enums; -import javax.persistence.AttributeConverter; -import javax.persistence.Converter; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; import java.util.stream.Stream; @Converter(autoApply = true) diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/Car.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/Car.java index 676d76307e3e..86ad487e11f8 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/Car.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/Car.java @@ -1,15 +1,15 @@ package com.baeldung.jpa.model; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.NamedStoredProcedureQueries; -import javax.persistence.NamedStoredProcedureQuery; -import javax.persistence.ParameterMode; -import javax.persistence.StoredProcedureParameter; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.NamedStoredProcedureQueries; +import jakarta.persistence.NamedStoredProcedureQuery; +import jakarta.persistence.ParameterMode; +import jakarta.persistence.StoredProcedureParameter; +import jakarta.persistence.Table; @Entity @Table(name = "CAR") diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/primarykeys/Account.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/primarykeys/Account.java index 915c605e65f3..d4825a56fcb3 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/primarykeys/Account.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/primarykeys/Account.java @@ -1,8 +1,8 @@ package com.baeldung.jpa.primarykeys; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.IdClass; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.IdClass; @Entity @IdClass(AccountId.class) diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/primarykeys/Book.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/primarykeys/Book.java index a84eb3ef012a..6a2b86d97781 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/primarykeys/Book.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/primarykeys/Book.java @@ -1,7 +1,7 @@ package com.baeldung.jpa.primarykeys; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; @Entity public class Book { diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/primarykeys/BookId.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/primarykeys/BookId.java index d8c925c148d3..e4c60bd5baad 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/primarykeys/BookId.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/primarykeys/BookId.java @@ -2,7 +2,7 @@ import java.io.Serializable; -import javax.persistence.Embeddable; +import jakarta.persistence.Embeddable; @Embeddable public class BookId implements Serializable { diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/sqlresultsetmapping/Employee.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/sqlresultsetmapping/Employee.java index b62a21d481b1..f6fed9913c1f 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/sqlresultsetmapping/Employee.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/sqlresultsetmapping/Employee.java @@ -1,6 +1,6 @@ package com.baeldung.jpa.sqlresultsetmapping; -import javax.persistence.*; +import jakarta.persistence.*; @SqlResultSetMapping( diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/sqlresultsetmapping/ScheduledDay.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/sqlresultsetmapping/ScheduledDay.java index a7ca59ab3f49..55a77d6d5029 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/sqlresultsetmapping/ScheduledDay.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/sqlresultsetmapping/ScheduledDay.java @@ -1,6 +1,6 @@ package com.baeldung.jpa.sqlresultsetmapping; -import javax.persistence.*; +import jakarta.persistence.*; @SqlResultSetMappings(value = { @SqlResultSetMapping(name = "ScheduleResult", diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/Message.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/Message.java index fb521cfea6fc..2888266203ce 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/Message.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/Message.java @@ -1,6 +1,6 @@ package com.baeldung.jpa.stringcast; -import javax.persistence.*; +import jakarta.persistence.*; @SqlResultSetMapping(name = "textQueryMapping", classes = { @ConstructorResult(targetClass = Message.class, columns = { diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java index 2cb5679d4df4..948ac52bce59 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java @@ -4,8 +4,8 @@ import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.persistence.Query; +import jakarta.persistence.EntityManager; +import jakarta.persistence.Query; public class QueryExecutor { diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index 50188391af25..b4816885b5b5 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -1,9 +1,8 @@ - + org.hibernate.jpa.HibernatePersistenceProvider @@ -12,18 +11,14 @@ com.baeldung.jpa.basicannotation.Course true - - - - - + + + + + - + @@ -34,18 +29,14 @@ com.baeldung.jpa.enums.CategoryConverter true - - - - - + + + + + - + @@ -54,39 +45,26 @@ com.baeldung.jpa.model.Car true - - - - - + + + + + - + com.baeldung.jpa.entitygraph.model.Post com.baeldung.jpa.entitygraph.model.User com.baeldung.jpa.entitygraph.model.Comment true - - - - - - + + + + @@ -96,17 +74,11 @@ com.baeldung.jpa.datetime.JPA22DateTimeEntity true - - - - - + + + + + @@ -124,18 +96,14 @@ com.baeldung.jpa.primarykeys.AccountId true - - - - - + + + + + - + diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/basicannotation/BasicAnnotationIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/basicannotation/BasicAnnotationIntegrationTest.java index d3f75804de3a..96e15af16fca 100644 --- a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/basicannotation/BasicAnnotationIntegrationTest.java +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/basicannotation/BasicAnnotationIntegrationTest.java @@ -1,9 +1,9 @@ package com.baeldung.jpa.basicannotation; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.PersistenceException; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; +import jakarta.persistence.PersistenceException; import org.junit.AfterClass; import org.junit.BeforeClass; diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/StudentEntityIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/StudentEntityIntegrationTest.java index 3c7a82edc319..caeeb62a989d 100644 --- a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/StudentEntityIntegrationTest.java +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/StudentEntityIntegrationTest.java @@ -7,10 +7,10 @@ import java.util.Date; import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.TypedQuery; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; +import jakarta.persistence.TypedQuery; import org.junit.After; import org.junit.Before; diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/enums/ArticleUnitTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/enums/ArticleUnitTest.java index 36a7cb1002bb..78d3588cc83d 100644 --- a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/enums/ArticleUnitTest.java +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/enums/ArticleUnitTest.java @@ -3,11 +3,11 @@ import org.junit.BeforeClass; import org.junit.Test; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; -import javax.persistence.TypedQuery; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.EntityTransaction; +import jakarta.persistence.Persistence; +import jakarta.persistence.TypedQuery; import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/primarykeys/CompositeKeysIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/primarykeys/CompositeKeysIntegrationTest.java index be529ab81cb2..45037387d616 100644 --- a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/primarykeys/CompositeKeysIntegrationTest.java +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/primarykeys/CompositeKeysIntegrationTest.java @@ -3,9 +3,9 @@ import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertEquals; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; import com.baeldung.jpa.primarykeys.Account; import com.baeldung.jpa.primarykeys.AccountId; diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/sqlresultsetmapping/SqlResultSetMappingUnitTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/sqlresultsetmapping/SqlResultSetMappingUnitTest.java index f318df3747a5..f61ed1617761 100644 --- a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/sqlresultsetmapping/SqlResultSetMappingUnitTest.java +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/sqlresultsetmapping/SqlResultSetMappingUnitTest.java @@ -4,10 +4,10 @@ import org.junit.jupiter.api.*; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.Query; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; +import jakarta.persistence.Query; import java.util.Collections; import java.util.List; @@ -44,7 +44,7 @@ public void whenNamedQuery_thenSingleEntityResult() { @Test public void whenNamedQuery_thenMultipleEntityResult() { - final Query query = em.createNativeQuery("SELECT e.id, e.name, d.id, d.employeeId, d.dayOfWeek " + final Query query = em.createNativeQuery("SELECT e.id as idEmployee, e.name, d.id as daysId, d.employeeId, d.dayOfWeek " + " FROM employee e, schedule_days d " + " WHERE e.id = d.employeeId", "EmployeeScheduleResults"); List results = query.getResultList(); diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java index 8bc8c854da8d..f1c61ee408b5 100644 --- a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java @@ -1,11 +1,11 @@ package com.baeldung.jpa.storedprocedure; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.ParameterMode; -import javax.persistence.Persistence; -import javax.persistence.StoredProcedureQuery; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.EntityTransaction; +import jakarta.persistence.ParameterMode; +import jakarta.persistence.Persistence; +import jakarta.persistence.StoredProcedureQuery; import org.junit.AfterClass; import org.junit.Assert; diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/stringcast/SpringCastUnitTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/stringcast/SpringCastUnitTest.java index 0a11725fc38e..52789c778343 100644 --- a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/stringcast/SpringCastUnitTest.java +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/stringcast/SpringCastUnitTest.java @@ -3,7 +3,7 @@ import org.junit.BeforeClass; import org.junit.Test; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.List; import static org.junit.Assert.assertEquals; diff --git a/persistence-modules/java-jpa/src/test/resources/persistence.xml b/persistence-modules/java-jpa/src/test/resources/persistence.xml index e9b5ebbbcfec..c9bec9557f3d 100644 --- a/persistence-modules/java-jpa/src/test/resources/persistence.xml +++ b/persistence-modules/java-jpa/src/test/resources/persistence.xml @@ -1,18 +1,17 @@ - + org.hibernate.jpa.HibernatePersistenceProvider com.baeldung.jpa.model.Car - - - - + + + + @@ -22,10 +21,10 @@ org.hibernate.jpa.HibernatePersistenceProvider com.baeldung.jpa.stringcast.Message - - - - + + + + diff --git a/persistence-modules/jnosql/jnosql-artemis/pom.xml b/persistence-modules/jnosql/jnosql-artemis/pom.xml index 0c1a6967d3e9..da100388ab0a 100644 --- a/persistence-modules/jnosql/jnosql-artemis/pom.xml +++ b/persistence-modules/jnosql/jnosql-artemis/pom.xml @@ -40,6 +40,16 @@ ${project.artifactId} + + org.apache.maven.plugins + maven-war-plugin + ${maven.war-plugin.version} + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler-plugin.version} + net.wasdev.wlp.maven.plugins liberty-maven-plugin @@ -80,7 +90,9 @@ 2.4.2 false - 8.0 + 8.0.1 + 3.3.1 + 3.8.1 \ No newline at end of file diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index d7ff51b4873c..9361e26d7d21 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -21,7 +21,6 @@ blaze-persistence core-java-persistence core-java-persistence-2 - deltaspike elasticsearch flyway flyway-repair @@ -29,7 +28,6 @@ hibernate5 hibernate-mapping hibernate-mapping-2 - hibernate-ogm hibernate-annotations hibernate-exceptions hibernate-libraries @@ -37,14 +35,13 @@ hibernate-queries hibernate-enterprise influxdb - java-cassandra java-cockroachdb java-jdbi java-jpa - java-jpa-2 + java-jpa-2 java-jpa-3 - - + + java-mongodb-2 java-mongodb-3 java-mongodb-queries @@ -71,7 +68,7 @@ spring-data-arangodb spring-data-cassandra spring-data-cassandra-test - spring-data-cassandra-reactive + spring-data-cosmosdb spring-data-couchbase-2 spring-data-dynamodb @@ -93,32 +90,37 @@ spring-data-jpa-repo-2 spring-data-jdbc spring-data-keyvalue - spring-data-mongodb + spring-data-mongodb-2 spring-data-mongodb-reactive - spring-data-neo4j + spring-data-redis - - + + spring-data-rest-2 spring-data-rest-querydsl spring-data-solr - spring-hibernate-3 - spring-hibernate-5 - spring-jpa - spring-jpa-2 + + + spring-jdbc spring-jooq spring-mybatis spring-persistence-simple + + fauna + spring-data-rest + java-mongodb + questdb - 5.2.17.Final - 42.2.20 - 2.3.4 + 6.2.0.Final + 42.5.4 + 2.7.1 1.16.3 - \ No newline at end of file + diff --git a/persistence-modules/querydsl/pom.xml b/persistence-modules/querydsl/pom.xml index c97dcdd93de6..921d45815ac4 100644 --- a/persistence-modules/querydsl/pom.xml +++ b/persistence-modules/querydsl/pom.xml @@ -19,11 +19,13 @@ com.querydsl querydsl-jpa + jakarta ${querydsl.version} com.querydsl querydsl-apt + jakarta ${querydsl.version} provided @@ -34,12 +36,6 @@ ${hibernate.version} compile - - org.hibernate.javax.persistence - hibernate-jpa-2.1-api - ${hibernate-jpa.version} - compile - commons-dbcp commons-dbcp @@ -106,8 +102,6 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - ${java.version} - ${java.version} -proc:none @@ -132,10 +126,8 @@ - 4.3.4.RELEASE - 5.2.5.Final - 1.0.0.Final - 4.1.4 + 6.0.6 + 5.0.0 1.6 1.4 1.1.3 diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/dao/PersonDaoImpl.java b/persistence-modules/querydsl/src/main/java/com/baeldung/dao/PersonDaoImpl.java index 20ebe0e3feea..8d91ec0f5911 100644 --- a/persistence-modules/querydsl/src/main/java/com/baeldung/dao/PersonDaoImpl.java +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/dao/PersonDaoImpl.java @@ -3,14 +3,18 @@ import com.baeldung.entity.Person; import com.baeldung.entity.QPerson; import com.querydsl.core.group.GroupBy; +import com.querydsl.jpa.JPQLTemplates; import com.querydsl.jpa.impl.JPAQuery; +import com.querydsl.jpa.impl.JPAQueryFactory; + import org.springframework.stereotype.Repository; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; import java.util.List; import java.util.Map; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; + @Repository public class PersonDaoImpl implements PersonDao { @@ -57,7 +61,7 @@ public int findMaxAge() { @Override public Map findMaxAgeByName() { - final JPAQuery query = new JPAQuery<>(em); + final JPAQueryFactory query = new JPAQueryFactory(JPQLTemplates.DEFAULT, em); final QPerson person = QPerson.person; return query.from(person).transform(GroupBy.groupBy(person.firstname).as(GroupBy.max(person.age))); diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/entity/Person.java b/persistence-modules/querydsl/src/main/java/com/baeldung/entity/Person.java index 310f21ab2a78..8985215fcd4e 100644 --- a/persistence-modules/querydsl/src/main/java/com/baeldung/entity/Person.java +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/entity/Person.java @@ -1,10 +1,10 @@ package com.baeldung.entity; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Person { diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/BlogPost.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/BlogPost.java index 6712ad08d565..43ba594bdd26 100644 --- a/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/BlogPost.java +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/BlogPost.java @@ -3,10 +3,10 @@ */ package com.baeldung.querydsl.intro.entities; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; @Entity public class BlogPost { diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/User.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/User.java index 4111284d5a1d..1d572eb389f0 100644 --- a/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/User.java +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydsl/intro/entities/User.java @@ -5,7 +5,7 @@ import java.util.HashSet; import java.util.Set; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class User { diff --git a/persistence-modules/querydsl/src/main/resources/META-INF/persistence.xml b/persistence-modules/querydsl/src/main/resources/META-INF/persistence.xml index 4b51cb444b74..078fa8ce2397 100644 --- a/persistence-modules/querydsl/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/querydsl/src/main/resources/META-INF/persistence.xml @@ -1,9 +1,8 @@ - + version="3.0" + xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"> diff --git a/persistence-modules/querydsl/src/test/java/com/baeldung/dao/PersonDaoIntegrationTest.java b/persistence-modules/querydsl/src/test/java/com/baeldung/dao/PersonDaoIntegrationTest.java index cf4e9ab872e8..e9cf679c4350 100644 --- a/persistence-modules/querydsl/src/test/java/com/baeldung/dao/PersonDaoIntegrationTest.java +++ b/persistence-modules/querydsl/src/test/java/com/baeldung/dao/PersonDaoIntegrationTest.java @@ -6,9 +6,9 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import junit.framework.Assert; @@ -16,7 +16,7 @@ @ContextConfiguration("/test-context.xml") @RunWith(SpringJUnit4ClassRunner.class) @Transactional -@TransactionConfiguration(defaultRollback = true) +@Rollback public class PersonDaoIntegrationTest { @Autowired diff --git a/persistence-modules/querydsl/src/test/java/com/baeldung/querydsl/intro/QueryDSLIntegrationTest.java b/persistence-modules/querydsl/src/test/java/com/baeldung/querydsl/intro/QueryDSLIntegrationTest.java index 7ae97c2880cb..29d49d114daf 100644 --- a/persistence-modules/querydsl/src/test/java/com/baeldung/querydsl/intro/QueryDSLIntegrationTest.java +++ b/persistence-modules/querydsl/src/test/java/com/baeldung/querydsl/intro/QueryDSLIntegrationTest.java @@ -14,9 +14,9 @@ import com.querydsl.jpa.impl.JPAQueryFactory; import org.junit.*; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; import java.util.List; import static org.junit.Assert.*; diff --git a/persistence-modules/questdb/pom.xml b/persistence-modules/questdb/pom.xml index ee3db461cbfa..5e803f739ad1 100644 --- a/persistence-modules/questdb/pom.xml +++ b/persistence-modules/questdb/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 org.baeldung diff --git a/persistence-modules/r2dbc/pom.xml b/persistence-modules/r2dbc/pom.xml index cfe344eba9df..5260bb98602b 100644 --- a/persistence-modules/r2dbc/pom.xml +++ b/persistence-modules/r2dbc/pom.xml @@ -89,9 +89,9 @@ - 9.14.1 - 42.5.2 - 1.0.0.RELEASE + 9.16.0 + 42.5.4 + 1.0.1.RELEASE diff --git a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/DatasourceConfig.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/DatasourceConfig.java index 21cc0bc6d31d..29e7df4c293e 100644 --- a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/DatasourceConfig.java +++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/DatasourceConfig.java @@ -29,9 +29,8 @@ public ConnectionFactory connectionFactory(R2DBCConfigurationProperties properti if ( !StringUtil.isNullOrEmpty(properties.getPassword())) { ob = ob.option(PASSWORD, properties.getPassword()); } - - ConnectionFactory cf = ConnectionFactories.get(ob.build()); - return cf; + + return ConnectionFactories.get(ob.build()); } diff --git a/persistence-modules/r2dbc/src/main/resources/application.yml b/persistence-modules/r2dbc/src/main/resources/application.yml index 919a08820935..d89fffaa31b5 100644 --- a/persistence-modules/r2dbc/src/main/resources/application.yml +++ b/persistence-modules/r2dbc/src/main/resources/application.yml @@ -9,6 +9,8 @@ spring: flyway: url: jdbc:postgresql://localhost:8082/flyway-test-db locations: classpath:db/postgres/migration + main: + allow-bean-definition-overriding: true # R2DBC URL r2dbc: url: r2dbc:h2:mem://./testdb diff --git a/persistence-modules/r2dbc/src/test/java/com/baeldung/examples/r2dbc/R2dbcExampleApplicationIntegrationTest.java b/persistence-modules/r2dbc/src/test/java/com/baeldung/examples/r2dbc/R2dbcExampleApplicationIntegrationTest.java index 7c3badc9767c..80c319cc6546 100644 --- a/persistence-modules/r2dbc/src/test/java/com/baeldung/examples/r2dbc/R2dbcExampleApplicationIntegrationTest.java +++ b/persistence-modules/r2dbc/src/test/java/com/baeldung/examples/r2dbc/R2dbcExampleApplicationIntegrationTest.java @@ -55,9 +55,7 @@ public void givenExistingAccountId_whenGetAccount_thenReturnExistingAccountInfo( .expectStatus() .isOk() .expectBody(Account.class) - .value((acc) -> { - assertThat(acc.getId(),is(1l)); - }); + .value((acc) -> assertThat(acc.getId(),is(1L))); } @Test @@ -71,9 +69,7 @@ public void givenDatabaseHasSomeAccounts_whenGetAccount_thenReturnExistingAccoun .expectStatus() .isOk() .expectBody(List.class) - .value((accounts) -> { - assertThat(accounts.size(),not(is(0))); - }); + .value((accounts) -> assertThat(accounts.size(),not(is(0)))); } @@ -89,9 +85,7 @@ public void givenNewAccountData_whenPostAccount_thenReturnNewAccountInfo() { .expectStatus() .is2xxSuccessful() .expectBody(Account.class) - .value((acc) -> { - assertThat(acc.getId(),is(notNullValue())); - }); + .value((acc) -> assertThat(acc.getId(),is(notNullValue()))); } diff --git a/persistence-modules/redis/pom.xml b/persistence-modules/redis/pom.xml index d1cb927c20f9..571487af3d06 100644 --- a/persistence-modules/redis/pom.xml +++ b/persistence-modules/redis/pom.xml @@ -56,9 +56,9 @@ 0.6 - 3.13.1 - 3.3.0 - 4.1.50.Final + 3.20.0 + 4.3.2 + 4.1.90.Final \ No newline at end of file diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/client/RedisClient.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/client/RedisClient.java index 72ff42ff74a1..abc095bcdf4b 100644 --- a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/client/RedisClient.java +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/client/RedisClient.java @@ -102,18 +102,18 @@ public Long zadd(final String key, final Map scoreMembers) { return 0L; } - public Set zrange(final String key, final long start, final long stop) { + public List zrange(final String key, final long start, final long stop) { try (Jedis jedis = jedisPool.getResource()) { return jedis.zrange(key, start, stop); } catch (Exception ex) { log.error("Exception caught in zrange", ex); } - return new HashSet(); + return new ArrayList<>(); } public String mset(final HashMap keysValues) { try (Jedis jedis = jedisPool.getResource()) { - ArrayList keysValuesArrayList = new ArrayList(); + ArrayList keysValuesArrayList = new ArrayList<>(); keysValues.forEach((key, value) -> { keysValuesArrayList.add(key); keysValuesArrayList.add(value); diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/iterator/RedisIterator.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/iterator/RedisIterator.java index 5fbd798ac2da..fd57e75f6f2f 100644 --- a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/iterator/RedisIterator.java +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/iterator/RedisIterator.java @@ -5,8 +5,8 @@ import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; import java.util.Iterator; import java.util.LinkedList; diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/ScanStrategy.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/ScanStrategy.java index 39d9e44a6362..5ebfd7c13555 100644 --- a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/ScanStrategy.java +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/ScanStrategy.java @@ -1,8 +1,8 @@ package com.baeldung.redis_scan.strategy; import redis.clients.jedis.Jedis; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; public interface ScanStrategy { ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams); diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Hscan.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Hscan.java index fd5ecd14ec47..2873229302b3 100644 --- a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Hscan.java +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Hscan.java @@ -2,8 +2,8 @@ import com.baeldung.redis_scan.strategy.ScanStrategy; import redis.clients.jedis.Jedis; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; import java.util.Map; import java.util.Map.Entry; diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Scan.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Scan.java index f28b56e34cb1..c3cf94ff1283 100644 --- a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Scan.java +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Scan.java @@ -2,8 +2,8 @@ import com.baeldung.redis_scan.strategy.ScanStrategy; import redis.clients.jedis.Jedis; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; public class Scan implements ScanStrategy { diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Sscan.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Sscan.java index ed47f7087e31..aa5e58bf67a1 100644 --- a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Sscan.java +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Sscan.java @@ -2,8 +2,8 @@ import com.baeldung.redis_scan.strategy.ScanStrategy; import redis.clients.jedis.Jedis; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; public class Sscan implements ScanStrategy { diff --git a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Zscan.java b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Zscan.java index bdffc15883bc..a540e69f17fa 100644 --- a/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Zscan.java +++ b/persistence-modules/redis/src/main/java/com/baeldung/redis_scan/strategy/impl/Zscan.java @@ -2,9 +2,9 @@ import com.baeldung.redis_scan.strategy.ScanStrategy; import redis.clients.jedis.Jedis; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; -import redis.clients.jedis.Tuple; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.resps.Tuple; public class Zscan implements ScanStrategy { diff --git a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java index 50d28af3d1a6..664ed1d0c3ba 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java @@ -4,6 +4,7 @@ import java.net.ServerSocket; import java.time.Duration; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Set; @@ -35,7 +36,10 @@ public static void setUp() throws IOException { port = s.getLocalPort(); s.close(); - redisServer = new RedisServer(port); + redisServer = RedisServer.builder() + .port(port) + .setting("maxheap 128M") + .build(); redisServer.start(); // Configure JEDIS @@ -148,7 +152,7 @@ public void givenARanking_thenSaveItInRedisSortedSet() { jedis.zadd(key, playerScore.getValue(), playerScore.getKey()); }); - Set players = jedis.zrevrange(key, 0, 1); + List players = jedis.zrevrange(key, 0, 1); Assert.assertEquals("PlayerThree", players.iterator().next()); long rank = jedis.zrevrank(key, "PlayerOne"); @@ -184,7 +188,7 @@ public void givenMultipleIndependentOperations_whenNetworkOptimizationIsImportan p.zadd("ranking", 126, userOneId); p.zadd("ranking", 325, userTwoId); Response pipeExists = p.sismember("searched#" + userOneId, "paris"); - Response> pipeRanking = p.zrange("ranking", 0, -1); + Response> pipeRanking = p.zrange("ranking", 0, -1); p.sync(); Assert.assertTrue(pipeExists.get()); diff --git a/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java index c2e771d7b87c..b80cae98d807 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java @@ -32,7 +32,10 @@ public static void setUp() throws IOException { port = s.getLocalPort(); s.close(); - redisServer = new RedisServer(port); + redisServer = RedisServer.builder() + .port(port) + .setting("maxheap 128M") + .build(); redisServer.start(); } diff --git a/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java index 8c8e6a02ddfa..79581df98992 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java @@ -29,8 +29,11 @@ public class RedissonIntegrationTest { private static RedissonClient client; @BeforeClass - public static void setUp() throws IOException { - redisServer = new RedisServer(6379); + public static void setUp() { + redisServer = RedisServer.builder() + .port(6379) + .setting("maxheap 128M") + .build(); redisServer.start(); client = Redisson.create(); } diff --git a/persistence-modules/redis/src/test/java/com/baeldung/redis/deleteeverything/DeleteEverythingInRedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/redis/deleteeverything/DeleteEverythingInRedisIntegrationTest.java index e0376fc6a58e..54123afdea22 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/redis/deleteeverything/DeleteEverythingInRedisIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/redis/deleteeverything/DeleteEverythingInRedisIntegrationTest.java @@ -23,7 +23,10 @@ public void setUp() throws IOException { port = s.getLocalPort(); s.close(); - redisServer = new RedisServer(port); + redisServer = RedisServer.builder() + .port(port) + .setting("maxheap 128M") + .build(); redisServer.start(); // Configure JEDIS diff --git a/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java index 9bf0b2b0868c..5c325e8ea0f3 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java @@ -8,6 +8,7 @@ import java.net.ServerSocket; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; @@ -24,7 +25,10 @@ public static void setUp() throws IOException { port = s.getLocalPort(); s.close(); - redisServer = new RedisServer(port); + redisServer = RedisServer.builder() + .port(port) + .setting("maxheap 128M") + .build(); } @AfterClass @@ -50,7 +54,7 @@ public void flushAll() { @Test public void testKeys() { - HashMap keyValues = new HashMap(); + HashMap keyValues = new HashMap<>(); keyValues.put("balls:cricket", "160"); keyValues.put("balls:football", "450"); keyValues.put("balls:volleyball", "270"); @@ -62,7 +66,7 @@ public void testKeys() { @Test public void testSmembers() { - HashSet setMembers = new HashSet(); + HashSet setMembers = new HashSet<>(); setMembers.add("cricket_160"); setMembers.add("football_450"); setMembers.add("volleyball_270"); @@ -73,7 +77,7 @@ public void testSmembers() { @Test public void testHgetAll() { - HashMap keyValues = new HashMap(); + HashMap keyValues = new HashMap<>(); keyValues.put("balls:cricket", "160"); keyValues.put("balls:football", "450"); keyValues.put("balls:volleyball", "270"); @@ -84,12 +88,12 @@ public void testHgetAll() { @Test public void testZRange() { - HashMap scoreMembers = new HashMap(); + HashMap scoreMembers = new HashMap<>(); scoreMembers.put("cricket", (double) 160); scoreMembers.put("football", (double) 450); scoreMembers.put("volleyball", (double) 270); redisClient.zadd("balls", scoreMembers); - Set readSetMembers = redisClient.zrange("balls", 0, -1); + List readSetMembers = redisClient.zrange("balls", 0, -1); Assert.assertEquals(readSetMembers.size(), scoreMembers.size()); } diff --git a/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java index 9bde969b5806..838d0144dc6e 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java @@ -8,7 +8,7 @@ import com.baeldung.redis_scan.strategy.impl.Sscan; import com.baeldung.redis_scan.strategy.impl.Zscan; import org.junit.*; -import redis.clients.jedis.Tuple; +import redis.clients.jedis.resps.Tuple; import redis.embedded.RedisServer; import java.io.IOException; @@ -31,7 +31,10 @@ public static void setUp() throws IOException { port = s.getLocalPort(); s.close(); - redisServer = new RedisServer(port); + redisServer = RedisServer.builder() + .port(port) + .setting("maxheap 128M") + .build(); } @AfterClass @@ -57,7 +60,7 @@ public void flushAll() { @Test public void testScanStrategy() { - HashMap keyValues = new HashMap(); + HashMap keyValues = new HashMap<>(); keyValues.put("balls:cricket", "160"); keyValues.put("balls:football", "450"); keyValues.put("balls:volleyball", "270"); @@ -66,7 +69,7 @@ public void testScanStrategy() { ScanStrategy scanStrategy = new Scan(); int iterationCount = 2; RedisIterator iterator = redisClient.iterator(iterationCount, "ball*", scanStrategy); - List results = new LinkedList(); + List results = new LinkedList<>(); while (iterator.hasNext()) { results.addAll(iterator.next()); } @@ -84,7 +87,7 @@ public void testSscanStrategy() { Sscan scanStrategy = new Sscan("balls"); int iterationCount = 2; RedisIterator iterator = redisClient.iterator(iterationCount, "*", scanStrategy); - List results = new LinkedList(); + List results = new LinkedList<>(); while (iterator.hasNext()) { results.addAll(iterator.next()); } @@ -93,7 +96,7 @@ public void testSscanStrategy() { @Test public void testHscanStrategy() { - HashMap hash = new HashMap(); + HashMap hash = new HashMap<>(); hash.put("cricket", "160"); hash.put("football", "450"); hash.put("volleyball", "270"); @@ -102,7 +105,7 @@ public void testHscanStrategy() { Hscan scanStrategy = new Hscan("balls"); int iterationCount = 2; RedisIterator iterator = redisClient.iterator(iterationCount, "*", scanStrategy); - List> results = new LinkedList>(); + List> results = new LinkedList<>(); while (iterator.hasNext()) { results.addAll(iterator.next()); } @@ -111,7 +114,7 @@ public void testHscanStrategy() { @Test public void testZscanStrategy() { - HashMap memberScores = new HashMap(); + HashMap memberScores = new HashMap<>(); memberScores.put("cricket", (double) 160); memberScores.put("football", (double) 450); memberScores.put("volleyball", (double) 270); @@ -120,7 +123,7 @@ public void testZscanStrategy() { Zscan scanStrategy = new Zscan("balls"); int iterationCount = 2; RedisIterator iterator = redisClient.iterator(iterationCount, "*", scanStrategy); - List results = new LinkedList(); + List results = new LinkedList<>(); while (iterator.hasNext()) { results.addAll(iterator.next()); } diff --git a/persistence-modules/scylladb/pom.xml b/persistence-modules/scylladb/pom.xml index e457c75d91b0..f84db877425a 100644 --- a/persistence-modules/scylladb/pom.xml +++ b/persistence-modules/scylladb/pom.xml @@ -1,85 +1,86 @@ - - 4.0.0 - com.baeldung.examples.scylladb - scylladb - 0.0.1-SNAPSHOT - scylladb - Sample ScyllaDB Project - - 1.17.6 - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - org.springframework.boot - spring-boot-starter - - - com.scylladb - java-driver-core - 4.14.1.0 - - - com.scylladb - java-driver-query-builder - 4.14.1.0 - + + 4.0.0 + com.baeldung.examples.scylladb + scylladb + 0.0.1-SNAPSHOT + scylladb + Sample ScyllaDB Project + + 1.17.6 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + org.springframework.boot + spring-boot-starter + + + com.scylladb + java-driver-core + 4.14.1.0 + + + com.scylladb + java-driver-query-builder + 4.14.1.0 + - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - - org.testcontainers - testcontainers - test - - - org.testcontainers - junit-jupiter - test - - - - - - org.testcontainers - testcontainers-bom - ${testcontainers.version} - pom - import - - - + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.testcontainers + testcontainers + test + + + org.testcontainers + junit-jupiter + test + + + + + + org.testcontainers + testcontainers-bom + ${testcontainers.version} + pom + import + + + - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.projectlombok - lombok - - - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml index 1a02b18e5034..260c558875d7 100644 --- a/persistence-modules/spring-boot-persistence-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-2/pom.xml @@ -17,13 +17,6 @@ - - org.junit - junit-bom - ${junit-jupiter.version} - pom - import - org.springframework.boot spring-boot-dependencies @@ -33,7 +26,7 @@ org.jdbi - jdbi3-spring4 + jdbi3-spring5 ${jdbi.version} @@ -55,7 +48,7 @@ org.jdbi - jdbi3-spring4 + jdbi3-spring5 org.jdbi @@ -103,6 +96,7 @@ mysql mysql-connector-java + ${mysql-connector-java.version} org.xerial @@ -143,10 +137,14 @@ - 3.9.1 - 2.1.8.RELEASE - 0.9.5.2 - 21.1.0.0 + 3.38.0 + 3.0.5 + 0.9.5.5 + 21.9.0.0 + + 2.0.7 + 1.4.6 + 8.0.33 \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java index ddbe6cc1187f..d744a46f3fb4 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java @@ -31,11 +31,11 @@ public Jdbi jdbi(DataSource ds,List jdbiPlugins, List> // Register all available plugins log.info("[I27] Installing plugins... ({} found)", jdbiPlugins.size()); - jdbiPlugins.forEach(plugin -> jdbi.installPlugin(plugin)); + jdbiPlugins.forEach(jdbi::installPlugin); // Register all available rowMappers log.info("[I31] Installing rowMappers... ({} found)", rowMappers.size()); - rowMappers.forEach(mapper -> jdbi.registerRowMapper(mapper)); + rowMappers.forEach(jdbi::registerRowMapper); return jdbi; } diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java index 80b615801bf6..36cfd59b6d3e 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java @@ -8,7 +8,7 @@ public class CarModel { private Long id; private String name; - private Integer year; + private Integer yearDate; private String sku; private Long makerId; } diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java index eeceafd6499a..b2311ef6a95b 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java @@ -18,7 +18,7 @@ public CarModel map(ResultSet rs, StatementContext ctx) throws SQLException { .id(rs.getLong("id")) .name(rs.getString("name")) .sku(rs.getString("sku")) - .year(rs.getInt("year")) + .yearDate(rs.getInt("year")) .build(); } diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/db/indexing/Image.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/db/indexing/Image.java index e3fcf53f819c..7c7a558777df 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/db/indexing/Image.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/db/indexing/Image.java @@ -1,9 +1,9 @@ package com.baeldung.db.indexing; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Lob; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Lob; @Entity class Image { diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java index fb2c3fcf6aa7..af4199e65ba2 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java @@ -1,9 +1,9 @@ package com.baeldung.spring.oracle.pooling.entity; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Book { diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java index ee2735abb8d0..cd4fafb60f38 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java @@ -1,10 +1,10 @@ package com.baeldung.springboothsqldb.application.entities; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "customers") diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntity.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntity.java index 90bd275240ea..8c3494d1e4e4 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntity.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntity.java @@ -5,9 +5,9 @@ import lombok.NoArgsConstructor; import lombok.Setter; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; @Entity @AllArgsConstructor diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntityWithCascade.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntityWithCascade.java index de0d62bfe2b5..ada6b87ae34d 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntityWithCascade.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntityWithCascade.java @@ -5,10 +5,10 @@ import lombok.NoArgsConstructor; import lombok.Setter; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; @Entity @AllArgsConstructor diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java index 712506eb9824..02af097dc026 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java @@ -1,11 +1,11 @@ package com.baeldung.tomcatconnectionpool.application.entities; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "customers") diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql index 0e045d727436..0b1a93158bfc 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql @@ -1,4 +1,4 @@ -- -- Insert -- -insert into car_maker(id,name) values (:id,:name); +insert into car_maker(name) values (:name); diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql index b27721358404..6bca3a0d6d9f 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql @@ -1,8 +1,8 @@ -- -- Insert -- -insert into car_model(maker_fk,name,sku,year) values ( +insert into car_model(maker_fk,name,sku,yearDate) values ( :makerId, :name, :sku, - :year ); + :yearDate ); diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java index ac5661afbccb..948d197f145a 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java @@ -76,7 +76,7 @@ public void givenNewCarMakers_whenInsertNewCarMakers_thenSuccess() { @Test public void givenExistingCarMaker_whenFindById_thenReturnExistingCarMaker() { - CarMaker maker = carMakerDao.findById(1l); + CarMaker maker = carMakerDao.findById(1L); assertThat(maker).isNotNull(); assertThat(maker.getId()).isEqualTo(1); @@ -85,12 +85,12 @@ public void givenExistingCarMaker_whenFindById_thenReturnExistingCarMaker() { @Test public void givenExistingCarMaker_whenBulkInsertFails_thenRollback() { - CarMaker maker = carMakerDao.findById(1l); + CarMaker maker = carMakerDao.findById(1L); CarModel m1 = CarModel.builder() .makerId(maker.getId()) .name("Model X1") .sku("1-M1") - .year(2019) + .yearDate(2019) .build(); maker.getModels().add(m1); @@ -98,7 +98,7 @@ public void givenExistingCarMaker_whenBulkInsertFails_thenRollback() { .makerId(maker.getId()) .name("Model X1") .sku("1-M1") - .year(2019) + .yearDate(2019) .build(); maker.getModels().add(m2); diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/FileSystemImageIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/FileSystemImageIntegrationTest.java index 83f5bae095bd..809d04cc969d 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/FileSystemImageIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/FileSystemImageIntegrationTest.java @@ -4,8 +4,10 @@ import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import java.io.File; import java.io.InputStream; -import java.nio.file.Paths; +import java.net.URISyntaxException; +import java.net.URL; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -64,10 +66,13 @@ void givenBaeldungImage_whenDownloadIt_thenReturnTheImage() throws Exception { private FileSystemResource baeldungJpegResource() { ClassLoader classLoader = ClassLoader.getSystemClassLoader(); - String imagePath = classLoader.getResource("baeldung.jpeg") - .getFile(); - - return new FileSystemResource(Paths.get(imagePath)); + try { + final URL resource = classLoader.getResource("baeldung.jpeg"); + if (resource != null) { + return new FileSystemResource(new File(resource.toURI()).getAbsolutePath()); + } + } catch (URISyntaxException ignore) {} + return null; } } diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/ImageIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/ImageIntegrationTest.java index e38e0a21a9fa..09e13aefd4b1 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/ImageIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/ImageIntegrationTest.java @@ -7,6 +7,8 @@ import java.io.IOException; import java.io.InputStream; +import java.net.URISyntaxException; +import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Optional; @@ -68,11 +70,15 @@ private MockMultipartHttpServletRequestBuilder createUploadImageRequest() throws private Image baeldungImage() throws IOException { ClassLoader classLoader = ClassLoader.getSystemClassLoader(); - - Image mockImage = new Image(); - mockImage.setContent(Files.readAllBytes(Paths.get(classLoader.getResource("baeldung.jpeg") - .getFile()))); - return mockImage; + try { + final URL resource = classLoader.getResource("baeldung.jpeg"); + if (resource != null) { + Image mockImage = new Image(); + mockImage.setContent(Files.readAllBytes(Paths.get(resource.toURI()))); + return mockImage; + } + } catch (URISyntaxException ignore) {} + return null; } } diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java index 6956df0b1322..bdd9a19b682f 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java @@ -29,8 +29,7 @@ public class CustomerControllerIntegrationTest { @Before public void setUpJsonMediaType() { - MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - + MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype()); } @Test diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/states/UserEntityIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/states/UserEntityIntegrationTest.java index 5d0dc99ad71c..0ce3ff34ce9b 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/states/UserEntityIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/states/UserEntityIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManagerFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql b/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql index e3e1f4ae3233..fb97140b4837 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql +++ b/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql @@ -1,12 +1,12 @@ -insert into car_maker(id,name) values (1,'Special Motors'); -insert into car_maker(id,name) values (2,'BWM'); -insert into car_maker(id,name) values (3,'Dolores'); +insert into car_maker(id,name) values (99,'Special Motors'); +insert into car_maker(id,name) values (100,'BWM'); +insert into car_maker(id,name) values (102,'Dolores'); -insert into car_model(id,maker_fk,name,sku,year) values(1,1,'Muze','SM001',2018); -insert into car_model(id,maker_fk,name,sku,year) values(2,1,'Empada','SM002',2008); +insert into car_model(id,maker_fk,name,sku,yearDate) values(132,99,'Muze','SM001',2018); +insert into car_model(id,maker_fk,name,sku,yearDate) values(145,99,'Empada','SM002',2008); -insert into car_model(id,maker_fk,name,sku,year) values(4,2,'BWM-100','BWM100',2008); -insert into car_model(id,maker_fk,name,sku,year) values(5,2,'BWM-200','BWM200',2009); -insert into car_model(id,maker_fk,name,sku,year) values(6,2,'BWM-300','BWM300',2008); +insert into car_model(id,maker_fk,name,sku,yearDate) values(43,100,'BWM-100','BWM100',2008); +insert into car_model(id,maker_fk,name,sku,yearDate) values(564,100,'BWM-200','BWM200',2009); +insert into car_model(id,maker_fk,name,sku,yearDate) values(343,100,'BWM-300','BWM300',2008); diff --git a/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql b/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql index 8d7db6c9f3f8..72f9e606de51 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql +++ b/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql @@ -19,9 +19,9 @@ create table car_model( maker_fk int not null, name varchar(128) not null, sku varchar(128) not null, - year int not null + yearDate int not null ); create unique index ui_car_model_01 on car_model(maker_fk,sku); -create unique index ui_car_model_02 on car_model(maker_fk,name,year); +create unique index ui_car_model_02 on car_model(maker_fk,name,yearDate); diff --git a/persistence-modules/spring-boot-persistence-h2/README.md b/persistence-modules/spring-boot-persistence-h2/README.md index 1d47907a9834..7f6e243677e7 100644 --- a/persistence-modules/spring-boot-persistence-h2/README.md +++ b/persistence-modules/spring-boot-persistence-h2/README.md @@ -5,3 +5,4 @@ - [Hibernate @NotNull vs @Column(nullable = false)](https://www.baeldung.com/hibernate-notnull-vs-nullable) - [Quick Guide to Hibernate enable_lazy_load_no_trans Property](https://www.baeldung.com/hibernate-lazy-loading-workaround) - [Where Does H2’s Embedded Database Store The Data?](https://www.baeldung.com/h2-embedded-db-data-storage) +- [Spring Boot H2 JdbcSQLSyntaxErrorException expected “identifier”](https://www.baeldung.com/spring-boot-h2-jdbcsqlsyntaxerrorexception-expected-identifier) diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/SpringBootH2Exceptions.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/SpringBootH2Exceptions.java new file mode 100644 index 000000000000..c7684423a20d --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/SpringBootH2Exceptions.java @@ -0,0 +1,15 @@ +package com.baeldung.h2.exceptions; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +@PropertySource("classpath:app-h2.properties") +public class SpringBootH2Exceptions { + + public static void main(String... args) { + SpringApplication.run(SpringBootH2Exceptions.class, args); + } + +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/models/User.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/models/User.java new file mode 100644 index 000000000000..e54e725fd015 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/models/User.java @@ -0,0 +1,38 @@ +package com.baeldung.h2.exceptions.models; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class User { + + @Id + private int id; + private String login; + private String password; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/repos/UserRepository.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/repos/UserRepository.java new file mode 100644 index 000000000000..d014fb16c657 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/repos/UserRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.h2.exceptions.repos; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.h2.exceptions.models.User; + +@Repository +public interface UserRepository extends JpaRepository { + +} diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/app-h2.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/app-h2.properties new file mode 100644 index 000000000000..bb88e7fef4f0 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/app-h2.properties @@ -0,0 +1 @@ +spring.sql.init.data-locations=user-data.sql diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/user-data.sql b/persistence-modules/spring-boot-persistence-h2/src/main/resources/user-data.sql new file mode 100644 index 000000000000..cea758c74e3c --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/user-data.sql @@ -0,0 +1,8 @@ +/* These commented lines will cause Spring Boot to fail at startup + * + * INSERT INTO user VALUES (1, 'admin', 'p@ssw@rd'); + * INSERT INTO user VALUES (2, 'user', 'userpasswd'); + * +*/ +INSERT INTO "user" VALUES (1, 'admin', 'p@ssw@rd'); +INSERT INTO "user" VALUES (2, 'user', 'userpasswd'); \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/h2/exceptions/SpringBootH2ExceptionsIntegrationTest.java b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/h2/exceptions/SpringBootH2ExceptionsIntegrationTest.java new file mode 100644 index 000000000000..94cf08fb7686 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/h2/exceptions/SpringBootH2ExceptionsIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.h2.exceptions; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.junit.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; + +import com.baeldung.h2.exceptions.models.User; +import com.baeldung.h2.exceptions.repos.UserRepository; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootH2Exceptions.class) +public class SpringBootH2ExceptionsIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Test + public void givenValidInitData_whenCallingFindAll_thenReturnData() { + List users = userRepository.findAll(); + + assertThat(users).hasSize(2); + } + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml b/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml index cd7198b9312c..121581498a31 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml @@ -5,7 +5,6 @@ 4.0.0 spring-boot-persistence-mongodb-2 spring-boot-persistence-mongodb-2 - war This is simple boot application for Spring boot persistence mongodb test diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/pom.xml b/persistence-modules/spring-boot-persistence-mongodb-3/pom.xml index b9a47aa70323..c48525673a1b 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/pom.xml +++ b/persistence-modules/spring-boot-persistence-mongodb-3/pom.xml @@ -5,7 +5,6 @@ 4.0.0 spring-boot-persistence-mongodb-3 spring-boot-persistence-mongodb-3 - war This is simple boot application for Spring boot persistence mongodb @@ -16,6 +15,21 @@ + + org.mongodb + mongodb-driver-sync + ${mongodb-driver.version} + + + org.mongodb + mongodb-driver-core + ${mongodb-driver.version} + + + org.mongodb + bson + ${mongodb-driver.version} + org.springframework.boot spring-boot-starter-web @@ -23,11 +37,21 @@ org.springframework.boot spring-boot-starter-data-mongodb + + + org.mongodb + mongodb-driver-sync + + + org.mongodb + mongodb-driver-core + + - - org.mongodb - mongodb-crypt - ${mongodb-crypt.version} + + org.mongodb + mongodb-crypt + ${mongodb-crypt.version} de.flapdoodle.embed @@ -37,7 +61,8 @@ - 1.6.1 + 1.7.3 + 4.9.1 - + diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/EncryptionConfig.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/EncryptionConfig.java index 0ff97eb6c143..1a74340057ee 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/EncryptionConfig.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/EncryptionConfig.java @@ -1,5 +1,7 @@ package com.baeldung.boot.csfle.config; +import java.io.File; + import org.bson.BsonBinary; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; @@ -17,7 +19,13 @@ public class EncryptionConfig { private String keyVaultAlias; @Value("${com.baeldung.csfle.auto-decryption:false}") - private Boolean autoDecryption; + private boolean autoDecryption; + + @Value("${com.baeldung.csfle.auto-encryption:false}") + private boolean autoEncryption; + + @Value("${com.baeldung.csfle.auto-encryption-lib:#{null}}") + private File autoEncryptionLib; private BsonBinary dataKeyId; @@ -41,7 +49,23 @@ public String getMasterKeyPath() { return masterKeyPath; } - public Boolean getAutoDecryption() { + public boolean isAutoDecryption() { return autoDecryption; } + + public boolean isAutoEncryption() { + return autoEncryption; + } + + public File getAutoEncryptionLib() { + return autoEncryptionLib; + } + + public String dataKeyIdUuid() { + if (dataKeyId == null) + throw new IllegalStateException("data key not initialized"); + + return dataKeyId.asUuid() + .toString(); + } } diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java index 0dff1ec86db8..19d0af08b2fb 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java @@ -1,14 +1,15 @@ package com.baeldung.boot.csfle.config; +import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; +import java.util.HashMap; import java.util.Map; import org.bson.BsonBinary; import org.bson.BsonDocument; import org.bson.Document; -import org.bson.conversions.Bson; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; @@ -51,14 +52,10 @@ protected String getDatabaseName() { @Bean @Override public MongoClient mongoClient() { - MongoClient client; try { - client = MongoClients.create(clientSettings()); - ClientEncryption encryption = clientEncryption(); - encryptionConfig.setDataKeyId(createOrRetrieveDataKey(client, encryption)); - - return client; + encryptionConfig.setDataKeyId(createOrRetrieveDataKey(encryption)); + return MongoClients.create(clientSettings()); } catch (IOException e) { throw new IllegalStateException("unable to create client", e); } @@ -77,19 +74,10 @@ public ClientEncryption clientEncryption() throws FileNotFoundException, IOExcep return ClientEncryptions.create(encryptionSettings); } - private BsonBinary createOrRetrieveDataKey(MongoClient client, ClientEncryption encryption) { - MongoNamespace namespace = new MongoNamespace(encryptionConfig.getKeyVaultNamespace()); - MongoCollection keyVault = client.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - Bson query = Filters.in("keyAltNames", encryptionConfig.getKeyVaultAlias()); - BsonDocument key = keyVault.withDocumentClass(BsonDocument.class) - .find(query) - .first(); - + private BsonBinary createOrRetrieveDataKey(ClientEncryption encryption) { + BsonDocument key = encryption.getKeyByAltName(encryptionConfig.getKeyVaultAlias()); if (key == null) { - keyVault.createIndex(Indexes.ascending("keyAltNames"), new IndexOptions().unique(true) - .partialFilterExpression(Filters.exists("keyAltNames"))); + createKeyUniqueIndex(); DataKeyOptions options = new DataKeyOptions(); options.keyAltNames(Arrays.asList(encryptionConfig.getKeyVaultAlias())); @@ -99,16 +87,68 @@ private BsonBinary createOrRetrieveDataKey(MongoClient client, ClientEncryption } } + private void createKeyUniqueIndex() { + try (MongoClient client = MongoClients.create(MongoClientSettings.builder() + .applyConnectionString(new ConnectionString(uri)) + .build())) { + MongoNamespace namespace = new MongoNamespace(encryptionConfig.getKeyVaultNamespace()); + MongoCollection keyVault = client.getDatabase(namespace.getDatabaseName()) + .getCollection(namespace.getCollectionName()); + + keyVault.createIndex(Indexes.ascending("keyAltNames"), new IndexOptions().unique(true) + .partialFilterExpression(Filters.exists("keyAltNames"))); + } + } + private MongoClientSettings clientSettings() throws FileNotFoundException, IOException { Builder settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString(uri)); - if (encryptionConfig.getAutoDecryption()) { - settings.autoEncryptionSettings(AutoEncryptionSettings.builder() + if (encryptionConfig.isAutoDecryption()) { + AutoEncryptionSettings.Builder builder = AutoEncryptionSettings.builder() .keyVaultNamespace(encryptionConfig.getKeyVaultNamespace()) - .kmsProviders(LocalKmsUtils.providersMap(encryptionConfig.getMasterKeyPath())) - .bypassAutoEncryption(true) - .build()); + .kmsProviders(LocalKmsUtils.providersMap(encryptionConfig.getMasterKeyPath())); + + if (encryptionConfig.isAutoEncryption() && encryptionConfig.getDataKeyId() != null) { + File autoEncryptionLib = encryptionConfig.getAutoEncryptionLib(); + if (!autoEncryptionLib.isFile()) { + throw new IllegalArgumentException("encryption lib must be an existing file"); + } + + Map map = new HashMap<>(); + map.put("cryptSharedLibRequired", true); + map.put("cryptSharedLibPath", autoEncryptionLib.toString()); + builder.extraOptions(map); + + String keyUuid = encryptionConfig.dataKeyIdUuid(); + HashMap schemaMap = new HashMap<>(); + schemaMap.put(getDatabaseName() + ".citizens", + BsonDocument.parse("{" + + " bsonType: \"object\"," + + " encryptMetadata: {" + + " keyId: [UUID(\"" + keyUuid + "\")]" + + " }," + + " properties: {" + + " email: {" + + " encrypt: {" + + " bsonType: \"string\"," + + " algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic\"" + + " }" + + " }," + + " birthYear: {" + + " encrypt: {" + + " bsonType: \"int\"," + + " algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Random\"" + + " }" + + " }" + + " }" + + "}")); + builder.schemaMap(schemaMap); + } else { + builder.bypassAutoEncryption(true); + } + + settings.autoEncryptionSettings(builder.build()); } return settings.build(); diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java index 6b3c463d0de6..c93b00f3f887 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java @@ -35,16 +35,20 @@ public class CitizenService { @Autowired private ClientEncryption clientEncryption; - public EncryptedCitizen save(Citizen citizen) { - EncryptedCitizen encryptedCitizen = new EncryptedCitizen(citizen); - encryptedCitizen.setEmail(encrypt(citizen.getEmail(), DETERMINISTIC_ALGORITHM)); - encryptedCitizen.setBirthYear(encrypt(citizen.getBirthYear(), RANDOM_ALGORITHM)); + public Object save(Citizen citizen) { + if (encryptionConfig.isAutoEncryption()) { + return mongo.save(citizen); + } else { + EncryptedCitizen encryptedCitizen = new EncryptedCitizen(citizen); + encryptedCitizen.setEmail(encrypt(citizen.getEmail(), DETERMINISTIC_ALGORITHM)); + encryptedCitizen.setBirthYear(encrypt(citizen.getBirthYear(), RANDOM_ALGORITHM)); - return mongo.save(encryptedCitizen); + return mongo.save(encryptedCitizen); + } } public List findAll() { - if (!encryptionConfig.getAutoDecryption()) { + if (!encryptionConfig.isAutoDecryption()) { List allEncrypted = mongo.findAll(EncryptedCitizen.class); return allEncrypted.stream() @@ -56,13 +60,20 @@ public List findAll() { } public Citizen findByEmail(String email) { - Query byEmail = new Query(Criteria.where("email") - .is(encrypt(email, DETERMINISTIC_ALGORITHM))); - if (!encryptionConfig.getAutoDecryption()) { - EncryptedCitizen encryptedCitizen = mongo.findOne(byEmail, EncryptedCitizen.class); - return decrypt(encryptedCitizen); + Criteria emailCriteria = Criteria.where("email"); + if (encryptionConfig.isAutoEncryption()) { + emailCriteria.is(email); } else { + emailCriteria + .is(encrypt(email, DETERMINISTIC_ALGORITHM)); + } + + Query byEmail = new Query(emailCriteria); + if (encryptionConfig.isAutoDecryption()) { return mongo.findOne(byEmail, Citizen.class); + } else { + EncryptedCitizen encryptedCitizen = mongo.findOne(byEmail, EncryptedCitizen.class); + return decrypt(encryptedCitizen); } } diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/web/CitizenController.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/web/CitizenController.java index d17435fb5ee5..7a2b2605cd2a 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/web/CitizenController.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/web/CitizenController.java @@ -11,7 +11,6 @@ import org.springframework.web.bind.annotation.RestController; import com.baeldung.boot.csfle.data.Citizen; -import com.baeldung.boot.csfle.data.EncryptedCitizen; import com.baeldung.boot.csfle.service.CitizenService; @RestController @@ -32,7 +31,7 @@ public Citizen getBy(@RequestParam String email) { } @PostMapping - public EncryptedCitizen post(@RequestBody Citizen citizen) { + public Object post(@RequestBody Citizen citizen) { return service.save(citizen); } } diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/csfle/CitizenServiceLiveTest.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/csfle/CitizenServiceLiveTest.java index 471cb2883af8..d57da4375183 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/csfle/CitizenServiceLiveTest.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/csfle/CitizenServiceLiveTest.java @@ -38,10 +38,14 @@ public void givenCitizen_whenEncryptingEmail_thenEncryptedCitizenEmailMatches() citizen.setName("Foo"); citizen.setEmail("foo@citizen.com"); - Binary encryptedEmail = service.encrypt(citizen.getEmail(), CitizenService.DETERMINISTIC_ALGORITHM); - - EncryptedCitizen saved = service.save(citizen); - assertEquals(encryptedEmail, saved.getEmail()); + Object saved = service.save(citizen); + if (saved instanceof EncryptedCitizen) { + Binary encryptedEmail = service.encrypt(citizen.getEmail(), CitizenService.DETERMINISTIC_ALGORITHM); + + assertEquals(encryptedEmail, ((EncryptedCitizen) saved).getEmail()); + } else { + assertEquals(citizen.getEmail(), ((Citizen) saved).getEmail()); + } } @Test diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/test/resources/embedded.properties b/persistence-modules/spring-boot-persistence-mongodb-3/src/test/resources/embedded.properties index 5325354e5591..cd1c1d43c772 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/test/resources/embedded.properties +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/test/resources/embedded.properties @@ -1,10 +1,10 @@ spring.mongodb.embedded.version=4.4.9 -spring.data.mongodb.uri=changeit -spring.data.mongodb.database=changeit +#spring.data.mongodb.uri=changeit +#spring.data.mongodb.database=changeit com.baeldung.csfle.kms-provider=local com.baeldung.csfle.key-vault.namespace=encryption._keyVault com.baeldung.csfle.key-vault.alias=master.key -com.baeldung.csfle.master-key-path=/tmp/master.key +#com.baeldung.csfle.master-key-path=/tmp/master.key com.baeldung.csfle.auto-decryption=false diff --git a/persistence-modules/spring-boot-persistence-mongodb/pom.xml b/persistence-modules/spring-boot-persistence-mongodb/pom.xml index 724fa38f7ed8..aae307f7f855 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/pom.xml +++ b/persistence-modules/spring-boot-persistence-mongodb/pom.xml @@ -5,7 +5,6 @@ 4.0.0 spring-boot-persistence-mongodb spring-boot-persistence-mongodb - war This is simple boot application for Spring boot persistence mongodb test diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dataloading/ApplicationDataLoading.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dataloading/ApplicationDataLoading.java new file mode 100644 index 000000000000..40742d303e7b --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dataloading/ApplicationDataLoading.java @@ -0,0 +1,16 @@ +package com.baeldung.dataloading; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.core.env.AbstractEnvironment; + +@SpringBootApplication(scanBasePackages = { "com.baeldung.dataloading" }) +public class ApplicationDataLoading { + + public static void main(String[] args) { + System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "datasource"); + + SpringApplication.run(ApplicationDataLoading.class, args); + } + +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dataloading/model/Country.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dataloading/model/Country.java new file mode 100644 index 000000000000..692d48caf023 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dataloading/model/Country.java @@ -0,0 +1,36 @@ +package com.baeldung.dataloading.model; + +import static javax.persistence.GenerationType.IDENTITY; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Country { + + @Id + @GeneratedValue(strategy = IDENTITY) + private Integer id; + + @Column(nullable = false) + private String name; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/application-datasource.properties b/persistence-modules/spring-boot-persistence/src/main/resources/application-datasource.properties new file mode 100644 index 000000000000..98cf2ba96568 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/resources/application-datasource.properties @@ -0,0 +1,14 @@ +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.hibernate.ddl-auto=create +spring.jpa.defer-datasource-initialization=true + +# Enabling H2 Console +spring.h2.console.enabled=true + +# By default enabled for Embedded Databases +#spring.sql.init.mode=always \ No newline at end of file diff --git a/persistence-modules/spring-data-couchbase-2/pom.xml b/persistence-modules/spring-data-couchbase-2/pom.xml index c860f809fdad..deb7d3b52491 100644 --- a/persistence-modules/spring-data-couchbase-2/pom.xml +++ b/persistence-modules/spring-data-couchbase-2/pom.xml @@ -57,23 +57,22 @@ test - javax.el - javax.el-api - ${javax.el.version} + org.glassfish.expressly + expressly + 5.0.0 - org.glassfish - javax.el - ${javax.el.version} + jakarta.annotation + jakarta.annotation-api + 2.1.1 - 4.3.4.RELEASE - 2.1.5.RELEASE - 5.3.3.Final - 2.9.6 - 3.0.0 + 6.0.6 + 5.0.3 + 8.0.0.Final + 2.12.2 \ No newline at end of file diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Campus.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Campus.java index d710a357967d..898ccc9562f8 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Campus.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Campus.java @@ -1,13 +1,12 @@ package com.baeldung.spring.data.couchbase.model; -import javax.validation.constraints.NotNull; +import jakarta.validation.constraints.NotNull; import org.springframework.data.annotation.Id; import org.springframework.data.couchbase.core.mapping.Document; +import org.springframework.data.couchbase.core.mapping.Field; import org.springframework.data.geo.Point; -import com.couchbase.client.java.repository.annotation.Field; - @Document public class Campus { diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Person.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Person.java index 1e081f01da11..180c089f9401 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Person.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Person.java @@ -1,12 +1,11 @@ package com.baeldung.spring.data.couchbase.model; -import javax.validation.constraints.NotNull; +import jakarta.validation.constraints.NotNull; import org.joda.time.DateTime; import org.springframework.data.annotation.Id; import org.springframework.data.couchbase.core.mapping.Document; - -import com.couchbase.client.java.repository.annotation.Field; +import org.springframework.data.couchbase.core.mapping.Field; @Document public class Person { diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Student.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Student.java index e979eca864af..8c03f66bb2ab 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Student.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/model/Student.java @@ -1,16 +1,15 @@ package com.baeldung.spring.data.couchbase.model; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Past; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Past; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; import org.joda.time.DateTime; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Version; import org.springframework.data.couchbase.core.mapping.Document; - -import com.couchbase.client.java.repository.annotation.Field; +import org.springframework.data.couchbase.core.mapping.Field; @Document public class Student { diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java index c4742ac44aed..ce20e0cd4960 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java @@ -5,9 +5,7 @@ import com.baeldung.spring.data.couchbase.model.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.couchbase.core.CouchbaseTemplate; - -import com.couchbase.client.java.view.Stale; -import com.couchbase.client.java.view.ViewQuery; +import org.springframework.data.couchbase.core.query.QueryCriteria; public class CustomStudentRepositoryImpl implements CustomStudentRepository { @@ -17,6 +15,6 @@ public class CustomStudentRepositoryImpl implements CustomStudentRepository { private CouchbaseTemplate template; public List findByFirstNameStartsWith(String s) { - return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName").startKey(s).stale(Stale.FALSE), Student.class); + return template.findByQuery(Student.class).matching(QueryCriteria.where("firstName").startingWith(s)).all(); } } diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonRepositoryService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonRepositoryService.java index 4051585e3135..5e1c2a2cb8e4 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonRepositoryService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonRepositoryService.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Optional; import com.baeldung.spring.data.couchbase.model.Person; import com.baeldung.spring.data.couchbase.repos.PersonRepository; @@ -22,12 +23,12 @@ public void setPersonRepository(PersonRepository repo) { this.repo = repo; } - public Person findOne(String id) { - return repo.findOne(id); + public Optional findOne(String id) { + return repo.findById(id); } public List findAll() { - List people = new ArrayList(); + List people = new ArrayList<>(); Iterator it = repo.findAll().iterator(); while (it.hasNext()) { people.add(it.next()); diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonService.java index f321eba94e8d..975af7f4a0bb 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonService.java @@ -1,12 +1,13 @@ package com.baeldung.spring.data.couchbase.service; import java.util.List; +import java.util.Optional; import com.baeldung.spring.data.couchbase.model.Person; public interface PersonService { - Person findOne(String id); + Optional findOne(String id); List findAll(); diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonTemplateService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonTemplateService.java index 5e49465a254b..3be9cb941698 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonTemplateService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/PersonTemplateService.java @@ -1,6 +1,9 @@ package com.baeldung.spring.data.couchbase.service; +import static org.springframework.data.couchbase.core.query.QueryCriteria.where; + import java.util.List; +import java.util.Optional; import com.baeldung.spring.data.couchbase.model.Person; import org.joda.time.DateTime; @@ -9,8 +12,6 @@ import org.springframework.data.couchbase.core.CouchbaseTemplate; import org.springframework.stereotype.Service; -import com.couchbase.client.java.view.ViewQuery; - @Service @Qualifier("PersonTemplateService") public class PersonTemplateService implements PersonService { @@ -24,33 +25,33 @@ public void setCouchbaseTemplate(CouchbaseTemplate template) { this.template = template; } - public Person findOne(String id) { - return template.findById(id, Person.class); + public Optional findOne(String id) { + return Optional.of(template.findById(Person.class).one(id)); } public List findAll() { - return template.findByView(ViewQuery.from(DESIGN_DOC, "all"), Person.class); + return template.findByQuery(Person.class).all(); } public List findByFirstName(String firstName) { - return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName"), Person.class); + return template.findByQuery(Person.class).matching(where("firstName").is(firstName)).all(); } public List findByLastName(String lastName) { - return template.findByView(ViewQuery.from(DESIGN_DOC, "byLastName"), Person.class); + return template.findByQuery(Person.class).matching(where("lastName").is(lastName)).all(); } public void create(Person person) { person.setCreated(DateTime.now()); - template.insert(person); + template.insertById(Person.class).one(person); } public void update(Person person) { person.setUpdated(DateTime.now()); - template.update(person); + template.removeById(Person.class).oneEntity(person); } public void delete(Person person) { - template.remove(person); + template.removeById(Person.class).oneEntity(person); } } diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentRepositoryService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentRepositoryService.java index ff9657260ad0..8a49ae075c11 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentRepositoryService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentRepositoryService.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Optional; import com.baeldung.spring.data.couchbase.model.Student; import com.baeldung.spring.data.couchbase.repos.StudentRepository; @@ -22,12 +23,12 @@ public void setStudentRepository(StudentRepository repo) { this.repo = repo; } - public Student findOne(String id) { - return repo.findOne(id); + public Optional findOne(String id) { + return repo.findById(id); } public List findAll() { - List people = new ArrayList(); + List people = new ArrayList<>(); Iterator it = repo.findAll().iterator(); while (it.hasNext()) { people.add(it.next()); diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentService.java index aa99a770cd28..c3512794bde5 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentService.java @@ -1,12 +1,13 @@ package com.baeldung.spring.data.couchbase.service; import java.util.List; +import java.util.Optional; import com.baeldung.spring.data.couchbase.model.Student; public interface StudentService { - Student findOne(String id); + Optional findOne(String id); List findAll(); diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentTemplateService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentTemplateService.java index 9110f682761c..59115a214960 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentTemplateService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase/service/StudentTemplateService.java @@ -1,6 +1,9 @@ package com.baeldung.spring.data.couchbase.service; +import static org.springframework.data.couchbase.core.query.QueryCriteria.where; + import java.util.List; +import java.util.Optional; import com.baeldung.spring.data.couchbase.model.Student; import org.joda.time.DateTime; @@ -9,8 +12,6 @@ import org.springframework.data.couchbase.core.CouchbaseTemplate; import org.springframework.stereotype.Service; -import com.couchbase.client.java.view.ViewQuery; - @Service @Qualifier("StudentTemplateService") public class StudentTemplateService implements StudentService { @@ -24,33 +25,33 @@ public void setCouchbaseTemplate(CouchbaseTemplate template) { this.template = template; } - public Student findOne(String id) { - return template.findById(id, Student.class); + public Optional findOne(String id) { + return Optional.of(template.findById(Student.class).one(id)); } public List findAll() { - return template.findByView(ViewQuery.from(DESIGN_DOC, "all"), Student.class); + return template.findByQuery(Student.class).all(); } public List findByFirstName(String firstName) { - return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName"), Student.class); + return template.findByQuery(Student.class).matching(where("firstName").is(firstName)).all(); } public List findByLastName(String lastName) { - return template.findByView(ViewQuery.from(DESIGN_DOC, "byLastName"), Student.class); + return template.findByQuery(Student.class).matching(where("lastName").is(lastName)).all(); } public void create(Student student) { student.setCreated(DateTime.now()); - template.insert(student); + template.insertById(Student.class).one(student); } public void update(Student student) { student.setUpdated(DateTime.now()); - template.update(student); + template.upsertById(Student.class).one(student); } public void delete(Student student) { - template.remove(student); + template.removeById(Student.class).oneEntity(student); } } diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusService.java index 567ffa2a7f77..6777fe4d959c 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusService.java @@ -1,5 +1,6 @@ package com.baeldung.spring.data.couchbase2b.service; +import java.util.Optional; import java.util.Set; import com.baeldung.spring.data.couchbase.model.Campus; @@ -8,7 +9,7 @@ public interface CampusService { - Campus find(String id); + Optional find(String id); Set findByName(String name); diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java index 03e2dced1ba3..9668da29e3fd 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java @@ -2,6 +2,7 @@ import java.util.HashSet; import java.util.Iterator; +import java.util.Optional; import java.util.Set; import com.baeldung.spring.data.couchbase2b.repos.CampusRepository; @@ -22,8 +23,8 @@ public void setCampusRepository(CampusRepository repo) { } @Override - public Campus find(String id) { - return repo.findOne(id); + public Optional find(String id) { + return repo.findById(id); } @Override diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonService.java index 7dc30ead118e..1e7091bdf45b 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonService.java @@ -1,12 +1,13 @@ package com.baeldung.spring.data.couchbase2b.service; import java.util.List; +import java.util.Optional; import com.baeldung.spring.data.couchbase.model.Person; public interface PersonService { - Person findOne(String id); + Optional findOne(String id); List findAll(); diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java index af08bd4ca8f4..bc6c5f267349 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Optional; import com.baeldung.spring.data.couchbase2b.repos.PersonRepository; import com.baeldung.spring.data.couchbase.model.Person; @@ -20,12 +21,12 @@ public void setPersonRepository(PersonRepository repo) { this.repo = repo; } - public Person findOne(String id) { - return repo.findOne(id); + public Optional findOne(String id) { + return repo.findById(id); } public List findAll() { - List people = new ArrayList(); + List people = new ArrayList<>(); Iterator it = repo.findAll().iterator(); while (it.hasNext()) { people.add(it.next()); diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentService.java index 3f318e1af16f..7c408f4c7508 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentService.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentService.java @@ -1,12 +1,13 @@ package com.baeldung.spring.data.couchbase2b.service; import java.util.List; +import java.util.Optional; import com.baeldung.spring.data.couchbase.model.Student; public interface StudentService { - Student findOne(String id); + Optional findOne(String id); List findAll(); diff --git a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java index 53feaead10e5..f2889e8caa0b 100644 --- a/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java +++ b/persistence-modules/spring-data-couchbase-2/src/main/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Optional; import com.baeldung.spring.data.couchbase2b.repos.StudentRepository; import com.baeldung.spring.data.couchbase.model.Student; @@ -20,12 +21,12 @@ public void setStudentRepository(StudentRepository repo) { this.repo = repo; } - public Student findOne(String id) { - return repo.findOne(id); + public Optional findOne(String id) { + return repo.findById(id); } public List findAll() { - List people = new ArrayList(); + List people = new ArrayList<>(); Iterator it = repo.findAll().iterator(); while (it.hasNext()) { people.add(it.next()); diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java index 403c012194e6..eacecb4e1e30 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java @@ -4,6 +4,21 @@ public class CustomTypeKeyCouchbaseConfig extends MyCouchbaseConfig { + @Override + public String getConnectionString() { + return NODE_LIST; + } + + @Override + public String getUserName() { + return BUCKET_USERNAME; + } + + @Override + public String getPassword() { + return BUCKET_PASSWORD; + } + @Override public String typeKey() { return MappingCouchbaseConverter.TYPEKEY_SYNCGATEWAY_COMPATIBLE; diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/MyCouchbaseConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/MyCouchbaseConfig.java index 5a2180f4b829..5412afb493fd 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/MyCouchbaseConfig.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/MyCouchbaseConfig.java @@ -1,42 +1,46 @@ package com.baeldung.spring.data.couchbase; -import java.util.Arrays; -import java.util.List; - import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration; import org.springframework.data.couchbase.core.mapping.event.ValidatingCouchbaseEventListener; -import org.springframework.data.couchbase.core.query.Consistency; import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepositories; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; +import com.couchbase.client.java.query.QueryScanConsistency; + @Configuration @EnableCouchbaseRepositories(basePackages = { "com.baeldung.spring.data.couchbase" }) public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration { - public static final List NODE_LIST = Arrays.asList("localhost"); + public static final String NODE_LIST = "localhost"; public static final String BUCKET_NAME = "baeldung"; - public static final String BUCKET_PASSWORD = ""; + public static final String BUCKET_USERNAME = "baeldung"; + public static final String BUCKET_PASSWORD = "baeldung"; @Override - protected List getBootstrapHosts() { + public String getConnectionString() { return NODE_LIST; } @Override - protected String getBucketName() { - return BUCKET_NAME; + public String getUserName() { + return BUCKET_USERNAME; } @Override - protected String getBucketPassword() { + public String getPassword() { return BUCKET_PASSWORD; } @Override - protected Consistency getDefaultConsistency() { - return Consistency.READ_YOUR_OWN_WRITES; + public String getBucketName() { + return BUCKET_NAME; + } + + @Override + public QueryScanConsistency getDefaultConsistency() { + return QueryScanConsistency.REQUEST_PLUS; } @Bean diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java index b989bb39d88c..33a6c4f091b9 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java @@ -1,11 +1,11 @@ package com.baeldung.spring.data.couchbase; -import org.springframework.data.couchbase.core.query.Consistency; +import com.couchbase.client.java.query.QueryScanConsistency; public class ReadYourOwnWritesCouchbaseConfig extends MyCouchbaseConfig { @Override - public Consistency getDefaultConsistency() { - return Consistency.READ_YOUR_OWN_WRITES; + public QueryScanConsistency getDefaultConsistency() { + return QueryScanConsistency.REQUEST_PLUS; } } diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonServiceLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonServiceLiveTest.java index 804bbdd2c87b..0275587ac378 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonServiceLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/PersonServiceLiveTest.java @@ -1,11 +1,15 @@ package com.baeldung.spring.data.couchbase.service; +import static com.baeldung.spring.data.couchbase.MyCouchbaseConfig.BUCKET_PASSWORD; +import static com.baeldung.spring.data.couchbase.MyCouchbaseConfig.BUCKET_USERNAME; +import static com.baeldung.spring.data.couchbase.MyCouchbaseConfig.NODE_LIST; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.List; +import java.util.Optional; import com.baeldung.spring.data.couchbase.IntegrationTest; import com.baeldung.spring.data.couchbase.MyCouchbaseConfig; @@ -16,9 +20,8 @@ import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.CouchbaseCluster; -import com.couchbase.client.java.document.JsonDocument; -import com.couchbase.client.java.document.json.JsonObject; +import com.couchbase.client.java.Collection; +import com.couchbase.client.java.json.JsonObject; public abstract class PersonServiceLiveTest extends IntegrationTest { @@ -27,32 +30,32 @@ public abstract class PersonServiceLiveTest extends IntegrationTest { static final String smith = "Smith"; static final String johnSmithId = "person:" + john + ":" + smith; static final Person johnSmith = new Person(johnSmithId, john, smith); - static final JsonObject jsonJohnSmith = JsonObject.empty().put(typeField, Person.class.getName()).put("firstName", john).put("lastName", smith).put("created", DateTime.now().getMillis()); + static final JsonObject jsonJohnSmith = JsonObject.create().put(typeField, Person.class.getName()).put("firstName", john).put("lastName", smith).put("created", DateTime.now().getMillis()); static final String foo = "Foo"; static final String bar = "Bar"; static final String foobarId = "person:" + foo + ":" + bar; static final Person foobar = new Person(foobarId, foo, bar); - static final JsonObject jsonFooBar = JsonObject.empty().put(typeField, Person.class.getName()).put("firstName", foo).put("lastName", bar).put("created", DateTime.now().getMillis()); + static final JsonObject jsonFooBar = JsonObject.create().put(typeField, Person.class.getName()).put("firstName", foo).put("lastName", bar).put("created", DateTime.now().getMillis()); PersonService personService; @BeforeClass public static void setupBeforeClass() { - final Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST); - final Bucket bucket = cluster.openBucket(MyCouchbaseConfig.BUCKET_NAME, MyCouchbaseConfig.BUCKET_PASSWORD); - bucket.upsert(JsonDocument.create(johnSmithId, jsonJohnSmith)); - bucket.upsert(JsonDocument.create(foobarId, jsonFooBar)); - bucket.close(); + final Cluster cluster = Cluster.connect(NODE_LIST, BUCKET_USERNAME, BUCKET_PASSWORD); + final Bucket bucket = cluster.bucket(MyCouchbaseConfig.BUCKET_NAME); + final Collection collection = bucket.defaultCollection(); + collection.upsert(johnSmithId, JsonObject.create().put(johnSmithId, jsonJohnSmith)); + collection.upsert(foobarId, JsonObject.create().put(foobarId, jsonFooBar)); cluster.disconnect(); } @Test public void whenFindingPersonByJohnSmithId_thenReturnsJohnSmith() { - final Person actualPerson = personService.findOne(johnSmithId); - assertNotNull(actualPerson); - assertNotNull(actualPerson.getCreated()); - assertEquals(johnSmith, actualPerson); + final Optional actualPerson = personService.findOne(johnSmithId); + assertTrue(actualPerson.isPresent()); + assertNotNull(actualPerson.get().getCreated()); + assertEquals(johnSmith, actualPerson.get()); } @Test diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentServiceLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentServiceLiveTest.java index c13b4930cae1..a502d46124b8 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentServiceLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase/service/StudentServiceLiveTest.java @@ -1,13 +1,17 @@ package com.baeldung.spring.data.couchbase.service; +import static com.baeldung.spring.data.couchbase.MyCouchbaseConfig.BUCKET_PASSWORD; +import static com.baeldung.spring.data.couchbase.MyCouchbaseConfig.BUCKET_USERNAME; +import static com.baeldung.spring.data.couchbase.MyCouchbaseConfig.NODE_LIST; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.List; +import java.util.Optional; -import javax.validation.ConstraintViolationException; +import jakarta.validation.ConstraintViolationException; import com.baeldung.spring.data.couchbase.IntegrationTest; import com.baeldung.spring.data.couchbase.MyCouchbaseConfig; @@ -18,9 +22,8 @@ import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.CouchbaseCluster; -import com.couchbase.client.java.document.JsonDocument; -import com.couchbase.client.java.document.json.JsonObject; +import com.couchbase.client.java.Collection; +import com.couchbase.client.java.json.JsonObject; public abstract class StudentServiceLiveTest extends IntegrationTest { @@ -30,24 +33,24 @@ public abstract class StudentServiceLiveTest extends IntegrationTest { static final String joeCollegeId = "student:" + joe + ":" + college; static final DateTime joeCollegeDob = DateTime.now().minusYears(21); static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); - static final JsonObject jsonJoeCollege = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1); + static final JsonObject jsonJoeCollege = JsonObject.create().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1); static final String judy = "Judy"; static final String jetson = "Jetson"; static final String judyJetsonId = "student:" + judy + ":" + jetson; static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); - static final JsonObject jsonJudyJetson = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1); + static final JsonObject jsonJudyJetson = JsonObject.create().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1); StudentService studentService; @BeforeClass public static void setupBeforeClass() { - Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST); - Bucket bucket = cluster.openBucket(MyCouchbaseConfig.BUCKET_NAME, MyCouchbaseConfig.BUCKET_PASSWORD); - bucket.upsert(JsonDocument.create(joeCollegeId, jsonJoeCollege)); - bucket.upsert(JsonDocument.create(judyJetsonId, jsonJudyJetson)); - bucket.close(); + final Cluster cluster = Cluster.connect(NODE_LIST, BUCKET_USERNAME, BUCKET_PASSWORD); + final Bucket bucket = cluster.bucket(MyCouchbaseConfig.BUCKET_NAME); + final Collection collection = bucket.defaultCollection(); + collection.upsert(joeCollegeId, JsonObject.create().put(joeCollegeId, jsonJoeCollege)); + collection.upsert(judyJetsonId, JsonObject.create().put(judyJetsonId, jsonJudyJetson)); cluster.disconnect(); } @@ -59,10 +62,10 @@ public void whenCreatingStudent_thenDocumentIsPersisted() { String id = "student:" + firstName + ":" + lastName; Student expectedStudent = new Student(id, firstName, lastName, dateOfBirth); studentService.create(expectedStudent); - Student actualStudent = studentService.findOne(id); - assertNotNull(actualStudent.getCreated()); - assertNotNull(actualStudent); - assertEquals(expectedStudent.getId(), actualStudent.getId()); + Optional actualStudent = studentService.findOne(id); + assertTrue(actualStudent.isPresent()); + assertNotNull(actualStudent.get().getCreated()); + assertEquals(expectedStudent.getId(), actualStudent.get().getId()); } @Test(expected = ConstraintViolationException.class) @@ -87,10 +90,10 @@ public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() @Test public void whenFindingStudentByJohnSmithId_thenReturnsJohnSmith() { - Student actualStudent = studentService.findOne(joeCollegeId); - assertNotNull(actualStudent); - assertNotNull(actualStudent.getCreated()); - assertEquals(joeCollegeId, actualStudent.getId()); + Optional actualStudent = studentService.findOne(joeCollegeId); + assertTrue(actualStudent.isPresent()); + assertNotNull(actualStudent.get().getCreated()); + assertEquals(joeCollegeId, actualStudent.get().getId()); } @Test diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java index 488819aaf531..bfa422037fb4 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java @@ -1,54 +1,47 @@ package com.baeldung.spring.data.couchbase2b; -import java.util.Arrays; +import java.util.Collections; import java.util.List; import com.baeldung.spring.data.couchbase.model.Campus; + +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.data.couchbase.SimpleCouchbaseClientFactory; import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration; import org.springframework.data.couchbase.core.CouchbaseTemplate; +import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter; import org.springframework.data.couchbase.core.mapping.event.ValidatingCouchbaseEventListener; -import org.springframework.data.couchbase.core.query.Consistency; import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepositories; import org.springframework.data.couchbase.repository.config.RepositoryOperationsMapping; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; +import com.couchbase.client.core.env.PasswordAuthenticator; import com.couchbase.client.java.Bucket; +import com.couchbase.client.java.env.ClusterEnvironment; @Configuration @EnableCouchbaseRepositories(basePackages = { "com.baeldung.spring.data.couchbase2b" }) public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration { - public static final List NODE_LIST = Arrays.asList("localhost"); + public static final String NODE_LIST = "localhost"; public static final String DEFAULT_BUCKET_NAME = "baeldung"; - public static final String DEFAULT_BUCKET_PASSWORD = ""; - - @Override - protected List getBootstrapHosts() { - return NODE_LIST; - } + public static final String DEFAULT_BUCKET_USERNAME = "baeldung"; + public static final String DEFAULT_BUCKET_PASSWORD = "baeldung"; - @Override - protected String getBucketName() { - return DEFAULT_BUCKET_NAME; - } - - @Override - protected String getBucketPassword() { - return DEFAULT_BUCKET_PASSWORD; - } + @Autowired + private MappingCouchbaseConverter mappingCouchbaseConverter; @Bean - public Bucket campusBucket() throws Exception { - return couchbaseCluster().openBucket("baeldung2", ""); + public Bucket campusBucket() { + return couchbaseCluster(ClusterEnvironment.create()).bucket("baeldung2"); } @Bean(name = "campusTemplate") - public CouchbaseTemplate campusTemplate() throws Exception { - CouchbaseTemplate template = new CouchbaseTemplate(couchbaseClusterInfo(), campusBucket(), mappingCouchbaseConverter(), translationService()); - template.setDefaultConsistency(getDefaultConsistency()); - return template; + public CouchbaseTemplate campusTemplate() { + return new CouchbaseTemplate(new SimpleCouchbaseClientFactory(NODE_LIST, + PasswordAuthenticator.create(DEFAULT_BUCKET_USERNAME, DEFAULT_BUCKET_PASSWORD), DEFAULT_BUCKET_NAME), mappingCouchbaseConverter); } @Override @@ -60,11 +53,6 @@ public void configureRepositoryOperationsMapping(RepositoryOperationsMapping bas } } - @Override - protected Consistency getDefaultConsistency() { - return Consistency.READ_YOUR_OWN_WRITES; - } - @Bean public LocalValidatorFactoryBean localValidatorFactoryBean() { return new LocalValidatorFactoryBean(); @@ -74,4 +62,24 @@ public LocalValidatorFactoryBean localValidatorFactoryBean() { public ValidatingCouchbaseEventListener validatingCouchbaseEventListener() { return new ValidatingCouchbaseEventListener(localValidatorFactoryBean()); } + + @Override + public String getConnectionString() { + return NODE_LIST; + } + + @Override + public String getUserName() { + return DEFAULT_BUCKET_USERNAME; + } + + @Override + public String getPassword() { + return DEFAULT_BUCKET_PASSWORD; + } + + @Override + public String getBucketName() { + return DEFAULT_BUCKET_NAME; + } } diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImplLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImplLiveTest.java index e94c09e6cdec..08adbfd016cd 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImplLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/CampusServiceImplLiveTest.java @@ -5,9 +5,10 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import java.util.Optional; import java.util.Set; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import com.baeldung.spring.data.couchbase.model.Campus; import com.baeldung.spring.data.couchbase2b.MultiBucketLiveTest; @@ -46,7 +47,7 @@ public class CampusServiceImplLiveTest extends MultiBucketLiveTest { private final Point NewYorkCity = new Point(74.0059, 40.7128); @PostConstruct - private void loadCampuses() throws Exception { + private void loadCampuses() { campusRepo.save(Brown); campusRepo.save(Columbia); campusRepo.save(Cornell); @@ -58,7 +59,7 @@ private void loadCampuses() throws Exception { } @Test - public final void givenNameHarvard_whenFindByName_thenReturnsHarvard() throws Exception { + public final void givenNameHarvard_whenFindByName_thenReturnsHarvard() { Set campuses = campusService.findByName(Harvard.getName()); assertNotNull(campuses); assertFalse(campuses.isEmpty()); @@ -67,14 +68,14 @@ public final void givenNameHarvard_whenFindByName_thenReturnsHarvard() throws Ex } @Test - public final void givenHarvardId_whenFind_thenReturnsHarvard() throws Exception { - Campus actual = campusService.find(Harvard.getId()); - assertNotNull(actual); - assertEquals(Harvard, actual); + public final void givenHarvardId_whenFind_thenReturnsHarvard() { + Optional actual = campusService.find(Harvard.getId()); + assertTrue(actual.isPresent()); + assertEquals(Harvard, actual.get()); } @Test - public final void whenFindAll_thenReturnsAll() throws Exception { + public final void whenFindAll_thenReturnsAll() { Set campuses = campusService.findAll(); assertTrue(campuses.contains(Brown)); assertTrue(campuses.contains(Columbia)); @@ -87,7 +88,7 @@ public final void whenFindAll_thenReturnsAll() throws Exception { } @Test - public final void whenFindByLocationNearBoston_thenResultContainsHarvard() throws Exception { + public final void whenFindByLocationNearBoston_thenResultContainsHarvard() { Set campuses = campusService.findByLocationNear(Boston, new Distance(1, Metrics.NEUTRAL)); assertFalse(campuses.isEmpty()); assertTrue(campuses.contains(Harvard)); @@ -95,7 +96,7 @@ public final void whenFindByLocationNearBoston_thenResultContainsHarvard() throw } @Test - public final void whenFindByLocationNearNewYorkCity_thenResultContainsColumbia() throws Exception { + public final void whenFindByLocationNearNewYorkCity_thenResultContainsColumbia() { Set campuses = campusService.findByLocationNear(NewYorkCity, new Distance(1, Metrics.NEUTRAL)); assertFalse(campuses.isEmpty()); assertTrue(campuses.contains(Columbia)); diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImplLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImplLiveTest.java index 3f98c1950a5e..28477e9d148b 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImplLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/PersonServiceImplLiveTest.java @@ -1,11 +1,15 @@ package com.baeldung.spring.data.couchbase2b.service; +import static com.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig.DEFAULT_BUCKET_PASSWORD; +import static com.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig.DEFAULT_BUCKET_USERNAME; +import static com.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig.NODE_LIST; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.List; +import java.util.Optional; import com.baeldung.spring.data.couchbase.model.Person; import com.baeldung.spring.data.couchbase2b.MultiBucketLiveTest; @@ -17,9 +21,8 @@ import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.CouchbaseCluster; -import com.couchbase.client.java.document.JsonDocument; -import com.couchbase.client.java.document.json.JsonObject; +import com.couchbase.client.java.Collection; +import com.couchbase.client.java.json.JsonObject; public class PersonServiceImplLiveTest extends MultiBucketLiveTest { @@ -28,33 +31,33 @@ public class PersonServiceImplLiveTest extends MultiBucketLiveTest { static final String smith = "Smith"; static final String johnSmithId = "person:" + john + ":" + smith; static final Person johnSmith = new Person(johnSmithId, john, smith); - static final JsonObject jsonJohnSmith = JsonObject.empty().put(typeField, Person.class.getName()).put("firstName", john).put("lastName", smith).put("created", DateTime.now().getMillis()); + static final JsonObject jsonJohnSmith = JsonObject.create().put(typeField, Person.class.getName()).put("firstName", john).put("lastName", smith).put("created", DateTime.now().getMillis()); static final String foo = "Foo"; static final String bar = "Bar"; static final String foobarId = "person:" + foo + ":" + bar; static final Person foobar = new Person(foobarId, foo, bar); - static final JsonObject jsonFooBar = JsonObject.empty().put(typeField, Person.class.getName()).put("firstName", foo).put("lastName", bar).put("created", DateTime.now().getMillis()); + static final JsonObject jsonFooBar = JsonObject.create().put(typeField, Person.class.getName()).put("firstName", foo).put("lastName", bar).put("created", DateTime.now().getMillis()); @Autowired private PersonServiceImpl personService; @BeforeClass public static void setupBeforeClass() { - final Cluster cluster = CouchbaseCluster.create(MultiBucketCouchbaseConfig.NODE_LIST); - final Bucket bucket = cluster.openBucket(MultiBucketCouchbaseConfig.DEFAULT_BUCKET_NAME, MultiBucketCouchbaseConfig.DEFAULT_BUCKET_PASSWORD); - bucket.upsert(JsonDocument.create(johnSmithId, jsonJohnSmith)); - bucket.upsert(JsonDocument.create(foobarId, jsonFooBar)); - bucket.close(); + final Cluster cluster = Cluster.connect(NODE_LIST, DEFAULT_BUCKET_USERNAME, DEFAULT_BUCKET_PASSWORD); + final Bucket bucket = cluster.bucket(MultiBucketCouchbaseConfig.DEFAULT_BUCKET_NAME); + final Collection collection = bucket.defaultCollection(); + collection.upsert(johnSmithId, JsonObject.create().put(johnSmithId, jsonJohnSmith)); + collection.upsert(foobarId, JsonObject.create().put(foobarId, jsonFooBar)); cluster.disconnect(); } @Test public void whenFindingPersonByJohnSmithId_thenReturnsJohnSmith() { - final Person actualPerson = personService.findOne(johnSmithId); - assertNotNull(actualPerson); - assertNotNull(actualPerson.getCreated()); - assertEquals(johnSmith, actualPerson); + final Optional actualPerson = personService.findOne(johnSmithId); + assertTrue(actualPerson.isPresent()); + assertNotNull(actualPerson.get().getCreated()); + assertEquals(johnSmith, actualPerson.get()); } @Test diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImplLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImplLiveTest.java index 004258a37e1e..98cbd397884a 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImplLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/com/baeldung/spring/data/couchbase2b/service/StudentServiceImplLiveTest.java @@ -1,13 +1,17 @@ package com.baeldung.spring.data.couchbase2b.service; +import static com.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig.DEFAULT_BUCKET_PASSWORD; +import static com.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig.DEFAULT_BUCKET_USERNAME; +import static com.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig.NODE_LIST; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.List; +import java.util.Optional; -import javax.validation.ConstraintViolationException; +import jakarta.validation.ConstraintViolationException; import com.baeldung.spring.data.couchbase.model.Student; import com.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; @@ -19,9 +23,8 @@ import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.CouchbaseCluster; -import com.couchbase.client.java.document.JsonDocument; -import com.couchbase.client.java.document.json.JsonObject; +import com.couchbase.client.java.Collection; +import com.couchbase.client.java.json.JsonObject; public class StudentServiceImplLiveTest extends MultiBucketLiveTest { @@ -31,25 +34,25 @@ public class StudentServiceImplLiveTest extends MultiBucketLiveTest { static final String joeCollegeId = "student:" + joe + ":" + college; static final DateTime joeCollegeDob = DateTime.now().minusYears(21); static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); - static final JsonObject jsonJoeCollege = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1); + static final JsonObject jsonJoeCollege = JsonObject.create().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1); static final String judy = "Judy"; static final String jetson = "Jetson"; static final String judyJetsonId = "student:" + judy + ":" + jetson; static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); - static final JsonObject jsonJudyJetson = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1); + static final JsonObject jsonJudyJetson = JsonObject.create().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1); @Autowired StudentServiceImpl studentService; @BeforeClass public static void setupBeforeClass() { - Cluster cluster = CouchbaseCluster.create(MultiBucketCouchbaseConfig.NODE_LIST); - Bucket bucket = cluster.openBucket(MultiBucketCouchbaseConfig.DEFAULT_BUCKET_NAME, MultiBucketCouchbaseConfig.DEFAULT_BUCKET_PASSWORD); - bucket.upsert(JsonDocument.create(joeCollegeId, jsonJoeCollege)); - bucket.upsert(JsonDocument.create(judyJetsonId, jsonJudyJetson)); - bucket.close(); + Cluster cluster = Cluster.connect(NODE_LIST, DEFAULT_BUCKET_USERNAME, DEFAULT_BUCKET_PASSWORD); + Bucket bucket = cluster.bucket(MultiBucketCouchbaseConfig.DEFAULT_BUCKET_NAME); + final Collection collection = bucket.defaultCollection(); + collection.upsert(joeCollegeId, JsonObject.create().put(joeCollegeId, jsonJoeCollege)); + collection.upsert(judyJetsonId, JsonObject.create().put(judyJetsonId, jsonJudyJetson)); cluster.disconnect(); } @@ -61,10 +64,10 @@ public void whenCreatingStudent_thenDocumentIsPersisted() { String id = "student:" + firstName + ":" + lastName; Student expectedStudent = new Student(id, firstName, lastName, dateOfBirth); studentService.create(expectedStudent); - Student actualStudent = studentService.findOne(id); - assertNotNull(actualStudent.getCreated()); - assertNotNull(actualStudent); - assertEquals(expectedStudent.getId(), actualStudent.getId()); + Optional actualStudent = studentService.findOne(id); + assertTrue(actualStudent.isPresent()); + assertNotNull(actualStudent.get().getCreated()); + assertEquals(expectedStudent.getId(), actualStudent.get().getId()); } @Test(expected = ConstraintViolationException.class) @@ -89,10 +92,10 @@ public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() @Test public void whenFindingStudentByJohnSmithId_thenReturnsJohnSmith() { - Student actualStudent = studentService.findOne(joeCollegeId); - assertNotNull(actualStudent); - assertNotNull(actualStudent.getCreated()); - assertEquals(joeCollegeId, actualStudent.getId()); + Optional actualStudent = studentService.findOne(joeCollegeId); + assertTrue(actualStudent.isPresent()); + assertNotNull(actualStudent.get().getCreated()); + assertEquals(joeCollegeId, actualStudent.get().getId()); } @Test diff --git a/persistence-modules/spring-data-eclipselink/pom.xml b/persistence-modules/spring-data-eclipselink/pom.xml index c3c530d2d749..34d8a1a6f805 100644 --- a/persistence-modules/spring-data-eclipselink/pom.xml +++ b/persistence-modules/spring-data-eclipselink/pom.xml @@ -64,9 +64,11 @@ - 1.5.9.RELEASE - 2.7.0 + 3.0.4 + 4.0.1 2.1.214 + 2.0.7 + 1.4.6 \ No newline at end of file diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/JpaConfiguration.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/JpaConfiguration.java index 60ff7909bedb..4d3f3aa8fc5a 100644 --- a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/JpaConfiguration.java +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/JpaConfiguration.java @@ -21,8 +21,8 @@ @Configuration public class JpaConfiguration extends JpaBaseConfiguration { - protected JpaConfiguration(DataSource dataSource, JpaProperties properties, ObjectProvider jtaTransactionManager, ObjectProvider transactionManagerCustomizers) { - super(dataSource, properties, jtaTransactionManager, transactionManagerCustomizers); + protected JpaConfiguration(DataSource dataSource, JpaProperties properties, ObjectProvider jtaTransactionManager) { + super(dataSource, properties, jtaTransactionManager); } @Override diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/model/Person.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/model/Person.java index 75161875bd86..cc4956e2fc8c 100644 --- a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/model/Person.java +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/model/Person.java @@ -1,9 +1,9 @@ package com.baeldung.eclipselink.springdata.model; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; /** * Created by adam. diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Address.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Address.java index b62889208cb2..474926977c7f 100644 --- a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Address.java +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Address.java @@ -1,6 +1,6 @@ package com.baeldung.eclipselink.springdata.pessimisticlocking; -import javax.persistence.Embeddable; +import jakarta.persistence.Embeddable; @Embeddable public class Address { diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Course.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Course.java index 8d90659f3e71..97b0f612d30d 100644 --- a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Course.java +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Course.java @@ -1,9 +1,9 @@ package com.baeldung.eclipselink.springdata.pessimisticlocking; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinTable; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToOne; @Entity public class Course { diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Customer.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Customer.java index f06a676de8e6..c2689a25a750 100644 --- a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Customer.java +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Customer.java @@ -1,9 +1,9 @@ package com.baeldung.eclipselink.springdata.pessimisticlocking; -import javax.persistence.CollectionTable; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.CollectionTable; +import jakarta.persistence.ElementCollection; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; import java.util.List; @Entity diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Employee.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Employee.java index d09b123225cc..67c8fbf66082 100644 --- a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Employee.java +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Employee.java @@ -1,6 +1,6 @@ package com.baeldung.eclipselink.springdata.pessimisticlocking; -import javax.persistence.Entity; +import jakarta.persistence.Entity; import java.math.BigDecimal; @Entity diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Individual.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Individual.java index 7edaaace54cf..05fd7a890d56 100644 --- a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Individual.java +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Individual.java @@ -1,9 +1,9 @@ package com.baeldung.eclipselink.springdata.pessimisticlocking; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; @Entity @Inheritance(strategy = InheritanceType.JOINED) diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Student.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Student.java index f613aab0f60a..f8db1179fcc1 100644 --- a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Student.java +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Student.java @@ -1,8 +1,8 @@ package com.baeldung.eclipselink.springdata.pessimisticlocking; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; import java.util.List; @Entity diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/pessimisticlocking/PessimisticLockScopesIntegrationTest.java index 6ee40fac9afa..596229fc2d31 100644 --- a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/pessimisticlocking/PessimisticLockScopesIntegrationTest.java +++ b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/pessimisticlocking/PessimisticLockScopesIntegrationTest.java @@ -1,14 +1,12 @@ package com.baeldung.eclipselink.springdata.pessimisticlocking; -import org.junit.Assert; -import org.junit.BeforeClass; import org.junit.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; -import javax.persistence.*; +import jakarta.persistence.*; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashMap; diff --git a/persistence-modules/spring-data-jpa-annotations/README.md b/persistence-modules/spring-data-jpa-annotations/README.md index 5a5440b1edaf..d7e6189ae540 100644 --- a/persistence-modules/spring-data-jpa-annotations/README.md +++ b/persistence-modules/spring-data-jpa-annotations/README.md @@ -10,6 +10,7 @@ This module contains articles about annotations used in Spring Data JPA - [Programmatic Transaction Management in Spring](https://www.baeldung.com/spring-programmatic-transaction-management) - [JPA Entity Lifecycle Events](https://www.baeldung.com/jpa-entity-lifecycle-events) - [Overriding Column Definition With @AttributeOverride](https://www.baeldung.com/jpa-attributeoverride) +- [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java similarity index 100% rename from spring-core-3/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java rename to persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccess.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/DataAccess.java similarity index 100% rename from spring-core-3/src/main/java/com/baeldung/customannotation/DataAccess.java rename to persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/DataAccess.java diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java similarity index 100% rename from spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java rename to persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java similarity index 100% rename from spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java rename to persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/GenericDAO.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/GenericDAO.java similarity index 100% rename from spring-core-3/src/main/java/com/baeldung/customannotation/GenericDAO.java rename to persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/GenericDAO.java diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/Account.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/Account.java similarity index 100% rename from spring-core-3/src/test/java/com/baeldung/customannotation/Account.java rename to persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/Account.java diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java similarity index 100% rename from spring-core-3/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java rename to persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java similarity index 100% rename from spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java rename to persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java similarity index 100% rename from spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java rename to persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/Person.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/Person.java similarity index 100% rename from spring-core-3/src/test/java/com/baeldung/customannotation/Person.java rename to persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/Person.java diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/entity/Customer.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/entity/Customer.java index efcae7385316..5af96d78221e 100644 --- a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/entity/Customer.java +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/entity/Customer.java @@ -1,8 +1,11 @@ package com.baeldung.entity; +import org.hibernate.annotations.Type; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import java.util.UUID; @Entity public class Customer { @@ -13,11 +16,20 @@ public class Customer { private String name; private String email; + @Type(type = "org.hibernate.type.UUIDCharType") + private UUID uuid; + public Customer(String name, String email) { this.name = name; this.email = email; } + public Customer(String name, String email, UUID uuid) { + this.name = name; + this.email = email; + this.uuid = uuid; + } + public String getName() { return name; } @@ -34,4 +46,7 @@ public void setEmail(String email) { this.email = email; } + public UUID getUuid() { + return this.uuid; + } } diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/repository/CustomerRepository.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/repository/CustomerRepository.java index 65b22bbd84a8..5f9710b83919 100644 --- a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/repository/CustomerRepository.java +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/repository/CustomerRepository.java @@ -6,6 +6,7 @@ import org.springframework.data.repository.query.Param; import java.util.List; +import java.util.UUID; public interface CustomerRepository extends JpaRepository { @@ -16,4 +17,5 @@ public interface CustomerRepository extends JpaRepository { @Query("SELECT c FROM Customer c WHERE (:name is null or c.name = :name) and (:email is null or c.email = :email)") List findCustomerByNameAndEmail(@Param("name") String name, @Param("email") String email); + List findCustomerByUuid(@Param("uuid") UUID uuid); } diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java index 5d6457ce30af..27208507f1df 100644 --- a/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java @@ -12,6 +12,7 @@ import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; +import java.util.UUID; import static org.junit.Assert.assertEquals; @@ -30,6 +31,7 @@ public void before() { entityManager.persist(new Customer("A", "A@example.com")); entityManager.persist(new Customer("D", null)); entityManager.persist(new Customer("D", "D@example.com")); + entityManager.persist(new Customer("C", null, UUID.fromString("c7c19ff4-8636-4b99-9591-c3327652f191"))); } @Test @@ -57,6 +59,20 @@ public void givenQueryAnnotation_whenEmailIsNull_thenIgnoreEmail() { assertEquals(2, customers.size()); } + @Test + public void givenUUIDIsPresent_whenQueryMethod_thenFetchedCorrectly() { + List customers = repository.findCustomerByUuid(UUID.fromString("c7c19ff4-8636-4b99-9591-c3327652f191")); + + assertEquals(1, customers.size()); + } + + @Test + public void givenNullUuid_whenQueryMethod_thenFetchedCorrectly() { + List customers = repository.findCustomerByUuid(null); + + assertEquals(3, customers.size()); + } + @After public void cleanUp() { repository.deleteAll(); diff --git a/persistence-modules/spring-data-jpa-query-3/pom.xml b/persistence-modules/spring-data-jpa-query-3/pom.xml index 18df57fe142c..1dff3024f648 100644 --- a/persistence-modules/spring-data-jpa-query-3/pom.xml +++ b/persistence-modules/spring-data-jpa-query-3/pom.xml @@ -30,6 +30,11 @@ javafaker ${javafaker.version} + + org.springframework.boot + spring-boot-starter-web + + org.springframework.boot spring-boot-starter-test diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/Customer.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/Customer.java new file mode 100644 index 000000000000..7ef4db808bce --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/Customer.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.data.jpa.paging; + +public class Customer { + + private String name; + + public Customer(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerRepository.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerRepository.java new file mode 100644 index 000000000000..ea418e7c55eb --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.data.jpa.paging; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CustomerRepository extends JpaRepository { + +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerRestController.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerRestController.java new file mode 100644 index 000000000000..4a3a38991ca1 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerRestController.java @@ -0,0 +1,31 @@ +package com.baeldung.spring.data.jpa.paging; + +import org.springframework.data.domain.Page; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CustomerRestController { + + private final CustomerService customerService; + + public CustomerRestController(CustomerService customerService) { + this.customerService = customerService; + } + + @GetMapping("/api/customers") + public ResponseEntity> getCustomers(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size) { + + Page customerPage = customerService.getCustomers(page, size); + HttpHeaders headers = new HttpHeaders(); + headers.add("X-Page-Number", String.valueOf(customerPage.getNumber())); + headers.add("X-Page-Size", String.valueOf(customerPage.getSize())); + + return ResponseEntity.ok() + .headers(headers) + .body(customerPage); + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerService.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerService.java new file mode 100644 index 000000000000..73affeb1a13c --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerService.java @@ -0,0 +1,35 @@ +package com.baeldung.spring.data.jpa.paging; + +import java.util.List; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@Service +public class CustomerService { + + public CustomerService(CustomerRepository customerRepository) { + this.customerRepository = customerRepository; + } + + private final CustomerRepository customerRepository; + + public Page getCustomers(int page, int size) { + + Pageable pageRequest = createPageRequestUsing(page, size); + + List allCustomers = customerRepository.findAll(); + int start = (int) pageRequest.getOffset(); + int end = Math.min((start + pageRequest.getPageSize()), allCustomers.size()); + + List pageContent = allCustomers.subList(start, end); + return new PageImpl<>(pageContent, pageRequest, allCustomers.size()); + } + + private Pageable createPageRequestUsing(int page, int size) { + return PageRequest.of(page, size); + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/PagingApplication.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/PagingApplication.java new file mode 100644 index 000000000000..58a6b43ff381 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/PagingApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.data.jpa.paging; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PagingApplication { + + public static void main(String[] args) { + SpringApplication.run(PagingApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/paging/CustomerControllerIntegrationTest.java b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/paging/CustomerControllerIntegrationTest.java new file mode 100644 index 000000000000..c928ab2a5dfb --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/paging/CustomerControllerIntegrationTest.java @@ -0,0 +1,69 @@ +package com.baeldung.spring.data.jpa.paging; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + +import org.json.JSONObject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +@WebMvcTest(CustomerRestController.class) +public class CustomerControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private CustomerService customerService; + + @BeforeEach + void setup() { + List allCustomers = getAllCustomers(); + Page customerPage = new PageImpl<>(allCustomers, PageRequest.of(1, 5), allCustomers.size()); + + when(customerService.getCustomers(1, 5)).thenReturn(customerPage); + + } + + private static List getAllCustomers() { + List customers = new ArrayList<>(); + IntStream.range(0, 20) + .forEach(i -> { + Customer customer = new Customer((Integer.toString(i))); + customers.add(customer); + }); + return customers; + } + + @Test + void givenTotalCustomers20_whenGetRequestWithPageAndSize_thenPagedReponseIsReturnedFromDesiredPageAndSize() throws Exception { + + MvcResult result = mockMvc.perform(get("/api/customers?page=1&size=5")) + .andExpect(status().isOk()) + .andReturn(); + + MockHttpServletResponse response = result.getResponse(); + + JSONObject jsonObject = new JSONObject(response.getContentAsString()); + assertThat(jsonObject.get("totalPages")).isEqualTo(4); + assertThat(jsonObject.get("totalElements")).isEqualTo(20); + assertThat(jsonObject.get("number")).isEqualTo(1); + assertThat(jsonObject.get("size")).isEqualTo(5); + assertThat(jsonObject.get("content")).isNotNull(); + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/paging/CustomerServiceUnitTest.java b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/paging/CustomerServiceUnitTest.java new file mode 100644 index 000000000000..1a34822527a7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/paging/CustomerServiceUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.spring.data.jpa.paging; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; + +@ExtendWith(MockitoExtension.class) +public class CustomerServiceUnitTest { + + @Mock + private CustomerRepository customerRepository; + + @InjectMocks + private CustomerService customerService; + + private static final List ALL_CUSTOMERS = Arrays.asList( + new Customer("Ali"), new Customer("Brian"), + new Customer("Coddy"), new Customer("Di"), + new Customer("Eve"), new Customer("Fin"), + new Customer("Grace"), new Customer("Harry"), + new Customer("Ivan"), new Customer("Judy"), + new Customer("Kasim"), new Customer("Liam"), + new Customer("Mike"), new Customer("Nick"), + new Customer("Omar"), new Customer("Penny"), + new Customer("Queen"), new Customer("Rob"), + new Customer("Sue"), new Customer("Tammy")); + + private static final List PAGE_1_CONTENTS = Arrays.asList("Ali", "Brian", "Coddy", "Di", "Eve"); + + private static final List PAGE_2_CONTENTS = Arrays.asList("Fin", "Grace", "Harry", "Ivan", "Judy"); + + private static final List PAGE_3_CONTENTS = Arrays.asList("Kasim", "Liam", "Mike", "Nick", "Omar"); + + private static final List PAGE_4_CONTENTS = Arrays.asList("Penny", "Queen", "Rob", "Sue", "Tammy"); + + private static final List EMPTY_PAGE = Arrays.asList(); + + @BeforeEach + void setup() { + when(customerRepository.findAll()).thenReturn(ALL_CUSTOMERS); + } + + private static Collection testIO() { + return Arrays.asList(new Object[][] { + { 0, 5, PAGE_1_CONTENTS, 20L, 4L }, + { 1, 5, PAGE_2_CONTENTS, 20L, 4L }, + { 2, 5, PAGE_3_CONTENTS, 20L, 4L }, + { 3, 5, PAGE_4_CONTENTS, 20L, 4L }, + { 4, 5, EMPTY_PAGE, 20L, 4L } } + ); + } + + @ParameterizedTest + @MethodSource("testIO") + void givenAListOfCustomers_whenGetCustomers_thenReturnsDesiredDataAlongWithPagingInformation(int page, int size, List expectedNames, long expectedTotalElements, long expectedTotalPages) { + Page customers = customerService.getCustomers(page, size); + List names = customers.getContent() + .stream() + .map(Customer::getName) + .collect(Collectors.toList()); + + assertEquals(expectedNames.size(), names.size()); + assertEquals(expectedNames, names); + assertEquals(expectedTotalElements, customers.getTotalElements()); + assertEquals(expectedTotalPages, customers.getTotalPages()); + } +} diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md index 23134ec02d6f..dc94ba41d090 100644 --- a/persistence-modules/spring-data-jpa-repo-2/README.md +++ b/persistence-modules/spring-data-jpa-repo-2/README.md @@ -9,4 +9,5 @@ - [Difference Between JPA and Spring Data JPA](https://www.baeldung.com/spring-data-jpa-vs-jpa) - [Differences Between Spring Data JPA findFirst() and findTop()](https://www.baeldung.com/spring-data-jpa-findfirst-vs-findtop) - [Difference Between findBy and findAllBy in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-find-by-vs-find-all-by) +- [Unidirectional One-to-Many and Cascading Delete in JPA](https://www.baeldung.com/spring-jpa-unidirectional-one-to-many-and-cascading-delete) - More articles: [[<-- prev]](../spring-data-jpa-repo) diff --git a/persistence-modules/spring-data-jpa-repo-2/pom.xml b/persistence-modules/spring-data-jpa-repo-2/pom.xml index dd0406eca8e4..8186a0f7a532 100644 --- a/persistence-modules/spring-data-jpa-repo-2/pom.xml +++ b/persistence-modules/spring-data-jpa-repo-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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-data-jpa-repo-2 spring-data-jpa-repo-2 diff --git a/persistence-modules/spring-data-jpa-repo-3/README.md b/persistence-modules/spring-data-jpa-repo-3/README.md index dc33900736ac..d3782eb1e673 100644 --- a/persistence-modules/spring-data-jpa-repo-3/README.md +++ b/persistence-modules/spring-data-jpa-repo-3/README.md @@ -4,4 +4,5 @@ This module contains articles about Spring Data JPA. ### Relevant Articles: - [New CRUD Repository Interfaces in Spring Data 3](https://www.baeldung.com/spring-data-3-crud-repository-interfaces) +- [How to Persist a List of String in JPA?](https://www.baeldung.com/java-jpa-persist-string-list) - More articles: [[<-- prev]](../spring-data-jpa-repo-2) diff --git a/persistence-modules/spring-data-jpa-repo-3/pom.xml b/persistence-modules/spring-data-jpa-repo-3/pom.xml index 8cd8ca7f61f0..207e753ecd6a 100644 --- a/persistence-modules/spring-data-jpa-repo-3/pom.xml +++ b/persistence-modules/spring-data-jpa-repo-3/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 com.baeldung @@ -24,6 +25,7 @@ h2 runtime + org.springframework.boot spring-boot-starter-test @@ -31,5 +33,4 @@ - diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Library.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Library.java new file mode 100644 index 000000000000..04c0ad5e0a0a --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Library.java @@ -0,0 +1,66 @@ +package com.baeldung.spring.data.jpa.listrepositories.entity; + +import jakarta.persistence.*; + +import java.util.ArrayList; +import java.util.List; + +@Entity(name = "library") +public class Library { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + + @Convert(converter = StringListConverter.class) + @Column(name = "addresses", nullable = false) + private List addresses = new ArrayList<>(); + + @ElementCollection(targetClass = String.class, fetch = FetchType.EAGER) + @CollectionTable(name = "book", joinColumns = @JoinColumn(name = "library_id")) + @Column(name = "book", nullable = false) + private List books = new ArrayList<>(); + + public Library() { + } + + public Library(String name, List addresses, List books) { + this.name = name; + this.addresses = addresses; + this.books = books; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getAddresses() { + return addresses; + } + + public void setAddresses(List addresses) { + this.addresses = addresses; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/StringListConverter.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/StringListConverter.java new file mode 100644 index 000000000000..ffc097ee1804 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/StringListConverter.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.data.jpa.listrepositories.entity; + +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; + +import java.util.Arrays; +import java.util.List; + + +import static java.util.Collections.*; + +@Converter +public class StringListConverter implements AttributeConverter, String> { + private static final String SPLIT_CHAR = ";"; + + @Override + public String convertToDatabaseColumn(List stringList) { + return stringList != null ? String.join(SPLIT_CHAR, stringList) : ""; + } + + @Override + public List convertToEntityAttribute(String string) { + return string != null ? Arrays.asList(string.split(SPLIT_CHAR)) : emptyList(); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryRepository.java new file mode 100644 index 000000000000..71deb04b3eb0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.data.jpa.listrepositories.repository; + +import com.baeldung.spring.data.jpa.listrepositories.entity.Library; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +@Repository +public interface LibraryRepository extends CrudRepository { + @Query("SELECT l FROM library l JOIN FETCH l.books WHERE l.id = (:id)") + Library findById(@Param("id") long id); +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/Application.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/Application.java new file mode 100644 index 000000000000..94e54889f69c --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/Application.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.data.jpa.naturalid; + +import com.baeldung.spring.data.jpa.naturalid.repository.NaturalIdRepositoryImpl; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(SpringBootApplication.class, args); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/HotelRoomsService.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/HotelRoomsService.java new file mode 100644 index 000000000000..c8cd1fada4b5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/HotelRoomsService.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.data.jpa.naturalid; + +import com.baeldung.spring.data.jpa.naturalid.entity.ConferenceRoom; +import com.baeldung.spring.data.jpa.naturalid.entity.GuestRoom; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; + +import org.hibernate.Session; +import org.springframework.stereotype.Service; + +import java.util.Optional; + +@Service +public class HotelRoomsService { + + private final EntityManager entityManager; + + public HotelRoomsService(EntityManagerFactory entityManagerFactory) { + this.entityManager = entityManagerFactory.createEntityManager(); + } + + public Optional conferenceRoom(String name) { + Session session = entityManager.unwrap(Session.class); + return session.bySimpleNaturalId(ConferenceRoom.class) + .loadOptional(name); + } + + public Optional guestRoom(int roomNumber, int floor) { + Session session = entityManager.unwrap(Session.class); + return session.byNaturalId(GuestRoom.class) + .using("roomNumber", roomNumber) + .using("floor", floor) + .loadOptional(); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepositoryConfig.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepositoryConfig.java new file mode 100644 index 000000000000..94b96ca86c5e --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdRepositoryConfig.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.data.jpa.naturalid; + +import com.baeldung.spring.data.jpa.naturalid.repository.NaturalIdRepositoryImpl; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@Configuration +@EnableJpaRepositories(repositoryBaseClass = NaturalIdRepositoryImpl.class) +public class NaturalIdRepositoryConfig { +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/ConferenceRoom.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/ConferenceRoom.java new file mode 100644 index 000000000000..6ff7e48a3de6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/ConferenceRoom.java @@ -0,0 +1,49 @@ +package com.baeldung.spring.data.jpa.naturalid.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; + +import org.hibernate.annotations.NaturalId; + +@Entity +public class ConferenceRoom { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NaturalId + private String name; + + private int capacity; + + public ConferenceRoom(String name, int capacity) { + this.name = name; + this.capacity = capacity; + } + + protected ConferenceRoom() { + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public int getCapacity() { + return capacity; + } + + public void setCapacity(int capacity) { + this.capacity = capacity; + } + + @Override + public String toString() { + return "HotelRoom{" + "id=" + id + ", name='" + name + '\'' + ", capacity=" + capacity + '}'; + } +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/GuestRoom.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/GuestRoom.java new file mode 100644 index 000000000000..121917862581 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/entity/GuestRoom.java @@ -0,0 +1,67 @@ +package com.baeldung.spring.data.jpa.naturalid.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; + +import org.hibernate.annotations.NaturalId; + +@Entity +public class GuestRoom { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NaturalId + private Integer roomNumber; + + @NaturalId + private Integer floor; + + private String name; + private int capacity; + + public GuestRoom(int roomNumber, int floor, String name, int capacity) { + this.roomNumber = roomNumber; + this.floor = floor; + this.name = name; + this.capacity = capacity; + } + + protected GuestRoom() { + } + + public Long getId() { + return id; + } + + public Integer getRoomNumber() { + return roomNumber; + } + + public Integer getFloor() { + return floor; + } + + public int getCapacity() { + return capacity; + } + + public void setCapacity(int capacity) { + this.capacity = capacity; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "GuestRoom{" + "id=" + id + ", roomNumber=" + roomNumber + ", floor=" + floor + ", name=" + name + ", capacity=" + capacity + '}'; + } +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomRepository.java new file mode 100644 index 000000000000..d12695f40f69 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/ConferenceRoomRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.data.jpa.naturalid.repository; + +import com.baeldung.spring.data.jpa.naturalid.entity.ConferenceRoom; + +import org.springframework.stereotype.Repository; + +@Repository +public interface ConferenceRoomRepository extends NaturalIdRepository { +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepository.java new file mode 100644 index 000000000000..dd761d6660e2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/GuestRoomJpaRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.data.jpa.naturalid.repository; + +import com.baeldung.spring.data.jpa.naturalid.entity.GuestRoom; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface GuestRoomJpaRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepository.java new file mode 100644 index 000000000000..5fe710c0a542 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.data.jpa.naturalid.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.NoRepositoryBean; + +import java.util.Optional; + +@NoRepositoryBean +public interface NaturalIdRepository extends JpaRepository { + Optional naturalId(ID naturalId); +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepositoryImpl.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepositoryImpl.java new file mode 100644 index 000000000000..2c6e62e189c5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/naturalid/repository/NaturalIdRepositoryImpl.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.data.jpa.naturalid.repository; + +import jakarta.persistence.EntityManager; + +import org.hibernate.Session; +import org.springframework.data.jpa.repository.support.JpaEntityInformation; +import org.springframework.data.jpa.repository.support.SimpleJpaRepository; +import org.springframework.data.repository.NoRepositoryBean; +import org.springframework.transaction.annotation.Transactional; + +import java.io.Serializable; +import java.util.Optional; + +public class NaturalIdRepositoryImpl extends SimpleJpaRepository implements NaturalIdRepository { + private final EntityManager entityManager; + + public NaturalIdRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) { + super(entityInformation, entityManager); + this.entityManager = entityManager; + } + + @Override + public Optional naturalId(ID naturalId) { + return entityManager.unwrap(Session.class) + .bySimpleNaturalId(this.getDomainClass()) + .loadOptional(naturalId); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-repo-3/src/main/resources/application.properties index 8b137891791f..5a1841e2ad56 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/resources/application.properties @@ -1 +1,2 @@ - +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE diff --git a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryIntegrationTest.java new file mode 100644 index 000000000000..7bd1b904078f --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.data.jpa.listrepositories.repository; + +import com.baeldung.spring.data.jpa.listrepositories.entity.Library; +import jakarta.transaction.Transactional; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.Arrays; + +@SpringBootTest +public class LibraryIntegrationTest { + + @Autowired + private LibraryRepository libraryRepository; + + @Test + @Transactional + public void givenLibrary_whenGetAddressesAndGetBooks_thenGetListOfItems(){ + Library library = new Library(); + library.setAddresses(Arrays.asList("Address 1", "Address 2")); + library.setBooks(Arrays.asList("Book 1", "Book 2")); + + libraryRepository.save(library); + Library lib = libraryRepository.findById(library.getId().longValue()); + + Assertions.assertEquals(2, lib.getAddresses().size()); + Assertions.assertEquals(2, lib.getBooks().size()); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdIntegrationTest.java new file mode 100644 index 000000000000..96cc805082b7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/naturalid/NaturalIdIntegrationTest.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.data.jpa.naturalid; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Optional; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import com.baeldung.spring.data.jpa.naturalid.entity.ConferenceRoom; +import com.baeldung.spring.data.jpa.naturalid.entity.GuestRoom; +import com.baeldung.spring.data.jpa.naturalid.repository.ConferenceRoomRepository; +import com.baeldung.spring.data.jpa.naturalid.repository.GuestRoomJpaRepository; + +@SpringBootTest +class NaturalIdIntegrationTest { + + @Autowired + private HotelRoomsService service; + + @Autowired + private GuestRoomJpaRepository guestRoomJpaRepository; + @Autowired + private ConferenceRoomRepository conferenceRoomRepository; + + @Test + void whenWeFindByNaturalKey_thenEntityIsReturnedCorrectly() { + guestRoomJpaRepository.save(new GuestRoom(23, 3, "B-423", 4)); + + Optional result = service.guestRoom(23, 3); + + assertThat(result).isPresent() + .hasValueSatisfying(room -> "B-423".equals(room.getName())); + } + + @Test + void whenWeFindBySimpleNaturalKey_thenEntityIsReturnedCorrectly() { + conferenceRoomRepository.save(new ConferenceRoom("Colorado", 100)); + + Optional result = service.conferenceRoom("Colorado"); + + assertThat(result).isPresent() + .hasValueSatisfying(room -> "Colorado".equals(room.getName())); + } + + @Test + void givenNaturalIdRepository_whenWeFindBySimpleNaturalKey_thenEntityIsReturnedCorrectly() { + conferenceRoomRepository.save(new ConferenceRoom("Nevada", 200)); + + Optional result = conferenceRoomRepository.naturalId("Nevada"); + + assertThat(result).isPresent() + .hasValueSatisfying(room -> "Nevada".equals(room.getName())); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java index 76cdf41d819f..8f86e8ce495a 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java @@ -2,6 +2,8 @@ import com.baeldung.derivedquery.entity.User; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import java.time.ZonedDateTime; import java.util.Collection; @@ -49,9 +51,12 @@ public interface UserRepository extends JpaRepository { List findByAgeIn(Collection ages); - List findByNameOrBirthDate(String name, ZonedDateTime birthDate); + @Query(value = "select * from users where (name = :nameParam OR birth_date <> :birthDateParam)", nativeQuery = true) + List findByNameOrBirthDate(@Param(value = "nameParam") String nameParam, @Param(value = "birthDateParam") ZonedDateTime birthDateParam); - List findByNameOrBirthDateAndActive(String name, ZonedDateTime birthDate, Boolean active); + @Query(value = "select * from users where (name = :nameParam OR birth_date <> :birthDateParam) and active = :activeParam", nativeQuery = true) + List findByNameOrBirthDateAndActive(@Param(value = "nameParam") String nameParam, @Param(value = "birthDateParam") ZonedDateTime birthDateParam, + @Param(value = "activeParam") Boolean activeParam); List findByNameOrderByName(String name); diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java index 2a6e166b886a..75e0db253f16 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java @@ -161,7 +161,7 @@ public void whenByNameOrBirthDate() { @Test public void whenByNameOrBirthDateAndActive() { - assertEquals(3, userRepository.findByNameOrBirthDateAndActive(USER_NAME_ADAM, BIRTHDATE, false).size()); + assertEquals(2, userRepository.findByNameOrBirthDateAndActive(USER_NAME_ADAM, BIRTHDATE, false).size()); } @Test diff --git a/persistence-modules/spring-jooq/pom.xml b/persistence-modules/spring-jooq/pom.xml index 9848c726c542..d12a9212123f 100644 --- a/persistence-modules/spring-jooq/pom.xml +++ b/persistence-modules/spring-jooq/pom.xml @@ -195,11 +195,11 @@ - 3.14.15 + 3.16.18 1.0.0 1.5 1.0.0 - 1.4.200 + 2.1.214 \ No newline at end of file diff --git a/pom.xml b/pom.xml index 0f532beaf22f..764eccdac996 100644 --- a/pom.xml +++ b/pom.xml @@ -1,8 +1,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 parent-modules @@ -222,6 +222,9 @@ maven-war-plugin ${maven-war-plugin.version} + + false + @@ -328,12 +331,12 @@ parent-boot-2 parent-spring-4 parent-spring-5 + parent-spring-6 parent-java - checker-plugin - + checker-framework + - core-java-modules/core-java core-java-modules/core-java-8 core-java-modules/core-java-8-2 core-java-modules/core-java-8-datetime @@ -347,29 +350,25 @@ core-java-modules/core-java-collections-conversions-2 core-java-modules/core-java-streams-2 - couchbase gradle-modules/gradle/maven-to-gradle - java-jdi - - jetbrains - jhipster-5 - jmh language-interop - libraries-3 - lombok-modules + libraries-jdk8 - muleesb + lombok-modules/lombok-custom - osgi - persistence-modules - web-modules + muleesb + web-modules/java-lite + web-modules/restx + persistence-modules/deltaspike + persistence-modules/hibernate-ogm + persistence-modules/java-cassandra @@ -412,36 +411,22 @@ parent-boot-2 parent-spring-4 parent-spring-5 + parent-spring-6 parent-java spring-4 - spring-aop - spring-bom spring-cloud-modules - - spring-exceptions - spring-integration - spring-jenkins-pipeline - spring-security-modules - spring-shell spring-soap - spring-spel spring-static-resources spring-swagger-codegen - spring-vault spring-web-modules - spring-websockets - static-analysis testing-modules - vertx-modules video-tutorials - xml - xml-2 @@ -481,22 +466,14 @@ parent-boot-2 parent-spring-4 parent-spring-5 + parent-spring-6 parent-java apache-spark image-processing - jenkins-modules jhipster-modules - jhipster-5 - jws - - libraries - libraries-4 - libraries-5 - libraries-6 - @@ -530,12 +507,12 @@ parent-boot-2 parent-spring-4 parent-spring-5 + parent-spring-6 parent-java - checker-plugin - + checker-framework + - core-java-modules/core-java core-java-modules/core-java-8 core-java-modules/core-java-8-2 core-java-modules/core-java-8-datetime @@ -549,27 +526,24 @@ core-java-modules/core-java-collections-conversions-2 core-java-modules/core-java-streams-2 - couchbase gradle-modules/gradle/maven-to-gradle - java-jdi - - jhipster-5 - jmh language-interop - libraries-3 - lombok-modules - muleesb + libraries-jdk8 - osgi - persistence-modules - web-modules + lombok-modules/lombok-custom + muleesb + web-modules/java-lite + web-modules/restx + persistence-modules/deltaspike + persistence-modules/hibernate-ogm + persistence-modules/java-cassandra @@ -604,35 +578,22 @@ parent-boot-2 parent-spring-4 parent-spring-5 + parent-spring-6 parent-java spring-4 - spring-bom spring-cloud-modules - - spring-exceptions - spring-integration - spring-jenkins-pipeline - spring-security-modules - spring-shell spring-soap - spring-spel spring-static-resources spring-swagger-codegen - spring-vault spring-web-modules - spring-websockets - static-analysis testing-modules - vertx-modules video-tutorials - xml - xml-2 @@ -664,21 +625,14 @@ parent-boot-2 parent-spring-4 parent-spring-5 + parent-spring-6 parent-java apache-spark image-processing - jenkins-modules jhipster-modules - jhipster-5 - jws - - libraries - libraries-4 - libraries-5 - libraries-6 @@ -744,6 +698,8 @@ + lombok-modules + osgi spring-katharsis logging-modules spring-boot-modules @@ -767,6 +723,7 @@ javafx spring-batch + spring-batch-2 spring-boot-rest spring-drools spring-exceptions @@ -789,7 +746,6 @@ server-modules apache-cxf-modules - spring-aop jmeter spring-aop-2 @@ -815,28 +771,26 @@ custom-pmd - spring-core-6 data-structures ddd-contexts jackson-modules + jmh deeplearning4j docker-modules drools guava-modules kubernetes-modules libraries-concurrency + jhipster-6 libraries-testing maven-modules optaplanner - persistence-modules/sirix - persistence-modules/spring-data-cassandra-2 - persistence-modules/spring-data-jpa-repo-3 + persistence-modules quarkus-modules spring-reactive-modules spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions - persistence-modules/fauna - persistence-modules/spring-data-rest + testing-modules/mockito-simple rule-engines-modules @@ -847,6 +801,8 @@ tablesaw geotools + jws + akka-modules @@ -858,7 +814,6 @@ apache-olingo apache-poi-2 - apache-rocketmq apache-thrift apache-tika @@ -869,9 +824,8 @@ axon bazel - code-generation + google-auto-project ddd - discord4j disruptor dozer dubbo @@ -883,13 +837,14 @@ hystrix jackson-simple java-blockchain - + java-jdi java-rmi java-spi javax-sound javaxval javaxval-2 javax-validation-advanced + jetbrains jgit jib @@ -897,8 +852,13 @@ jsoup ksqldb jsf + + libraries libraries-2 - libraries-7 + libraries-4 + libraries-5 + libraries-6 + libraries-apache-commons libraries-apache-commons-collections libraries-apache-commons-io @@ -911,6 +871,7 @@ libraries-primitive libraries-rpc libraries-server + libraries-transform lucene mapstruct @@ -923,7 +884,6 @@ protobuffer reactor-core rsocket - slack @@ -931,10 +891,10 @@ spring-5-webflux spring-5-webflux-2 spring-activiti - spring-batch-2 + spring-actuator spring-core-2 spring-core-3 - spring-core-5 + spring-credhub spring-di-3 spring-cucumber @@ -948,16 +908,25 @@ spring-scheduling spring-state-machine + spring-shell + spring-spel spring-threads + spring-vault + spring-websockets + static-analysis tensorflow-java + vertx-modules xstream webrtc - persistence-modules/java-mongodb messaging-modules - persistence-modules/questdb vaadin + libraries-3 + web-modules + jenkins-modules + xml + xml-2 @@ -991,6 +960,8 @@ + lombok-modules + osgi spring-katharsis logging-modules spring-boot-modules @@ -1014,6 +985,7 @@ javafx spring-batch + spring-batch-2 spring-boot-rest spring-drools spring-exceptions @@ -1060,10 +1032,10 @@ spring-aop spring-aop-2 custom-pmd - spring-core-6 data-structures ddd-contexts jackson-modules + jmh deeplearning4j jmeter docker-modules @@ -1071,18 +1043,16 @@ guava-modules kubernetes-modules libraries-concurrency + jhipster-6 libraries-testing maven-modules optaplanner - persistence-modules/sirix - persistence-modules/spring-data-cassandra-2 - persistence-modules/spring-data-jpa-repo-3 + persistence-modules quarkus-modules spring-reactive-modules spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions - persistence-modules/fauna - persistence-modules/spring-data-rest + testing-modules/mockito-simple rule-engines-modules @@ -1093,6 +1063,8 @@ tablesaw geotools + jws + akka-modules @@ -1103,7 +1075,6 @@ apache-olingo apache-poi-2 - apache-rocketmq apache-thrift apache-tika @@ -1114,9 +1085,8 @@ axon bazel - code-generation + google-auto-project ddd - discord4j disruptor dozer @@ -1130,13 +1100,14 @@ hystrix jackson-simple java-blockchain - + java-jdi java-rmi java-spi javax-sound javaxval javaxval-2 javax-validation-advanced + jetbrains jgit jib @@ -1145,7 +1116,11 @@ jsf ksqldb - libraries-7 + libraries + libraries-2 + libraries-4 + libraries-5 + libraries-6 libraries-apache-commons libraries-apache-commons-collections libraries-apache-commons-io @@ -1155,9 +1130,11 @@ libraries-http libraries-http-2 libraries-io + libraries-ai libraries-primitive libraries-rpc libraries-server + libraries-transform lucene mapstruct @@ -1170,7 +1147,6 @@ protobuffer reactor-core rsocket - slack @@ -1179,10 +1155,9 @@ spring-5-webflux spring-5-webflux-2 spring-activiti - spring-batch-2 spring-core-2 spring-core-3 - spring-core-5 + spring-credhub spring-di-3 spring-cucumber @@ -1195,16 +1170,25 @@ spring-scheduling spring-state-machine + spring-shell + spring-spel spring-threads + spring-vault + spring-websockets + static-analysis tensorflow-java + vertx-modules xstream webrtc - persistence-modules/java-mongodb - libraries-2 + messaging-modules - persistence-modules/questdb vaadin + libraries-3 + web-modules + jenkins-modules + xml + xml-2 @@ -1222,6 +1206,7 @@ parent-boot-2 parent-spring-4 parent-spring-5 + parent-spring-6 parent-java @@ -1257,6 +1242,7 @@ 1.12.13 + 1.7.32 1.2.7 @@ -1275,7 +1261,7 @@ 2.6 3.12.0 1.5.0 - 3.0.0 + 3.3.2 4.0.1 1.2 2.3.3 diff --git a/quarkus-modules/quarkus-funqy/pom.xml b/quarkus-modules/quarkus-funqy/pom.xml index 603f45828717..ae9c34e7e036 100644 --- a/quarkus-modules/quarkus-funqy/pom.xml +++ b/quarkus-modules/quarkus-funqy/pom.xml @@ -1,133 +1,134 @@ - - 4.0.0 - com.baeldung.quarkus - quarkus-funqy - 1.0.0-SNAPSHOT - - 3.10.1 - false - 17 - UTF-8 - UTF-8 - quarkus-bom - io.quarkus.platform - 2.16.0.Final - 3.0.0-M7 - - - com.baeldung - quarkus-modules + 4.0.0 + com.baeldung.quarkus + quarkus-funqy 1.0.0-SNAPSHOT - - + + 3.10.1 + false + 17 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 2.16.0.Final + 3.0.0-M7 + + + com.baeldung + quarkus-modules + 1.0.0-SNAPSHOT + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + - - ${quarkus.platform.group-id} - ${quarkus.platform.artifact-id} - ${quarkus.platform.version} - pom - import - + + io.quarkus + quarkus-funqy-http + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-funqy-knative-events + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + - - - - io.quarkus - quarkus-funqy-http - - - io.quarkus - quarkus-arc - - - io.quarkus - quarkus-funqy-knative-events - - - io.quarkus - quarkus-junit5 - test - - - io.rest-assured - rest-assured - test - - - - - - ${quarkus.platform.group-id} - quarkus-maven-plugin - ${quarkus.platform.version} - true - - - - build - generate-code - generate-code-tests - - - - - - maven-compiler-plugin - ${compiler-plugin.version} - - - -parameters - - - - - maven-surefire-plugin - ${surefire-plugin.version} - - - org.jboss.logmanager.LogManager - ${maven.home} - - - - - - - - native - - - native - - - + - - maven-failsafe-plugin - ${surefire-plugin.version} - - - - integration-test - verify - + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + + + + + + maven-compiler-plugin + ${compiler-plugin.version} - - ${project.build.directory}/${project.build.finalName}-runner - org.jboss.logmanager.LogManager - ${maven.home} - + + -parameters + - - - + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + - - - native - - - + + + + native + + + native + + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + native + + + diff --git a/discord4j/.gitignore b/saas-modules/discord4j/.gitignore similarity index 100% rename from discord4j/.gitignore rename to saas-modules/discord4j/.gitignore diff --git a/discord4j/README.md b/saas-modules/discord4j/README.md similarity index 100% rename from discord4j/README.md rename to saas-modules/discord4j/README.md diff --git a/discord4j/pom.xml b/saas-modules/discord4j/pom.xml similarity index 90% rename from discord4j/pom.xml rename to saas-modules/discord4j/pom.xml index 3ea85c05c7a5..ff398dd1a390 100644 --- a/discord4j/pom.xml +++ b/saas-modules/discord4j/pom.xml @@ -3,17 +3,14 @@ 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 discord4j - 0.0.1-SNAPSHOT discord4j Demo Discord bot using Discord4J + Spring Boot com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 + saas-modules + 1.0.0-SNAPSHOT diff --git a/discord4j/src/main/java/com/baeldung/discordbot/BotConfiguration.java b/saas-modules/discord4j/src/main/java/com/baeldung/discordbot/BotConfiguration.java similarity index 100% rename from discord4j/src/main/java/com/baeldung/discordbot/BotConfiguration.java rename to saas-modules/discord4j/src/main/java/com/baeldung/discordbot/BotConfiguration.java diff --git a/discord4j/src/main/java/com/baeldung/discordbot/DiscordBotApplication.java b/saas-modules/discord4j/src/main/java/com/baeldung/discordbot/DiscordBotApplication.java similarity index 100% rename from discord4j/src/main/java/com/baeldung/discordbot/DiscordBotApplication.java rename to saas-modules/discord4j/src/main/java/com/baeldung/discordbot/DiscordBotApplication.java diff --git a/discord4j/src/main/java/com/baeldung/discordbot/events/EventListener.java b/saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/EventListener.java similarity index 100% rename from discord4j/src/main/java/com/baeldung/discordbot/events/EventListener.java rename to saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/EventListener.java diff --git a/discord4j/src/main/java/com/baeldung/discordbot/events/MessageCreateListener.java b/saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/MessageCreateListener.java similarity index 100% rename from discord4j/src/main/java/com/baeldung/discordbot/events/MessageCreateListener.java rename to saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/MessageCreateListener.java diff --git a/discord4j/src/main/java/com/baeldung/discordbot/events/MessageListener.java b/saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/MessageListener.java similarity index 100% rename from discord4j/src/main/java/com/baeldung/discordbot/events/MessageListener.java rename to saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/MessageListener.java diff --git a/discord4j/src/main/java/com/baeldung/discordbot/events/MessageUpdateListener.java b/saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/MessageUpdateListener.java similarity index 100% rename from discord4j/src/main/java/com/baeldung/discordbot/events/MessageUpdateListener.java rename to saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/MessageUpdateListener.java diff --git a/discord4j/src/main/resources/application.yml b/saas-modules/discord4j/src/main/resources/application.yml similarity index 100% rename from discord4j/src/main/resources/application.yml rename to saas-modules/discord4j/src/main/resources/application.yml diff --git a/discord4j/src/test/java/com/baeldung/discordbot/DiscordBotLiveTest.java b/saas-modules/discord4j/src/test/java/com/baeldung/discordbot/DiscordBotLiveTest.java similarity index 100% rename from discord4j/src/test/java/com/baeldung/discordbot/DiscordBotLiveTest.java rename to saas-modules/discord4j/src/test/java/com/baeldung/discordbot/DiscordBotLiveTest.java diff --git a/saas-modules/jira-rest-integration/pom.xml b/saas-modules/jira-rest-integration/pom.xml index ebf36646e4e3..f98320bafab1 100644 --- a/saas-modules/jira-rest-integration/pom.xml +++ b/saas-modules/jira-rest-integration/pom.xml @@ -45,7 +45,7 @@ -Xmx300m -XX:+UseParallelGC -classpath - + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed diff --git a/saas-modules/pom.xml b/saas-modules/pom.xml index 7e8adebdd9d5..16ed50918c5c 100644 --- a/saas-modules/pom.xml +++ b/saas-modules/pom.xml @@ -16,11 +16,13 @@ + 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 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 lines) throws Exception { + public void write(Chunk 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 list) { - for (T listItem : list) { + public void write(Chunk 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> select() { + List> results = new ArrayList<>(); + try { + Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement(); + statement.executeQuery("SELECT * FROM student"); + connection.commit(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + return results; + } + + @RequestMapping("/rollback") + public List> rollback() { + List> results = new ArrayList<>(); + try (Connection connection = dataSource.getConnection()) { + connection.rollback(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + return results; + } + + @RequestMapping("/query-error") + public void error() { + try (Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("SELECT UNDEFINED()"); + } catch (Exception ignored) { + } + } +} diff --git a/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/controllers/StudentController.java b/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/controllers/StudentController.java new file mode 100644 index 000000000000..d60fd8b52eb1 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/controllers/StudentController.java @@ -0,0 +1,29 @@ +package com.baeldung.p6spy.controllers; + +import com.baeldung.p6spy.repository.Student; +import com.baeldung.p6spy.repository.StudentRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("student") +public class StudentController { + + @Autowired + private StudentRepository repository; + + @RequestMapping("/save") + public Long save() { + return repository.save(new Student("Pablo", "Picasso")).getId(); + } + + @RequestMapping("/find/{name}") + public List getAll(@PathVariable String name) { + return repository.findAllByFirstName(name); + } + +} diff --git a/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/repository/Student.java b/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/repository/Student.java new file mode 100644 index 000000000000..881f9409b889 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/repository/Student.java @@ -0,0 +1,53 @@ +package com.baeldung.p6spy.repository; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue + private Long id; + + private String firstName; + private String lastName; + + public Student() { + } + + public Student(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = 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; + } + + @Override + public String toString() { + return "Student{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}'; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/repository/StudentRepository.java b/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/repository/StudentRepository.java new file mode 100644 index 000000000000..90d2c2287769 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-observation/src/main/java/com/baeldung/p6spy/repository/StudentRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.p6spy.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface StudentRepository extends JpaRepository { + List findAllByFirstName(String firstName); +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3-observation/src/main/resources/spy.properties b/spring-boot-modules/spring-boot-3-observation/src/main/resources/spy.properties new file mode 100644 index 000000000000..c14d381836b3 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-observation/src/main/resources/spy.properties @@ -0,0 +1,36 @@ +# specifies the appender to use for logging +# Please note: reload means forgetting all the previously set +# settings (even those set during runtime - via JMX) +# and starting with the clean table +# (only the properties read from the configuration file) +# (default is com.p6spy.engine.spy.appender.FileLogger) +#appender=com.p6spy.engine.spy.appender.Slf4JLogger +#appender=com.p6spy.engine.spy.appender.StdoutLogger +appender=com.p6spy.engine.spy.appender.FileLogger + +# name of logfile to use, note Windows users should make sure to use forward slashes in their pathname (e:/test/spy.log) +# (used for com.p6spy.engine.spy.appender.FileLogger only) +# (default is spy.log) +logfile=database.log + +# append to the p6spy log file. if this is set to false the +# log file is truncated every time. (file logger only) +# (default is true) +append=true + +# class to use for formatting log messages (default is: com.p6spy.engine.spy.appender.SingleLineFormat) +logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat + +# Custom log message format used ONLY IF logMessageFormat is set to com.p6spy.engine.spy.appender.CustomLineFormat +# default is %(currentTime)|%(executionTime)|%(category)|connection%(connectionId)|%(sqlSingleLine) +# Available placeholders are: +# %(connectionId) the id of the connection +# %(currentTime) the current time expressing in milliseconds +# %(executionTime) the time in milliseconds that the operation took to complete +# %(category) the category of the operation +# %(effectiveSql) the SQL statement as submitted to the driver +# %(effectiveSqlSingleLine) the SQL statement as submitted to the driver, with all new lines removed +# %(sql) the SQL statement with all bind variables replaced with actual values +# %(sqlSingleLine) the SQL statement with all bind variables replaced with actual values, with all new lines removed +customLogMessageFormat=%(currentTime)|%(executionTime)|%(category)|%(sqlSingleLine) + diff --git a/spring-boot-modules/spring-boot-3-observation/src/test/java/com/baeldung/p6spy/JDBCControllerIntegrationTest.java b/spring-boot-modules/spring-boot-3-observation/src/test/java/com/baeldung/p6spy/JDBCControllerIntegrationTest.java new file mode 100644 index 000000000000..433641fcb03f --- /dev/null +++ b/spring-boot-modules/spring-boot-3-observation/src/test/java/com/baeldung/p6spy/JDBCControllerIntegrationTest.java @@ -0,0 +1,53 @@ +/* + * Copyright 2017 the original author or 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 + * + * http://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. + */ + +package com.baeldung.p6spy; + +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.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.web.client.RestTemplate; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +class JDBCControllerIntegrationTest { + + private final RestTemplate restTemplate = new RestTemplate(); + @Value("http://localhost:${local.server.port}/jdbc") + private String localhost; + + @Test + void testJdbcCommitRESTMethod_isSuccessful() { + Assertions.assertTrue(restTemplate.getForEntity(localhost + "/commit", String.class) + .getStatusCode().is2xxSuccessful()); + } + + @Test + void jdbcRollbackRESTMethod_isSuccessful() { + Assertions.assertTrue(restTemplate.getForEntity(localhost + "/rollback", String.class) + .getStatusCode().is2xxSuccessful()); + } + + @Test + void jdbcQueryErrorRESTMethod_isSuccessful() { + Assertions.assertTrue(restTemplate.getForEntity(localhost + "/query-error", String.class) + .getStatusCode().is2xxSuccessful()); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3-observation/src/test/java/com/baeldung/p6spy/SampleP6SpyApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-3-observation/src/test/java/com/baeldung/p6spy/SampleP6SpyApplicationIntegrationTest.java new file mode 100644 index 000000000000..ba6dd4319598 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-observation/src/test/java/com/baeldung/p6spy/SampleP6SpyApplicationIntegrationTest.java @@ -0,0 +1,49 @@ +/* + * Copyright 2021 the original author or 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 + * + * http://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. + */ + +package com.baeldung.p6spy; + +import com.github.gavlyukovskiy.boot.jdbc.decorator.DecoratedDataSource; +import com.github.gavlyukovskiy.boot.jdbc.decorator.p6spy.P6SpyDataSourceDecorator; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import javax.sql.DataSource; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(SpringExtension.class) +@SpringBootTest +class SampleP6SpyApplicationIntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + void whenP6SpyEnabled_datasourceIsDecorated() { + assertThat(dataSource).isInstanceOf(DecoratedDataSource.class); + } + + @Test + void whenP6SpyEnabled_decoratingChainContainsP6Spy() { + DecoratedDataSource decoratedDataSource = (DecoratedDataSource) dataSource; + assertThat(decoratedDataSource.getDecoratingChain().get(0).getDataSourceDecorator()).isInstanceOf(P6SpyDataSourceDecorator.class); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3-observation/src/test/resources/spy.properties b/spring-boot-modules/spring-boot-3-observation/src/test/resources/spy.properties new file mode 100644 index 000000000000..ea4525df980e --- /dev/null +++ b/spring-boot-modules/spring-boot-3-observation/src/test/resources/spy.properties @@ -0,0 +1,3 @@ +# specifies the appender to use for logging. +# used to avoid the creation of logging file with tests. +appender=com.p6spy.engine.spy.appender.StdoutLogger \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/pom.xml b/spring-boot-modules/spring-boot-3-test-pitfalls/pom.xml index 90e4ba022a5f..21a7e5f70288 100644 --- a/spring-boot-modules/spring-boot-3-test-pitfalls/pom.xml +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/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-test-pitfalls 0.0.1-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-3-url-matching/README.md b/spring-boot-modules/spring-boot-3-url-matching/README.md new file mode 100644 index 000000000000..577849c0e146 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-url-matching/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [URL Matching in Spring Boot 3](https://www.baeldung.com/spring-boot-3-url-matching) diff --git a/spring-boot-modules/spring-boot-3-url-matching/pom.xml b/spring-boot-modules/spring-boot-3-url-matching/pom.xml new file mode 100644 index 000000000000..ca8213e1cf1c --- /dev/null +++ b/spring-boot-modules/spring-boot-3-url-matching/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + spring-boot-3 + 0.0.1-SNAPSHOT + spring-boot-3 + URL Matching in Spring Boot + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-hateoas + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-starter-test + + + org.springframework + spring-test + 6.0.6 + test + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + org.springframework.boot + spring-boot-starter-webflux + + + io.projectreactor + reactor-core + 3.5.4 + + + io.projectreactor + reactor-test + 3.5.4 + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + 3.0.0-M7 + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/URLMatchingApplication.java b/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/URLMatchingApplication.java new file mode 100644 index 000000000000..914f2e1e539b --- /dev/null +++ b/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/URLMatchingApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.sample; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; + +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) +public class URLMatchingApplication { + public static void main(String[] args) { + SpringApplication.run(URLMatchingApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/config/WebConfig.java b/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/config/WebConfig.java new file mode 100644 index 000000000000..d4b70c63fa70 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/config/WebConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.sample.config; + +import com.baeldung.sample.filters.TrailingSlashRedirectFilterReactive; +import jakarta.servlet.Filter; +import org.springframework.web.server.WebFilter; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.sample.filters.TrailingSlashRedirectFilter; + + + +@Configuration +public class WebConfig { + @Bean + public WebFilter trailingSlashRedirectReactiveFilter() { + return new TrailingSlashRedirectFilterReactive(); + } + @Bean + public Filter trailingSlashRedirectFilter() { + return new TrailingSlashRedirectFilter(); + } + @Bean + public FilterRegistrationBean trailingSlashFilter() { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(trailingSlashRedirectFilter()); + registrationBean.addUrlPatterns("/*"); + return registrationBean; + } +} diff --git a/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/filters/TrailingSlashRedirectFilter.java b/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/filters/TrailingSlashRedirectFilter.java new file mode 100644 index 000000000000..6db83b73f245 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/filters/TrailingSlashRedirectFilter.java @@ -0,0 +1,52 @@ +package com.baeldung.sample.filters; + +import java.io.IOException; +import jakarta.servlet.http.HttpServletRequestWrapper; +import org.springframework.stereotype.Component; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; + +@Component +public class TrailingSlashRedirectFilter implements Filter { + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + String path = httpRequest.getRequestURI(); + + if (path.endsWith("/")) { + String newPath = path.substring(0, path.length() - 1); + HttpServletRequest newRequest = new CustomHttpServletRequestWrapper(httpRequest, newPath); + chain.doFilter(newRequest, response); + } else { + chain.doFilter(request, response); + } + } + + private static class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper { + + private final String newPath; + + public CustomHttpServletRequestWrapper(HttpServletRequest request, String newPath) { + super(request); + this.newPath = newPath; + } + + @Override + public String getRequestURI() { + return newPath; + } + + @Override + public StringBuffer getRequestURL() { + StringBuffer url = new StringBuffer(); + url.append(getScheme()).append("://").append(getServerName()).append(":").append(getServerPort()) + .append(newPath); + return url; + } + } +} diff --git a/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/filters/TrailingSlashRedirectFilterReactive.java b/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/filters/TrailingSlashRedirectFilterReactive.java new file mode 100644 index 000000000000..f983d8144138 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/filters/TrailingSlashRedirectFilterReactive.java @@ -0,0 +1,27 @@ +package com.baeldung.sample.filters; + +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilter; +import org.springframework.web.server.WebFilterChain; + +import reactor.core.publisher.Mono; + +@Component +public class TrailingSlashRedirectFilterReactive implements WebFilter { + + @Override + public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { + ServerHttpRequest request = exchange.getRequest(); + String path = request.getPath().value(); + + if (path.endsWith("/")) { + String newPath = path.substring(0, path.length() - 1); + ServerHttpRequest newRequest = request.mutate().path(newPath).build(); + return chain.filter(exchange.mutate().request(newRequest).build()); + } + + return chain.filter(exchange); + } +} diff --git a/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/resources/GreetingsController.java b/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/resources/GreetingsController.java new file mode 100644 index 000000000000..5c98ed764ef7 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/resources/GreetingsController.java @@ -0,0 +1,19 @@ +package com.baeldung.sample.resources; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class GreetingsController { + + @GetMapping("/some/greeting") + public String greeting() { + return "Hello"; + } + + @GetMapping("/some/greeting/") + public String greetingTrailingSlash() { + return "Hello with slash"; + } + +} diff --git a/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/resources/GreetingsControllerReactive.java b/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/resources/GreetingsControllerReactive.java new file mode 100644 index 000000000000..fde353ac43d2 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-url-matching/src/main/java/com/baeldung/sample/resources/GreetingsControllerReactive.java @@ -0,0 +1,20 @@ +package com.baeldung.sample.resources; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Mono; + +@RestController +public class GreetingsControllerReactive { + + @GetMapping("/some/reactive/greeting") + public Mono greeting() { + return Mono.just("Hello reactive"); + } + + @GetMapping("/some/reactive/greeting/") + public Mono greetingTrailingSlash() { + return Mono.just("Hello with slash reactive"); + } +} diff --git a/spring-boot-modules/spring-boot-3-url-matching/src/main/resources/application.yml b/spring-boot-modules/spring-boot-3-url-matching/src/main/resources/application.yml new file mode 100644 index 000000000000..8d047336f6aa --- /dev/null +++ b/spring-boot-modules/spring-boot-3-url-matching/src/main/resources/application.yml @@ -0,0 +1,7 @@ +spring: + mvc: + throw-exception-if-no-handler-found: true + jackson: + deserialization: + FAIL_ON_UNKNOWN_PROPERTIES: true + property-naming-strategy: SNAKE_CASE diff --git a/spring-boot-modules/spring-boot-3-url-matching/src/test/java/com/baeldung/sample/resources/GreetingsControllerApiIntegrationTest.java b/spring-boot-modules/spring-boot-3-url-matching/src/test/java/com/baeldung/sample/resources/GreetingsControllerApiIntegrationTest.java new file mode 100644 index 000000000000..754ef4aafe5f --- /dev/null +++ b/spring-boot-modules/spring-boot-3-url-matching/src/test/java/com/baeldung/sample/resources/GreetingsControllerApiIntegrationTest.java @@ -0,0 +1,45 @@ +package com.baeldung.sample.resources; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +@WebMvcTest(controllers = GreetingsController.class) +class GreetingsControllerApiIntegrationTest { + + private static final String BASEURL = "/some"; + private static final String DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_JSON_VALUE; + + @Autowired + MockMvc mvc; + + @Test + public void testGreeting() throws Exception { + mvc.perform(get(BASEURL + "/greeting").accept(DEFAULT_MEDIA_TYPE)) + .andExpect(status().isOk()) + .andExpect(content().string("Hello")); + } + + @Test + @Disabled("Disabled while TrailingSlashRedirectFilter is in use.") + public void testGreetingTrailingSlash() throws Exception { + mvc.perform(get(BASEURL + "/greeting/").accept(DEFAULT_MEDIA_TYPE)) + .andExpect(status().isOk()) + .andExpect(content().string("Hello with slash")); + } + + @Test + public void testGreetingTrailingSlashWithFilter() throws Exception { + mvc.perform(get(BASEURL + "/greeting/").accept(DEFAULT_MEDIA_TYPE)) + .andExpect(status().isOk()) + .andExpect(content().string("Hello")); + } + +} diff --git a/spring-boot-modules/spring-boot-3-url-matching/src/test/java/com/baeldung/sample/resources/GreetingsControllerReactiveApiIntegrationTest.java b/spring-boot-modules/spring-boot-3-url-matching/src/test/java/com/baeldung/sample/resources/GreetingsControllerReactiveApiIntegrationTest.java new file mode 100644 index 000000000000..9d5e439a747d --- /dev/null +++ b/spring-boot-modules/spring-boot-3-url-matching/src/test/java/com/baeldung/sample/resources/GreetingsControllerReactiveApiIntegrationTest.java @@ -0,0 +1,46 @@ +package com.baeldung.sample.resources; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; +import org.springframework.test.web.reactive.server.WebTestClient; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@WebFluxTest +public class GreetingsControllerReactiveApiIntegrationTest { + private static final String BASEURL = "/some/reactive"; + @Autowired + private WebTestClient webClient; + @Test + public void testGreeting() { + webClient.get().uri( BASEURL + "/greeting") + .exchange() + .expectStatus().isOk() + .expectBody().consumeWith(result -> { + String responseBody = new String(result.getResponseBody()); + assertTrue(responseBody.contains("Hello reactive")); + }); + } + @Test + @Disabled("Disabled while TrailingSlashRedirectFilter is in use.") + public void testGreetingTrailingSlash() { + webClient.get().uri(BASEURL + "/greeting/") + .exchange() + .expectStatus().isOk() + .expectBody().consumeWith(result -> { + String responseBody = new String(result.getResponseBody()); + assertTrue(responseBody.contains("Hello with slash reactive")); + }); + } + @Test + public void testGreetingTrailingSlashWithFilter() { + webClient.get().uri(BASEURL + "/greeting/") + .exchange() + .expectStatus().isOk() + .expectBody().consumeWith(result -> { + String responseBody = new String(result.getResponseBody()); + assertTrue(responseBody.contains("Hello reactive")); + }); + } +} diff --git a/spring-boot-modules/spring-boot-3/README.md b/spring-boot-modules/spring-boot-3/README.md index be95ce283098..e99eb7912715 100644 --- a/spring-boot-modules/spring-boot-3/README.md +++ b/spring-boot-modules/spring-boot-3/README.md @@ -6,3 +6,4 @@ - [Migrate Application From Spring Boot 2 to Spring Boot 3](https://www.baeldung.com/spring-boot-3-migration) - [Using Java Records with JPA](https://www.baeldung.com/spring-jpa-java-records) - [HTTP Interface in Spring 6](https://www.baeldung.com/spring-6-http-interface) +- [Working with Virtual Threads in Spring 6](https://www.baeldung.com/spring-6-virtual-threads) diff --git a/spring-boot-modules/spring-boot-3/pom.xml b/spring-boot-modules/spring-boot-3/pom.xml index 03740e805fe1..8fe995ca9197 100644 --- a/spring-boot-modules/spring-boot-3/pom.xml +++ b/spring-boot-modules/spring-boot-3/pom.xml @@ -116,6 +116,7 @@ org.springframework.boot spring-boot-maven-plugin + com.baeldung.virtualthreads.VirtualThreadsApp org.projectlombok @@ -131,15 +132,23 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-compiler-plugin + + --enable-preview + + + 19 1.5.2.Final 2.0.0 3.0.0-M7 com.baeldung.sample.TodoApplication - 5.14.0 + 5.14.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/virtualthreads/VirtualThreadsApp.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/virtualthreads/VirtualThreadsApp.java new file mode 100644 index 000000000000..159fa1c2438c --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/virtualthreads/VirtualThreadsApp.java @@ -0,0 +1,13 @@ +package com.baeldung.virtualthreads; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class VirtualThreadsApp { + + public static void main(String[] args) { + SpringApplication.run(VirtualThreadsApp.class, args); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/virtualthreads/config/ThreadConfig.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/virtualthreads/config/ThreadConfig.java new file mode 100644 index 000000000000..7231ec0b9417 --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/virtualthreads/config/ThreadConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.virtualthreads.config; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.web.embedded.tomcat.TomcatProtocolHandlerCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.AsyncTaskExecutor; +import org.springframework.core.task.support.TaskExecutorAdapter; +import org.springframework.scheduling.annotation.EnableAsync; + +import java.util.concurrent.Executors; + +@EnableAsync +@Configuration +@ConditionalOnProperty( + value = "spring.thread-executor", + havingValue = "virtual" +) +public class ThreadConfig { + + @Bean + public AsyncTaskExecutor applicationTaskExecutor() { + return new TaskExecutorAdapter(Executors.newVirtualThreadPerTaskExecutor()); + } + + @Bean + public TomcatProtocolHandlerCustomizer protocolHandlerVirtualThreadExecutorCustomizer() { + return protocolHandler -> { + protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor()); + }; + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/virtualthreads/controller/LoadTestController.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/virtualthreads/controller/LoadTestController.java new file mode 100644 index 000000000000..d99d3824a023 --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/virtualthreads/controller/LoadTestController.java @@ -0,0 +1,23 @@ +package com.baeldung.virtualthreads.controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.io.IOException; + +@RestController +@RequestMapping("/load") +public class LoadTestController { + + private static final Logger LOG = LoggerFactory.getLogger(LoadTestController.class); + + @GetMapping + public void doSomething() throws InterruptedException { + LOG.info("hey, I'm doing something"); + Thread.sleep(1000); + } + +} diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/virtualthreads/controller/ThreadController.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/virtualthreads/controller/ThreadController.java new file mode 100644 index 000000000000..73b28ce9f09b --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/virtualthreads/controller/ThreadController.java @@ -0,0 +1,16 @@ +package com.baeldung.virtualthreads.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/thread") +public class ThreadController { + + @GetMapping("/name") + public String getThreadName() { + return Thread.currentThread().toString(); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3/src/main/resources/application.yml b/spring-boot-modules/spring-boot-3/src/main/resources/application.yml index 9a966a5bbddc..5f9031bc9e67 100644 --- a/spring-boot-modules/spring-boot-3/src/main/resources/application.yml +++ b/spring-boot-modules/spring-boot-3/src/main/resources/application.yml @@ -14,8 +14,10 @@ spring: properties: hibernate: dialect: org.hibernate.dialect.H2Dialect + thread-executor: standard + # Custom Properties cors: allow: origins: ${CORS_ALLOWED_ORIGINS:*} - credentials: ${CORS_ALLOW_CREDENTIALS:false} + credentials: ${CORS_ALLOW_CREDENTIALS:false} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3/src/test/HTTP Load Request .jmx b/spring-boot-modules/spring-boot-3/src/test/HTTP Load Request .jmx new file mode 100644 index 000000000000..bbd02cecbeff --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/test/HTTP Load Request .jmx @@ -0,0 +1,125 @@ + + + + + + false + true + false + + + + + + + + stoptest + + false + -1 + + 1000 + 10 + true + 100 + + true + + + + + + + localhost + 8080 + + + /load + GET + true + false + true + false + + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + true + false + false + false + true + 0 + true + true + true + true + true + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + true + false + false + false + true + 0 + true + true + true + true + true + true + + + + + + + + diff --git a/spring-boot-modules/spring-boot-ci-cd/pom.xml b/spring-boot-modules/spring-boot-ci-cd/pom.xml index 39b90a0777e8..8c12c9823648 100644 --- a/spring-boot-modules/spring-boot-ci-cd/pom.xml +++ b/spring-boot-modules/spring-boot-ci-cd/pom.xml @@ -70,7 +70,8 @@ spring-boot-ci-cd java $JAVA_OPTS -jar -Dserver.port=$PORT - target/${project.build.finalName}.jar + target/${project.build.finalName}.jar + diff --git a/spring-boot-modules/spring-boot-cli/README.md b/spring-boot-modules/spring-boot-cli/README.md index 79e259c855ca..4ed50d3f561f 100644 --- a/spring-boot-modules/spring-boot-cli/README.md +++ b/spring-boot-modules/spring-boot-cli/README.md @@ -4,3 +4,4 @@ This module contains articles about Spring Boot CLI ### Relevant Articles: - [Introduction to Spring Boot CLI](https://www.baeldung.com/spring-boot-cli) +- [Encode Passwords With Spring Boot CLI](https://www.baeldung.com/spring-boot-cli-encode-passwords) diff --git a/spring-core-5/pom.xml b/spring-boot-modules/spring-boot-cli/pom.xml similarity index 51% rename from spring-core-5/pom.xml rename to spring-boot-modules/spring-boot-cli/pom.xml index 1c2e80be4406..76b14b2103f2 100644 --- a/spring-core-5/pom.xml +++ b/spring-boot-modules/spring-boot-cli/pom.xml @@ -3,43 +3,36 @@ 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-core-5 - spring-core-5 + spring-boot-cli + spring-boot-cli + jar + - com.baeldung - parent-spring-5 - 0.0.1-SNAPSHOT - ../parent-spring-5 + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT org.springframework.boot - spring-boot-starter - ${spring-boot-starter.version} + spring-boot-starter-web org.springframework.boot - spring-boot-starter-web - ${spring-boot-starter.version} + spring-boot-starter-security org.springframework.boot spring-boot-starter-test - ${spring-boot-starter.version} test - org.projectlombok - lombok - ${lombok.version} + org.springframework.security + spring-security-test + test - - 5.3.3 - 2.4.2 - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-cli/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-cli/src/main/java/com/baeldung/Application.java new file mode 100644 index 000000000000..c0490d50c636 --- /dev/null +++ b/spring-boot-modules/spring-boot-cli/src/main/java/com/baeldung/Application.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-cli/src/main/java/com/baeldung/controller/LoginController.java b/spring-boot-modules/spring-boot-cli/src/main/java/com/baeldung/controller/LoginController.java new file mode 100644 index 000000000000..b678f63623ce --- /dev/null +++ b/spring-boot-modules/spring-boot-cli/src/main/java/com/baeldung/controller/LoginController.java @@ -0,0 +1,13 @@ +package com.baeldung.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class LoginController { + + @GetMapping("/") + public String hello() { + return "Hello World!"; + } +} diff --git a/spring-boot-modules/spring-boot-cli/src/main/resources/application.properties b/spring-boot-modules/spring-boot-cli/src/main/resources/application.properties new file mode 100644 index 000000000000..4b341094a1f1 --- /dev/null +++ b/spring-boot-modules/spring-boot-cli/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.security.user.name=baeldung +# Encoded password with SpringBoot CLI, the decoded password is baeldungPassword +spring.security.user.password={bcrypt}$2y$10$R8VIwFiQ7aUST17YqMaWJuxjkCYqk3jjPlSxyDLLzqCTOwFuJNq2a \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-cli/src/test/java/com/baeldung/encoding/PasswordEncodingUnitTest.java b/spring-boot-modules/spring-boot-cli/src/test/java/com/baeldung/encoding/PasswordEncodingUnitTest.java new file mode 100644 index 000000000000..8939029f7170 --- /dev/null +++ b/spring-boot-modules/spring-boot-cli/src/test/java/com/baeldung/encoding/PasswordEncodingUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.encoding; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +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.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureMockMvc +public class PasswordEncodingUnitTest { + private final static String userName = "baeldung"; + private final static String passwordDecoded = "baeldungPassword"; + + private MockMvc mvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + @Before + public void setup() { + mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) + .apply(springSecurity()) + .build(); + } + + @Test + public void givenRequestWithWrongPassword_shouldFailWith401() throws Exception { + mvc.perform(get("/").with(httpBasic(userName, "wrongPassword"))) + .andExpect(status().isUnauthorized()); + + } + + @Test + public void givenRequestWithCorrectDecodedPassword_houldSucceedWith200() throws Exception { + mvc.perform(get("/").with(httpBasic(userName, passwordDecoded))) + .andExpect(status().isOk()); + + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data-3/README.md b/spring-boot-modules/spring-boot-data-3/README.md index 39598948530d..7130d251181c 100644 --- a/spring-boot-modules/spring-boot-data-3/README.md +++ b/spring-boot-modules/spring-boot-data-3/README.md @@ -1,2 +1,4 @@ ### Relevant Articles: - [Spring Data JPA – Run an App Without a Database](https://www.baeldung.com/spring-data-jpa-run-app-without-db) +- [Integrate AWS Secrets Manager in Spring Boot](https://www.baeldung.com/spring-boot-integrate-aws-secrets-manager) +- [Fix Spring Data JPA Exception: No Property Found for Type](https://www.baeldung.com/spring-data-jpa-exception-no-property-found-for-type) diff --git a/spring-boot-modules/spring-boot-data-3/pom.xml b/spring-boot-modules/spring-boot-data-3/pom.xml index cf53c256977e..4903d2ea26f2 100644 --- a/spring-boot-modules/spring-boot-data-3/pom.xml +++ b/spring-boot-modules/spring-boot-data-3/pom.xml @@ -25,15 +25,29 @@ spring-boot-starter-data-jpa - com.mysql - mysql-connector-j + com.amazonaws.secretsmanager + aws-secretsmanager-jdbc + ${aws.secrets.manager.jdbc} + + + mysql + mysql-connector-java runtime + + com.h2database + h2 + org.springframework.boot spring-boot-starter-test test + + io.awspring.cloud + spring-cloud-starter-aws-secrets-manager-config + ${aws.secrets.manager.config} + @@ -45,4 +59,9 @@ + + 2.4.4 + 1.0.11 + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/nopropertyfound/NoPropertyFoundApplication.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/nopropertyfound/NoPropertyFoundApplication.java new file mode 100644 index 000000000000..276df9535b95 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/nopropertyfound/NoPropertyFoundApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.nopropertyfound; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class NoPropertyFoundApplication { + + public static void main(String[] args) { + SpringApplication.run(NoPropertyFoundApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/nopropertyfound/config/DbConfig.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/nopropertyfound/config/DbConfig.java new file mode 100644 index 000000000000..9a589e55a379 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/nopropertyfound/config/DbConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.nopropertyfound.config; + +import javax.sql.DataSource; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class DbConfig { + + @Bean + @ConfigurationProperties(prefix = "h2.datasource") + public DataSource dataSource() { + return DataSourceBuilder.create() + .build(); + } + +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/nopropertyfound/model/Person.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/nopropertyfound/model/Person.java new file mode 100644 index 000000000000..3392d3ec67ca --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/nopropertyfound/model/Person.java @@ -0,0 +1,41 @@ +package com.baeldung.nopropertyfound.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + private String firstName; + private String lastName; + + public int getId() { + return id; + } + + public void setId(int 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/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/nopropertyfound/repository/PersonRepository.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/nopropertyfound/repository/PersonRepository.java new file mode 100644 index 000000000000..900c391c93de --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/nopropertyfound/repository/PersonRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.nopropertyfound.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.nopropertyfound.model.Person; + +@Repository +public interface PersonRepository extends JpaRepository { + + // findByFirsttName will cause Spring Data to throw PropertyReferenceException + // Person findByFirsttName(String firstName); + Person findByFirstName(String firstName); + +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/startdbwithawssecretsmanager/StartWithAWSSecretsManagerApplication.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/startdbwithawssecretsmanager/StartWithAWSSecretsManagerApplication.java new file mode 100644 index 000000000000..0bcbef772902 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/startdbwithawssecretsmanager/StartWithAWSSecretsManagerApplication.java @@ -0,0 +1,29 @@ +package com.baeldung.startdbwithawssecretsmanager; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Profile; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +@Profile("aws") +public class StartWithAWSSecretsManagerApplication { + @Value("${api-key1}") + private String apiKeyValue1; + + @Value("${api-key2}") + private String apiKeyValue2; + + @PostConstruct + private void postConstruct() { + System.out.println(apiKeyValue1); + System.out.println(apiKeyValue2); + } + + public static void main(String[] args) { + SpringApplication.run(StartWithAWSSecretsManagerApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/startdbwithawssecretsmanager/controller/UserController.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/startdbwithawssecretsmanager/controller/UserController.java new file mode 100644 index 000000000000..08745db3f005 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/startdbwithawssecretsmanager/controller/UserController.java @@ -0,0 +1,38 @@ +package com.baeldung.startdbwithawssecretsmanager.controller; + +import com.baeldung.startdbwithawssecretsmanager.model.UserEntity; +import com.baeldung.startdbwithawssecretsmanager.repository.UserRepository; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +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.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("users") +public class UserController { + + private final UserRepository userRepository; + + public UserController(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @GetMapping(value = "/{id}", produces = "application/json") + public @ResponseBody UserEntity getUser(@PathVariable Long id) { + return userRepository.findById(id).get(); + } + + @PostMapping + public UserEntity createUser(@RequestBody UserEntity userEntity) { + return userRepository.save(userEntity); + } + + @DeleteMapping(value = "/{id}") + public void removeUser(@PathVariable Long id) { + userRepository.deleteById(id); + } +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/startdbwithawssecretsmanager/model/UserEntity.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/startdbwithawssecretsmanager/model/UserEntity.java new file mode 100644 index 000000000000..285e7094dd58 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/startdbwithawssecretsmanager/model/UserEntity.java @@ -0,0 +1,40 @@ +package com.baeldung.startdbwithawssecretsmanager.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class UserEntity { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String name; + + public UserEntity() { + } + + public UserEntity(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/startdbwithawssecretsmanager/repository/UserRepository.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/startdbwithawssecretsmanager/repository/UserRepository.java new file mode 100644 index 000000000000..e2abfe88e6a3 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/startdbwithawssecretsmanager/repository/UserRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.startdbwithawssecretsmanager.repository; + +import com.baeldung.startdbwithawssecretsmanager.model.UserEntity; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository + extends CrudRepository { +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/resources/application-aws.properties b/spring-boot-modules/spring-boot-data-3/src/main/resources/application-aws.properties new file mode 100644 index 000000000000..07c4b0a4d68a --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/resources/application-aws.properties @@ -0,0 +1,9 @@ +spring.datasource.driver-class-name=com.amazonaws.secretsmanager.sql.AWSSecretsManagerMySQLDriver +spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect +spring.datasource.url=jdbc-secretsmanager:mysql://database-1.cwhqvgjbpgfw.eu-central-1.rds.amazonaws.com:3306/test +spring.datasource.username=rds/credentials + +#Overwriting application.properties configuration back to default. +spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=true + +spring.config.import=aws-secretsmanager:test/secret/ diff --git a/spring-boot-modules/spring-boot-data-3/src/main/resources/application.properties b/spring-boot-modules/spring-boot-data-3/src/main/resources/application.properties index cbe044134feb..71f39e0ee333 100644 --- a/spring-boot-modules/spring-boot-data-3/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-data-3/src/main/resources/application.properties @@ -4,4 +4,9 @@ spring.datasource.username=root spring.datasource.password=root spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.ddl-auto=none -spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false \ No newline at end of file +spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false + +h2.datasource.url=jdbc:h2:mem:testdb +h2.datasource.driver-class-name=org.h2.Driver +h2.datasource.username=sa +h2.datasource.password= diff --git a/spring-boot-modules/spring-boot-data-3/src/main/resources/data.sql b/spring-boot-modules/spring-boot-data-3/src/main/resources/data.sql new file mode 100644 index 000000000000..5623bbfadf46 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/resources/data.sql @@ -0,0 +1,3 @@ +INSERT INTO person (first_name, last_name) VALUES('Azhrioun', 'Abderrahim'); +INSERT INTO person (first_name, last_name) VALUES('Brian', 'Wheeler'); +INSERT INTO person (first_name, last_name) VALUES('Dave', 'Anderson'); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data-3/src/main/resources/schema.sql b/spring-boot-modules/spring-boot-data-3/src/main/resources/schema.sql new file mode 100644 index 000000000000..738ef25298f9 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/resources/schema.sql @@ -0,0 +1,6 @@ +DROP TABLE IF EXISTS person; +CREATE TABLE person( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(200), + last_name VARCHAR(200) +) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/nopropertyfound/PersonRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/nopropertyfound/PersonRepositoryIntegrationTest.java new file mode 100644 index 000000000000..2a9d1a46f235 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/nopropertyfound/PersonRepositoryIntegrationTest.java @@ -0,0 +1,28 @@ +package com.baeldung.nopropertyfound; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; + +import com.baeldung.nopropertyfound.model.Person; +import com.baeldung.nopropertyfound.repository.PersonRepository; + +@DataJpaTest +class PersonRepositoryIntegrationTest { + + @Autowired + private PersonRepository personRepository; + + @Test + void givenQueryMethod_whenUsingValidProperty_thenCorrect() { + + Person person = personRepository.findByFirstName("Azhrioun"); + + assertNotNull(person); + assertEquals("Abderrahim", person.getLastName()); + } + +} diff --git a/spring-boot-modules/spring-boot-environment/pom.xml b/spring-boot-modules/spring-boot-environment/pom.xml index 013156fa7f07..4bdb35358cc3 100644 --- a/spring-boot-modules/spring-boot-environment/pom.xml +++ b/spring-boot-modules/spring-boot-environment/pom.xml @@ -149,7 +149,7 @@ - + 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"