diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java index 988a89e7af..92cb452dc8 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java @@ -7,7 +7,6 @@ import static org.mockserver.model.HttpResponse.response; import java.io.IOException; import java.net.ServerSocket; -import java.net.URISyntaxException; import org.apache.http.HttpStatus; import org.junit.jupiter.api.AfterAll; @@ -18,22 +17,19 @@ import org.mockserver.integration.ClientAndServer; public class GetRequestMockServer { public static ClientAndServer mockServer; - public static String serviceOneUrl; - public static String serviceTwoUrl; public static int serverPort; public static final String SERVER_ADDRESS = "127.0.0.1"; - public static final String PATH_ONE = "/test1"; - public static final String PATH_TWO = "/test2"; - public static final String METHOD = "GET"; + + public static final String SECURITY_PATH = "/spring-security-rest-basic-auth/api/foos/1"; + + public static final String UPLOAD_PATH = "/spring-mvc-java/stub/multipart"; @BeforeAll static void startServer() throws IOException { serverPort = getFreePort(); - System.out.println("Free port "+serverPort); - serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE; - serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO; + System.out.println("Free port " + serverPort); mockServer = startClientAndServer(serverPort); mockGetRequest(); } @@ -44,33 +40,36 @@ public class GetRequestMockServer { } private static void mockGetRequest() { - new MockServerClient(SERVER_ADDRESS, serverPort) - .when( - request() - .withPath(PATH_ONE) - .withMethod(METHOD), - exactly(5) - ) - .respond( - response() - .withStatusCode(HttpStatus.SC_OK) - .withBody("{\"status\":\"ok\"}") - ); - new MockServerClient(SERVER_ADDRESS, serverPort) - .when( - request() - .withPath(PATH_TWO) - .withMethod(METHOD), - exactly(1) - ) - .respond( - response() - .withStatusCode(HttpStatus.SC_OK) - .withBody("{\"status\":\"ok\"}") - ); + + MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort); + + client.when( + request() + .withPath(SECURITY_PATH) + .withMethod("GET"), + exactly(1) + ) + .respond( + response() + .withStatusCode(HttpStatus.SC_OK) + .withBody("{\"status\":\"ok\"}") + ); + + client.when( + request() + .withPath(UPLOAD_PATH) + .withMethod("POST"), + exactly(4) + ) + .respond( + response() + .withStatusCode(HttpStatus.SC_OK) + .withBody("{\"status\":\"ok\"}") + .withHeader("Content-Type", "multipart/form-data") + ); } - private static int getFreePort () throws IOException { + private static int getFreePort() throws IOException { try (ServerSocket serverSocket = new ServerSocket(0)) { return serverSocket.getLocalPort(); } diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java index d19e0e1d86..d3e80c4429 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java @@ -19,7 +19,7 @@ class HttpClientCancelRequestLiveTest { void whenRequestIsCanceled_thenCorrect() throws IOException { HttpGet request = new HttpGet(SAMPLE_URL); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - httpClient.execute(request, response -> { + httpClient.execute(request, response -> { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); @@ -28,6 +28,12 @@ class HttpClientCancelRequestLiveTest { System.out.println("Response content length: " + entity.getContentLength()); } System.out.println("----------------------------------------"); + + if (entity != null) { + // Closes this stream and releases any system resources + entity.close(); + } + // Do not feel like reading the response body // Call abort on the request object request.abort(); diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java index 720049378b..69eedc8e48 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java @@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.apache.hc.core5.http.ParseException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -13,7 +14,6 @@ import org.apache.hc.client5.http.entity.mime.HttpMultipartMode; import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.client5.http.entity.mime.StringBody; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.core5.http.ContentType; @@ -28,9 +28,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; -import com.baeldung.httpclient.handler.CustomHttpClientResponseHandler; - -class HttpClientMultipartLiveTest { +class HttpClientMultipartLiveTest extends GetRequestMockServer { // No longer available // private static final String SERVER = "http://echo.200please.com"; @@ -45,13 +43,15 @@ class HttpClientMultipartLiveTest { @BeforeEach public void before() { post = new HttpPost(SERVER); + String URL = "http://localhost:" + serverPort + "/spring-mvc-java/stub/multipart"; + post = new HttpPost(URL); } @Test void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + TEXTFILENAME); + .getContextClassLoader() + .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); @@ -66,27 +66,28 @@ class HttpClientMultipartLiveTest { final HttpEntity entity = builder.build(); post.setEntity(entity); - try(CloseableHttpClient client = HttpClientBuilder.create() - .build(); + try (CloseableHttpClient client = HttpClientBuilder.create() + .build()) { - CloseableHttpResponse response = (CloseableHttpResponse) client - .execute(post, new CustomHttpClientResponseHandler())){ - final int statusCode = response.getCode(); - final String responseString = getContent(response.getEntity()); - final String contentTypeInHeader = getContentTypeHeader(); + client.execute(post, response -> { + final int statusCode = response.getCode(); + final String responseString = getContent(response.getEntity()); + final String contentTypeInHeader = getContentTypeHeader(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); - System.out.println(responseString); - System.out.println("POST Content Type: " + contentTypeInHeader); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + assertTrue(contentTypeInHeader.contains("multipart/form-data")); + System.out.println(responseString); + System.out.println("POST Content Type: " + contentTypeInHeader); + return response; + }); } } @Test void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + TEXTFILENAME); + .getContextClassLoader() + .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final String message = "This is a multipart post"; final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); @@ -96,30 +97,31 @@ class HttpClientMultipartLiveTest { final HttpEntity entity = builder.build(); post.setEntity(entity); - try(CloseableHttpClient client = HttpClientBuilder.create() - .build(); + try (CloseableHttpClient client = HttpClientBuilder.create() + .build()) { - CloseableHttpResponse response = (CloseableHttpResponse) client - .execute(post, new CustomHttpClientResponseHandler())){ + client.execute(post, response -> { - final int statusCode = response.getCode(); - final String responseString = getContent(response.getEntity()); - final String contentTypeInHeader = getContentTypeHeader(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); - System.out.println(responseString); - System.out.println("POST Content Type: " + contentTypeInHeader); + final int statusCode = response.getCode(); + final String responseString = getContent(response.getEntity()); + final String contentTypeInHeader = getContentTypeHeader(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + assertTrue(contentTypeInHeader.contains("multipart/form-data")); + System.out.println(responseString); + System.out.println("POST Content Type: " + contentTypeInHeader); + return response; + }); } } @Test void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + ZIPFILENAME); + .getContextClassLoader() + .getResource("uploads/" + ZIPFILENAME); final URL url2 = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + IMAGEFILENAME); + .getContextClassLoader() + .getResource("uploads/" + IMAGEFILENAME); final InputStream inputStream = new FileInputStream(url.getPath()); final File file = new File(url2.getPath()); final String message = "This is a multipart post"; @@ -131,25 +133,25 @@ class HttpClientMultipartLiveTest { final HttpEntity entity = builder.build(); post.setEntity(entity); - try(CloseableHttpClient client = HttpClientBuilder.create() - .build(); + try (CloseableHttpClient client = HttpClientBuilder.create() + .build()) { - CloseableHttpResponse response = (CloseableHttpResponse) client - .execute(post, new CustomHttpClientResponseHandler())){ - - final int statusCode = response.getCode(); - final String responseString = getContent(response.getEntity()); - final String contentTypeInHeader = getContentTypeHeader(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); - System.out.println(responseString); - System.out.println("POST Content Type: " + contentTypeInHeader); - inputStream.close(); + client.execute(post, response -> { + final int statusCode = response.getCode(); + final String responseString = getContent(response.getEntity()); + final String contentTypeInHeader = getContentTypeHeader(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + assertTrue(contentTypeInHeader.contains("multipart/form-data;")); + System.out.println(responseString); + System.out.println("POST Content Type: " + contentTypeInHeader); + inputStream.close(); + return response; + }); } } @Test - void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { + void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException, ParseException { final String message = "This is a multipart post"; final byte[] bytes = "binary code".getBytes(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); @@ -159,21 +161,20 @@ class HttpClientMultipartLiveTest { final HttpEntity entity = builder.build(); post.setEntity(entity); - try(CloseableHttpClient client = HttpClientBuilder.create() - .build(); + try (CloseableHttpClient httpClient = HttpClientBuilder.create() + .build()) { - CloseableHttpResponse response = (CloseableHttpResponse) client - .execute(post, new CustomHttpClientResponseHandler())){ - - final int statusCode = response.getCode(); - final String responseString = getContent(response.getEntity()); - final String contentTypeInHeader = getContentTypeHeader(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); - System.out.println(responseString); - System.out.println("POST Content Type: " + contentTypeInHeader); + httpClient.execute(post, response -> { + final int statusCode = response.getCode(); + final String responseString = getContent(response.getEntity()); + final String contentTypeInHeader = getContentTypeHeader(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + assertTrue(contentTypeInHeader.contains("multipart/form-data;")); + System.out.println(responseString); + System.out.println("POST Content Type: " + contentTypeInHeader); + return response; + }); } - } // UTIL 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 4173909f7d..b8bc536918 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 @@ -43,7 +43,7 @@ public class HttpClientLiveTest { @Test(expected = ConnectTimeoutException.class) public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException { - final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(20).build(); + final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5).setConnectTimeout(5).setSocketTimeout(2).build(); final HttpGet request = new HttpGet(SAMPLE_URL); request.setConfig(requestConfig); response = instance.execute(request); diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientSandboxLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientSandboxLiveTest.java index c667ae36f6..f72aa0c878 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientSandboxLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientSandboxLiveTest.java @@ -1,5 +1,6 @@ package com.baeldung.httpclient.base; +import com.baeldung.httpclient.GetRequestMockServer; import com.baeldung.httpclient.ResponseUtil; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; @@ -9,14 +10,14 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; /* * NOTE : Need module spring-security-rest-basic-auth to be running */ -public class HttpClientSandboxLiveTest { +public class HttpClientSandboxLiveTest extends GetRequestMockServer { @Test public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { @@ -26,7 +27,7 @@ public class HttpClientSandboxLiveTest { final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build(); - final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1"); + final HttpGet httpGet = new HttpGet("http://localhost:" + serverPort + "/spring-security-rest-basic-auth/api/foos/1"); final CloseableHttpResponse response = client.execute(httpGet); System.out.println(response.getStatusLine()); diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java deleted file mode 100644 index 0559854b35..0000000000 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.httpclient.handler; - -import org.apache.hc.core5.http.ClassicHttpResponse; -import org.apache.hc.core5.http.io.HttpClientResponseHandler; - -public class CustomHttpClientResponseHandler implements HttpClientResponseHandler { - @Override - public ClassicHttpResponse handleResponse(ClassicHttpResponse response) { - return response; - } -} \ No newline at end of file diff --git a/apache-httpclient4/pom.xml b/apache-httpclient4/pom.xml index e0bf9dd5f6..21c675db35 100644 --- a/apache-httpclient4/pom.xml +++ b/apache-httpclient4/pom.xml @@ -199,33 +199,7 @@ true - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - + @@ -233,26 +207,6 @@ live - - org.codehaus.cargo - cargo-maven2-plugin - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - org.apache.maven.plugins maven-surefire-plugin @@ -269,9 +223,6 @@ **/*LiveTest.java - - cargo - @@ -291,7 +242,6 @@ 4.5.14 5.11.2 - 1.6.1 3.3.2 diff --git a/apache-httpclient4/src/test/java/com/baeldung/GetRequestMockServer.java b/apache-httpclient4/src/test/java/com/baeldung/GetRequestMockServer.java new file mode 100644 index 0000000000..52f1baa30d --- /dev/null +++ b/apache-httpclient4/src/test/java/com/baeldung/GetRequestMockServer.java @@ -0,0 +1,56 @@ +package com.baeldung; + +import static org.mockserver.integration.ClientAndServer.startClientAndServer; +import static org.mockserver.model.HttpRequest.request; +import static org.mockserver.model.HttpResponse.response; + +import java.io.IOException; +import java.net.ServerSocket; + +import org.apache.http.HttpStatus; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.mockserver.client.MockServerClient; +import org.mockserver.integration.ClientAndServer; + +public class GetRequestMockServer { + + public static ClientAndServer mockServer; + public static int serverPort; + public static String simplePathUrl; + public static final String SERVER_ADDRESS = "127.0.0.1"; + public static final String SIMPLE_PATH = "/httpclient-simple/api/bars/1"; + + @BeforeAll + static void startServer() throws IOException { + serverPort = getFreePort(); + System.out.println("Free port " + serverPort); + mockServer = startClientAndServer(serverPort); + + simplePathUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + SIMPLE_PATH; + + mockGetRequest(); + } + + @AfterAll + static void stopServer() { + mockServer.stop(); + } + + private static void mockGetRequest() { + + MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort); + + client.when(request().withPath(SIMPLE_PATH) + .withMethod("GET")) + .respond(response().withStatusCode(HttpStatus.SC_OK) + .withBody("{\"status\":\"ok\"}")); + } + + private static int getFreePort() throws IOException { + try (ServerSocket serverSocket = new ServerSocket(0)) { + return serverSocket.getLocalPort(); + } + } + +} \ No newline at end of file diff --git a/apache-httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java index 2785bc5d08..9d1052b7b3 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java @@ -10,7 +10,7 @@ import java.io.IOException; import java.security.GeneralSecurityException; import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLHandshakeException; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; @@ -31,10 +31,10 @@ import org.springframework.http.ResponseEntity; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; +import com.baeldung.GetRequestMockServer; -class ClientLiveTest { +class ClientLiveTest extends GetRequestMockServer { - final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1"; @Test void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException { @@ -54,13 +54,13 @@ class ClientLiveTest { .build(); final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); - final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); + final ResponseEntity response = new RestTemplate(requestFactory).exchange(simplePathUrl, HttpMethod.GET, null, String.class); assertThat(response.getStatusCode().value(), equalTo(200)); } @Test void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException { - final HttpGet getMethod = new HttpGet(urlOverHttps); + final HttpGet getMethod = new HttpGet(simplePathUrl); try (final CloseableHttpClient httpClient = HttpClients.custom() .setSSLHostnameVerifier(new NoopHostnameVerifier()) @@ -80,20 +80,22 @@ class ClientLiveTest { final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); - final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); + final ResponseEntity response = new RestTemplate(requestFactory).exchange(simplePathUrl, HttpMethod.GET, null, String.class); assertThat(response.getStatusCode().value(), equalTo(200)); } @Test void whenHttpsUrlIsConsumed_thenException() { - String urlOverHttps = "https://localhost:8082/httpclient-simple"; + String urlOverHttps = "https://localhost:"+serverPort+"/httpclient-simple/api/bars/1"; HttpGet getMethod = new HttpGet(urlOverHttps); - assertThrows(SSLPeerUnverifiedException.class, () -> { + assertThrows(SSLHandshakeException.class, () -> { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpResponse response = httpClient.execute(getMethod); assertThat(response.getStatusLine() .getStatusCode(), equalTo(200)); }); } + + } \ No newline at end of file diff --git a/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java b/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java index c336e6a068..3c0f5b7c63 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java @@ -1,6 +1,5 @@ package com.baeldung.client; -import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -89,4 +88,5 @@ public class RestClientV4LiveManualTest { HttpResponse response = httpClient.execute(getMethod); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } + } diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java deleted file mode 100644 index ae432e68f0..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.baeldung.httpclient; - -import static org.mockserver.integration.ClientAndServer.startClientAndServer; -import static org.mockserver.matchers.Times.exactly; -import static org.mockserver.model.HttpRequest.request; -import static org.mockserver.model.HttpResponse.response; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.URISyntaxException; - -import org.apache.http.HttpStatus; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.mockserver.client.MockServerClient; -import org.mockserver.integration.ClientAndServer; - -public class GetRequestMockServer { - - public static ClientAndServer mockServer; - public static String serviceOneUrl; - public static String serviceTwoUrl; - - public static int serverPort; - - public static final String SERVER_ADDRESS = "127.0.0.1"; - public static final String PATH_ONE = "/test1"; - public static final String PATH_TWO = "/test2"; - public static final String METHOD = "GET"; - - @BeforeAll - static void startServer() throws IOException, URISyntaxException { - serverPort = getFreePort(); - serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE; - serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO; - mockServer = startClientAndServer(serverPort); - mockGetRequest(); - } - - @AfterAll - static void stopServer() { - mockServer.stop(); - } - - private static void mockGetRequest() { - new MockServerClient(SERVER_ADDRESS, serverPort) - .when( - request() - .withPath(PATH_ONE) - .withMethod(METHOD), - exactly(5) - ) - .respond( - response() - .withStatusCode(HttpStatus.SC_OK) - .withBody("{\"status\":\"ok\"}") - ); - new MockServerClient(SERVER_ADDRESS, serverPort) - .when( - request() - .withPath(PATH_TWO) - .withMethod(METHOD), - exactly(1) - ) - .respond( - response() - .withStatusCode(HttpStatus.SC_OK) - .withBody("{\"status\":\"ok\"}") - ); - } - - private static int getFreePort () throws IOException { - try (ServerSocket serverSocket = new ServerSocket(0)) { - return serverSocket.getLocalPort(); - } - } -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java index e097f9f511..80b16d7f07 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java @@ -31,6 +31,7 @@ import org.apache.http.protocol.HttpContext; import org.apache.http.ssl.SSLContexts; import org.junit.jupiter.api.Test; +import com.baeldung.GetRequestMockServer; class HttpAsyncClientV4LiveTest extends GetRequestMockServer { diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java index 226a7b8cf7..446c47c200 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java @@ -44,7 +44,9 @@ public class HttpClientCancelRequestV4LiveTest { System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); + entity.getContent().close(); } + System.out.println("----------------------------------------"); // Do not feel like reading the response body diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java index 4d4dd7be15..ed22913ddd 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java @@ -21,7 +21,9 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -class HttpClientTimeoutV4LiveTest { +import com.baeldung.GetRequestMockServer; + +class HttpClientTimeoutV4LiveTest extends GetRequestMockServer { private CloseableHttpResponse response; @@ -97,7 +99,7 @@ class HttpClientTimeoutV4LiveTest { int timeout = 20; // seconds RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000) .setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); - HttpGet getMethod = new HttpGet("http://localhost:8082/httpclient-simple/api/bars/1"); + HttpGet getMethod = new HttpGet(simplePathUrl); getMethod.setConfig(requestConfig); int hardTimeout = 5; // seconds diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java index 0d394b4ce7..9a7a734b65 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java @@ -13,13 +13,15 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.junit.jupiter.api.Test; +import com.baeldung.GetRequestMockServer; + class ApacheHttpClientUnitTest extends GetRequestMockServer { @Test void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { - HttpGet httpGet = new HttpGet(serviceOneUrl); + HttpGet httpGet = new HttpGet(simplePathUrl); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/GetRequestMockServer.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/GetRequestMockServer.java deleted file mode 100644 index 3473117cef..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/GetRequestMockServer.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.baeldung.httpclient.httpclient; - -import org.apache.http.HttpStatus; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.mockserver.client.MockServerClient; -import org.mockserver.integration.ClientAndServer; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.URISyntaxException; - -import static org.mockserver.integration.ClientAndServer.startClientAndServer; -import static org.mockserver.matchers.Times.exactly; -import static org.mockserver.model.HttpRequest.request; -import static org.mockserver.model.HttpResponse.response; - -public class GetRequestMockServer { - - public static ClientAndServer mockServer; - public static String serviceOneUrl; - public static String serviceTwoUrl; - - private static int serverPort; - - public static final String SERVER_ADDRESS = "127.0.0.1"; - public static final String PATH_ONE = "/test1"; - public static final String PATH_TWO = "/test2"; - public static final String METHOD = "GET"; - - @BeforeAll - static void startServer() throws IOException, URISyntaxException { - serverPort = getFreePort(); - serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE; - serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO; - mockServer = startClientAndServer(serverPort); - mockGetRequest(); - } - - @AfterAll - static void stopServer() { - mockServer.stop(); - } - - private static void mockGetRequest() { - new MockServerClient(SERVER_ADDRESS, serverPort) - .when( - request() - .withPath(PATH_ONE) - .withMethod(METHOD), - exactly(5) - ) - .respond( - response() - .withStatusCode(HttpStatus.SC_OK) - .withBody("{\"status\":\"ok\"}") - ); - new MockServerClient(SERVER_ADDRESS, serverPort) - .when( - request() - .withPath(PATH_TWO) - .withMethod(METHOD), - exactly(1) - ) - .respond( - response() - .withStatusCode(HttpStatus.SC_OK) - .withBody("{\"status\":\"ok\"}") - ); - } - - private static int getFreePort () throws IOException { - try (ServerSocket serverSocket = new ServerSocket(0)) { - return serverSocket.getLocalPort(); - } - } - -} diff --git a/core-java-modules/core-java-20/README.md b/core-java-modules/core-java-20/README.md index aba4e9e240..f859bf9e23 100644 --- a/core-java-modules/core-java-20/README.md +++ b/core-java-modules/core-java-20/README.md @@ -1,2 +1,3 @@ ## Relevant Articles - [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values) +- [How to Read Zip Files Entries With Java](https://www.baeldung.com/java-read-zip-files) diff --git a/core-java-modules/core-java-concurrency-2/README.md b/core-java-modules/core-java-concurrency-2/README.md index c52f17a07b..3badd36d5e 100644 --- a/core-java-modules/core-java-concurrency-2/README.md +++ b/core-java-modules/core-java-concurrency-2/README.md @@ -6,3 +6,4 @@ - [Using a Mutex Object in Java](https://www.baeldung.com/java-mutex) - [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded) - [How to Check if All Runnables Are Done](https://www.baeldung.com/java-runnables-check-status) +- [Parallelize for Loop in Java](https://www.baeldung.com/java-for-loop-parallel) 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 619a68cdef..e896ab7469 100644 --- a/core-java-modules/core-java-concurrency-basic-3/README.md +++ b/core-java-modules/core-java-concurrency-basic-3/README.md @@ -8,4 +8,5 @@ This module contains articles about basic Java concurrency. - [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await) - [Is CompletableFuture Non-blocking?](https://www.baeldung.com/java-completablefuture-non-blocking) - [Returning a Value After Finishing Thread’s Job in Java](https://www.baeldung.com/java-return-value-after-thread-finish) +- [CompletableFuture and ThreadPool in Java](https://www.baeldung.com/java-completablefuture-threadpool) - [[<-- Prev]](../core-java-concurrency-basic-2) diff --git a/core-java-modules/core-java-date-operations-3/README.md b/core-java-modules/core-java-date-operations-3/README.md index c87714f38a..97855814e5 100644 --- a/core-java-modules/core-java-date-operations-3/README.md +++ b/core-java-modules/core-java-date-operations-3/README.md @@ -8,4 +8,5 @@ This module contains articles about date operations in Java. - [How to Determine Date of the First Day of the Week Using LocalDate in Java](https://www.baeldung.com/java-first-day-of-the-week) - [Adding One Month to Current Date in Java](https://www.baeldung.com/java-adding-one-month-to-current-date) - [How to Get Last Day of a Month in Java](https://www.baeldung.com/java-last-day-month) +- [Getting Yesterday’s Date in Java](https://www.baeldung.com/java-find-yesterdays-date) - [[<-- Prev]](/core-java-modules/core-java-date-operations-2) 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 551fd65b7d..e86539c750 100644 --- a/core-java-modules/core-java-io-apis-2/README.md +++ b/core-java-modules/core-java-io-apis-2/README.md @@ -4,13 +4,5 @@ This module contains articles about core Java input/output(IO) APIs. ### Relevant Articles: - [Constructing a Relative Path From Two Absolute Paths in Java](https://www.baeldung.com/java-relative-path-absolute) -- [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input) - [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path) -- [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer) -- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader) -- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line) -- [Storing Java Scanner Input in an Array](https://www.baeldung.com/java-store-scanner-input-in-array) -- [How to Take Input as String With Spaces in Java Using Scanner?](https://www.baeldung.com/java-scanner-input-with-spaces) -- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file) -- [What’s the Difference between Scanner next() and nextLine() Methods?](https://www.baeldung.com/java-scanner-next-vs-nextline) -- [Handle NoSuchElementException When Reading a File Through Scanner](https://www.baeldung.com/java-scanner-nosuchelementexception-reading-file) +- [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty) \ No newline at end of file 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 e828b730d2..bf7af998e3 100644 --- a/core-java-modules/core-java-io-apis-2/pom.xml +++ b/core-java-modules/core-java-io-apis-2/pom.xml @@ -92,12 +92,6 @@ 7.1.0 test - - org.testng - testng - 7.5 - compile - core-java-io-apis-2 diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/emptyfile/CheckFileIsEmptyUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/emptyfile/CheckFileIsEmptyUnitTest.java new file mode 100644 index 0000000000..02b4d758b3 --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/emptyfile/CheckFileIsEmptyUnitTest.java @@ -0,0 +1,71 @@ +package com.baeldung.emptyfile; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class CheckFileIsEmptyUnitTest { + @Test + void whenTheFileIsEmpty_thenFileLengthIsZero(@TempDir Path tempDir) throws IOException { + File emptyFile = tempDir.resolve("an-empty-file.txt") + .toFile(); + emptyFile.createNewFile(); + assertTrue(emptyFile.exists()); + assertEquals(0, emptyFile.length()); + } + + @Test + void whenFileDoesNotExist_thenFileLengthIsZero(@TempDir Path tempDir) { + File aNewFile = tempDir.resolve("a-new-file.txt") + .toFile(); + assertFalse(aNewFile.exists()); + assertEquals(0, aNewFile.length()); + } + + boolean isFileEmpty(File file) { + if (!file.exists()) { + throw new IllegalArgumentException("Cannot check the file length. The file is not found: " + file.getAbsolutePath()); + } + return file.length() == 0; + } + + @Test + void whenTheFileDoesNotExist_thenIsFilesEmptyThrowsException(@TempDir Path tempDir) { + File aNewFile = tempDir.resolve("a-new-file.txt") + .toFile(); + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> isFileEmpty(aNewFile)); + assertEquals(ex.getMessage(), "Cannot check the file length. The file is not found: " + aNewFile.getAbsolutePath()); + } + + @Test + void whenTheFileIsEmpty_thenIsFilesEmptyReturnsTrue(@TempDir Path tempDir) throws IOException { + File emptyFile = tempDir.resolve("an-empty-file.txt") + .toFile(); + emptyFile.createNewFile(); + assertTrue(isFileEmpty(emptyFile)); + + } + + @Test + void whenTheFileIsEmpty_thenFilesSizeReturnsTrue(@TempDir Path tempDir) throws IOException { + Path emptyFilePath = tempDir.resolve("an-empty-file.txt"); + Files.createFile(emptyFilePath); + assertEquals(0, Files.size(emptyFilePath)); + } + + @Test + void whenTheFileDoesNotExist_thenFilesSizeThrowsException(@TempDir Path tempDir) { + Path aNewFilePath = tempDir.resolve("a-new-file.txt"); + assertThrows(NoSuchFileException.class, () -> Files.size(aNewFilePath)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-apis-3/README.md b/core-java-modules/core-java-io-apis-3/README.md deleted file mode 100644 index 23f2b41ac7..0000000000 --- a/core-java-modules/core-java-io-apis-3/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Core Java IO APIs - -This module contains articles about core Java input/output(IO) APIs. - -### Relevant Articles: -- [Read Date in Java Using Scanner](https://www.baeldung.com/java-scanner-read-date) diff --git a/core-java-modules/core-java-io-apis-3/pom.xml b/core-java-modules/core-java-io-apis-3/pom.xml deleted file mode 100644 index 8b2431397b..0000000000 --- a/core-java-modules/core-java-io-apis-3/pom.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - 4.0.0 - core-java-io-apis-3 - core-java-io-apis-3 - 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-io-apis/README.md b/core-java-modules/core-java-io-apis/README.md index 9399443ebd..b00b0a6022 100644 --- a/core-java-modules/core-java-io-apis/README.md +++ b/core-java-modules/core-java-io-apis/README.md @@ -10,6 +10,6 @@ This module contains articles about core Java input/output(IO) APIs. - [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](https://www.baeldung.com/java-path) - [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter) - [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader) -- [Java Scanner](https://www.baeldung.com/java-scanner) -- [Scanner nextLine() Method](https://www.baeldung.com/java-scanner-nextline) -- [Java Scanner hasNext() vs. hasNextLine()](https://www.baeldung.com/java-scanner-hasnext-vs-hasnextline) \ No newline at end of file +- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader) +- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line) +- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file) \ 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 f9d404cd5b..8889fd5f50 100644 --- a/core-java-modules/core-java-io-apis/pom.xml +++ b/core-java-modules/core-java-io-apis/pom.xml @@ -31,6 +31,12 @@ ${lombok.version} provided + + org.testng + testng + 7.5 + compile + 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/src/main/java/com/baeldung/multinput/MultiInputs.java similarity index 97% rename from core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/multinput/MultiInputs.java rename to core-java-modules/core-java-io-apis/src/main/java/com/baeldung/multinput/MultiInputs.java index df799b2511..bc14c4275b 100644 --- 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/src/main/java/com/baeldung/multinput/MultiInputs.java @@ -1,36 +1,36 @@ -package com.baeldung.multinput; - -import java.util.InputMismatchException; -import java.util.Scanner; - -public class MultiInputs { - public void UsingSpaceDelimiter(){ - Scanner scanner = new Scanner(System.in); - System.out.print("Enter two numbers: "); - int num1 = scanner.nextInt(); - int num2 = scanner.nextInt(); - System.out.println("You entered " + num1 + " and " + num2); - - } - public void UsingREDelimiter(){ - Scanner scanner = new Scanner(System.in); - scanner.useDelimiter("[\\s,]+"); - System.out.print("Enter two numbers separated by a space or a comma: "); - int num1 = scanner.nextInt(); - int num2 = scanner.nextInt(); - System.out.println("You entered " + num1 + " and " + num2); - - } - public void UsingCustomDelimiter(){ - Scanner scanner = new Scanner(System.in); - scanner.useDelimiter(";"); - System.out.print("Enter two numbers separated by a semicolon: "); - try { int num1 = scanner.nextInt(); - int num2 = scanner.nextInt(); - System.out.println("You entered " + num1 + " and " + num2); } - catch (InputMismatchException e) - { System.out.println("Invalid input. Please enter two integers separated by a semicolon."); } - - } -} - +package com.baeldung.multinput; + +import java.util.InputMismatchException; +import java.util.Scanner; + +public class MultiInputs { + public void UsingSpaceDelimiter(){ + Scanner scanner = new Scanner(System.in); + System.out.print("Enter two numbers: "); + int num1 = scanner.nextInt(); + int num2 = scanner.nextInt(); + System.out.println("You entered " + num1 + " and " + num2); + + } + public void UsingREDelimiter(){ + Scanner scanner = new Scanner(System.in); + scanner.useDelimiter("[\\s,]+"); + System.out.print("Enter two numbers separated by a space or a comma: "); + int num1 = scanner.nextInt(); + int num2 = scanner.nextInt(); + System.out.println("You entered " + num1 + " and " + num2); + + } + public void UsingCustomDelimiter(){ + Scanner scanner = new Scanner(System.in); + scanner.useDelimiter(";"); + System.out.print("Enter two numbers separated by a semicolon: "); + try { int num1 = scanner.nextInt(); + int num2 = scanner.nextInt(); + System.out.println("You entered " + num1 + " and " + num2); } + catch (InputMismatchException e) + { System.out.println("Invalid input. Please enter two integers separated by a semicolon."); } + + } +} + 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/src/test/java/com/baeldung/bufferedreadervsfilereader/BufferedReaderUnitTest.java similarity index 96% rename from core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/BufferedReaderUnitTest.java rename to core-java-modules/core-java-io-apis/src/test/java/com/baeldung/bufferedreadervsfilereader/BufferedReaderUnitTest.java index 62f0d9da22..6892ef33a9 100644 --- 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/src/test/java/com/baeldung/bufferedreadervsfilereader/BufferedReaderUnitTest.java @@ -1,36 +1,36 @@ -package com.baeldung.bufferedreadervsfilereader; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; - -import org.junit.jupiter.api.Test; - -class BufferedReaderUnitTest { - - @Test - void whenReadingAFile_thenReadsLineByLine() { - StringBuilder result = new StringBuilder(); - - final Path filePath = new File("src/test/resources/sampleText1.txt").toPath(); - try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(filePath), StandardCharsets.UTF_8))) { - String line; - - while((line = br.readLine()) != null) { - result.append(line); - result.append('\n'); - } - } catch (IOException e) { - e.printStackTrace(); - } - - assertEquals("first line\nsecond line\nthird line\n", result.toString()); - } - -} +package com.baeldung.bufferedreadervsfilereader; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.junit.jupiter.api.Test; + +class BufferedReaderUnitTest { + + @Test + void whenReadingAFile_thenReadsLineByLine() { + StringBuilder result = new StringBuilder(); + + final Path filePath = new File("src/test/resources/sampleText1.txt").toPath(); + try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(filePath), StandardCharsets.UTF_8))) { + String line; + + while((line = br.readLine()) != null) { + result.append(line); + result.append('\n'); + } + } catch (IOException e) { + e.printStackTrace(); + } + + assertEquals("first line\nsecond line\nthird line\n", result.toString()); + } + +} 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/src/test/java/com/baeldung/bufferedreadervsfilereader/FileReaderUnitTest.java similarity index 95% rename from core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/FileReaderUnitTest.java rename to core-java-modules/core-java-io-apis/src/test/java/com/baeldung/bufferedreadervsfilereader/FileReaderUnitTest.java index da724d32e8..2c09d2a084 100644 --- 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/src/test/java/com/baeldung/bufferedreadervsfilereader/FileReaderUnitTest.java @@ -1,30 +1,30 @@ -package com.baeldung.bufferedreadervsfilereader; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.FileReader; -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -class FileReaderUnitTest { - - @Test - void whenReadingAFile_thenReadsCharByChar() { - StringBuilder result = new StringBuilder(); - - try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) { - int i = fr.read(); - - while(i != -1) { - result.append((char)i); - - i = fr.read(); - } - } catch (IOException e) { - e.printStackTrace(); - } - - assertEquals("qwerty", result.toString()); - } -} +package com.baeldung.bufferedreadervsfilereader; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.FileReader; +import java.io.IOException; + +import org.junit.jupiter.api.Test; + +class FileReaderUnitTest { + + @Test + void whenReadingAFile_thenReadsCharByChar() { + StringBuilder result = new StringBuilder(); + + try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) { + int i = fr.read(); + + while(i != -1) { + result.append((char)i); + + i = fr.read(); + } + } catch (IOException e) { + e.printStackTrace(); + } + + assertEquals("qwerty", result.toString()); + } +} 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/src/test/java/com/baeldung/multinput/TestMultipleInputsUnitTest.java similarity index 84% rename from core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/multinput/TestMultipleInputsUnitTest.java rename to core-java-modules/core-java-io-apis/src/test/java/com/baeldung/multinput/TestMultipleInputsUnitTest.java index 317d9e817e..0fbcd9bbb2 100644 --- 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/src/test/java/com/baeldung/multinput/TestMultipleInputsUnitTest.java @@ -1,47 +1,49 @@ -package com.baeldung.multinput; - import java.io.ByteArrayInputStream; - import java.io.InputStream; - import java.util.InputMismatchException; - import org.junit.jupiter.api.Assertions; - import org.testng.annotations.Test; -import com.baeldung.multinput.MultiInputs; -public class TestMultipleInputsUnitTest { - @Test - public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() { - String input = "10 20\n"; - InputStream in = new ByteArrayInputStream(input.getBytes()); - System.setIn(in); - MultiInputs mi = new MultiInputs(); - mi.UsingSpaceDelimiter(); - // You can add assertions here to verify the behavior of the method - } - - @Test - public void givenMultipleInputs_whenUsingREDelimiter_thenExpectPrintingOutputs() { - String input = "30, 40\n"; - InputStream in = new ByteArrayInputStream(input.getBytes()); - System.setIn(in); - MultiInputs mi = new MultiInputs(); - mi.UsingREDelimiter(); - // You can add assertions here to verify the behavior of the method - } - - @Test - public void givenMultipleInputs_whenUsingCustomDelimiter_thenExpectPrintingOutputs() { - String input = "50; 60\n"; - InputStream in = new ByteArrayInputStream(input.getBytes()); - System.setIn(in); - MultiInputs mi = new MultiInputs(); - mi.UsingCustomDelimiter(); - // You can add assertions here to verify the behavior of the method - } - - @Test - public void givenInvalidInput_whenUsingSpaceDelimiter_thenExpectInputMismatchException() { - String input = "abc\n"; - InputStream in = new ByteArrayInputStream(input.getBytes()); - System.setIn(in); - MultiInputs mi = new MultiInputs(); - Assertions.assertThrows(InputMismatchException.class, mi::UsingSpaceDelimiter); - } -} +package com.baeldung.multinput; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.InputMismatchException; + +import org.junit.jupiter.api.Assertions; +import org.testng.annotations.Test; + +public class TestMultipleInputsUnitTest { + @Test + public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() { + String input = "10 20\n"; + InputStream in = new ByteArrayInputStream(input.getBytes()); + System.setIn(in); + MultiInputs mi = new MultiInputs(); + mi.UsingSpaceDelimiter(); + // You can add assertions here to verify the behavior of the method + } + + @Test + public void givenMultipleInputs_whenUsingREDelimiter_thenExpectPrintingOutputs() { + String input = "30, 40\n"; + InputStream in = new ByteArrayInputStream(input.getBytes()); + System.setIn(in); + MultiInputs mi = new MultiInputs(); + mi.UsingREDelimiter(); + // You can add assertions here to verify the behavior of the method + } + + @Test + public void givenMultipleInputs_whenUsingCustomDelimiter_thenExpectPrintingOutputs() { + String input = "50; 60\n"; + InputStream in = new ByteArrayInputStream(input.getBytes()); + System.setIn(in); + MultiInputs mi = new MultiInputs(); + mi.UsingCustomDelimiter(); + // You can add assertions here to verify the behavior of the method + } + + @Test + public void givenInvalidInput_whenUsingSpaceDelimiter_thenExpectInputMismatchException() { + String input = "abc\n"; + InputStream in = new ByteArrayInputStream(input.getBytes()); + System.setIn(in); + MultiInputs mi = new MultiInputs(); + Assertions.assertThrows(InputMismatchException.class, mi::UsingSpaceDelimiter); + } +} 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/src/test/java/com/baeldung/outputtofile/ConsoleOutputToFileUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/outputtofile/ConsoleOutputToFileUnitTest.java rename to core-java-modules/core-java-io-apis/src/test/java/com/baeldung/outputtofile/ConsoleOutputToFileUnitTest.java diff --git a/core-java-modules/core-java-jar/README.md b/core-java-modules/core-java-jar/README.md index c99ea63b22..cf4c0f461e 100644 --- a/core-java-modules/core-java-jar/README.md +++ b/core-java-modules/core-java-jar/README.md @@ -4,7 +4,7 @@ This module contains articles about JAR files ### Relevant Articles: -- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) +- [How to Create an Executable JAR with Maven](https://www.baeldung.com/executable-jar-with-maven) - [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class) - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) - [Get Names of Classes Inside a JAR File](https://www.baeldung.com/jar-file-get-class-names) diff --git a/core-java-modules/core-java-lang-6/README.md b/core-java-modules/core-java-lang-6/README.md new file mode 100644 index 0000000000..825a592fee --- /dev/null +++ b/core-java-modules/core-java-lang-6/README.md @@ -0,0 +1,7 @@ +## Core Java Lang (Part 6) + +This module contains articles about core features in the Java language + +### Relevant Articles: + +- [Convert One Enum to Another Enum in Java](https://www.baeldung.com/java-convert-enums) diff --git a/core-java-modules/core-java-lang-6/pom.xml b/core-java-modules/core-java-lang-6/pom.xml new file mode 100644 index 0000000000..86121e0a7f --- /dev/null +++ b/core-java-modules/core-java-lang-6/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + core-java-lang-6 + + + + + org.mapstruct + mapstruct + ${mapstruct.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 17 + 17 + + + + org.mapstruct + mapstruct-processor + ${mapstruct.version} + + + + + + + + + 17 + 17 + UTF-8 + 1.5.5.Final + + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/EnumMapper.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/EnumMapper.java new file mode 100644 index 0000000000..5b6a82d860 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/EnumMapper.java @@ -0,0 +1,26 @@ +package com.baeldung.enums.mapping; + +import org.mapstruct.Mapper; +import org.mapstruct.MappingConstants; +import org.mapstruct.ValueMapping; + +import com.baeldung.enums.mapping.order.CmsOrderStatus; +import com.baeldung.enums.mapping.order.OrderStatus; +import com.baeldung.enums.mapping.user.ExternalUserStatus; +import com.baeldung.enums.mapping.user.UserStatus; + +@Mapper +public interface EnumMapper { + + CmsOrderStatus map(OrderStatus orderStatus); + + @ValueMapping(source = "PENDING", target = "INACTIVE") + @ValueMapping(source = "BLOCKED", target = "INACTIVE") + @ValueMapping(source = "INACTIVATED_BY_SYSTEM", target = "INACTIVE") + @ValueMapping(source = "DELETED", target = "INACTIVE") + ExternalUserStatus map(UserStatus userStatus); + + @ValueMapping(source = MappingConstants.ANY_REMAINING, target = "INACTIVE") + ExternalUserStatus mapDefault(UserStatus userStatus); + +} diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/order/CmsOrderStatus.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/order/CmsOrderStatus.java new file mode 100644 index 0000000000..8c35f62180 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/order/CmsOrderStatus.java @@ -0,0 +1,5 @@ +package com.baeldung.enums.mapping.order; + +public enum CmsOrderStatus { + PENDING, APPROVED, PACKED, DELIVERED +} diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/order/OrderStatus.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/order/OrderStatus.java new file mode 100644 index 0000000000..b46018cc4f --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/order/OrderStatus.java @@ -0,0 +1,13 @@ +package com.baeldung.enums.mapping.order; + +public enum OrderStatus { + PENDING, APPROVED, PACKED, DELIVERED; + + public CmsOrderStatus toCmsOrderStatus() { + return CmsOrderStatus.valueOf(this.name()); + } + + public CmsOrderStatus toCmsOrderStatusOrdinal() { + return CmsOrderStatus.values()[this.ordinal()]; + } +} diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/user/ExternalUserStatus.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/user/ExternalUserStatus.java new file mode 100644 index 0000000000..7361e8fe75 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/user/ExternalUserStatus.java @@ -0,0 +1,5 @@ +package com.baeldung.enums.mapping.user; + +public enum ExternalUserStatus { + ACTIVE, INACTIVE +} diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/user/UserStatus.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/user/UserStatus.java new file mode 100644 index 0000000000..6e6d5d2a9a --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/user/UserStatus.java @@ -0,0 +1,26 @@ +package com.baeldung.enums.mapping.user; + +public enum UserStatus { + PENDING, ACTIVE, BLOCKED, INACTIVATED_BY_SYSTEM, DELETED; + + public ExternalUserStatus toExternalUserStatusViaSwitchStatement() { + return switch (this) { + case PENDING, BLOCKED, INACTIVATED_BY_SYSTEM, DELETED -> ExternalUserStatus.INACTIVE; + case ACTIVE -> ExternalUserStatus.ACTIVE; + }; + } + + public ExternalUserStatus toExternalUserStatusViaRegularSwitch() { + switch (this) { + case PENDING: + case BLOCKED: + case INACTIVATED_BY_SYSTEM: + case DELETED: + return ExternalUserStatus.INACTIVE; + case ACTIVE: + return ExternalUserStatus.ACTIVE; + } + return null; + } + +} diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/user/UserStatusMapper.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/user/UserStatusMapper.java new file mode 100644 index 0000000000..a9ec017d6d --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/user/UserStatusMapper.java @@ -0,0 +1,20 @@ +package com.baeldung.enums.mapping.user; + +import java.util.EnumMap; + +public class UserStatusMapper { + public static EnumMap statusesMap; + + static { + statusesMap = new EnumMap<>(UserStatus.class); + statusesMap.put(UserStatus.PENDING, ExternalUserStatus.INACTIVE); + statusesMap.put(UserStatus.BLOCKED, ExternalUserStatus.INACTIVE); + statusesMap.put(UserStatus.DELETED, ExternalUserStatus.INACTIVE); + statusesMap.put(UserStatus.INACTIVATED_BY_SYSTEM, ExternalUserStatus.INACTIVE); + statusesMap.put(UserStatus.ACTIVE, ExternalUserStatus.ACTIVE); + } + + public static ExternalUserStatus toExternalUserStatus(UserStatus userStatus) { + return statusesMap.get(userStatus); + } +} diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/user/UserStatusWithFieldVariable.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/user/UserStatusWithFieldVariable.java new file mode 100644 index 0000000000..49ec9200ae --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/enums/mapping/user/UserStatusWithFieldVariable.java @@ -0,0 +1,19 @@ +package com.baeldung.enums.mapping.user; + +public enum UserStatusWithFieldVariable { + PENDING(ExternalUserStatus.INACTIVE), + ACTIVE(ExternalUserStatus.ACTIVE), + BLOCKED(ExternalUserStatus.INACTIVE), + INACTIVATED_BY_SYSTEM(ExternalUserStatus.INACTIVE), + DELETED(ExternalUserStatus.INACTIVE); + + private final ExternalUserStatus externalUserStatus; + + UserStatusWithFieldVariable(ExternalUserStatus externalUserStatus) { + this.externalUserStatus = externalUserStatus; + } + + public ExternalUserStatus toExternalUserStatus() { + return externalUserStatus; + } +} diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/enums/mapping/EnumConversionUnitTest.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/enums/mapping/EnumConversionUnitTest.java new file mode 100644 index 0000000000..9272f9b63a --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/enums/mapping/EnumConversionUnitTest.java @@ -0,0 +1,120 @@ +package com.baeldung.enums.mapping; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +import com.baeldung.enums.mapping.order.CmsOrderStatus; +import com.baeldung.enums.mapping.order.OrderStatus; +import com.baeldung.enums.mapping.user.ExternalUserStatus; +import com.baeldung.enums.mapping.user.UserStatus; +import com.baeldung.enums.mapping.user.UserStatusMapper; +import com.baeldung.enums.mapping.user.UserStatusWithFieldVariable; + +public class EnumConversionUnitTest { + + @Test + void whenUsingSwitchStatement_thenEnumConverted() { + UserStatus userStatusDeleted = UserStatus.DELETED; + UserStatus userStatusPending = UserStatus.PENDING; + UserStatus userStatusActive = UserStatus.ACTIVE; + + assertEquals(ExternalUserStatus.INACTIVE, userStatusDeleted.toExternalUserStatusViaSwitchStatement()); + assertEquals(ExternalUserStatus.INACTIVE, userStatusPending.toExternalUserStatusViaSwitchStatement()); + assertEquals(ExternalUserStatus.ACTIVE, userStatusActive.toExternalUserStatusViaSwitchStatement()); + } + + @Test + void whenUsingSwitch_thenEnumConverted() { + UserStatus userStatusDeleted = UserStatus.DELETED; + UserStatus userStatusPending = UserStatus.PENDING; + UserStatus userStatusActive = UserStatus.ACTIVE; + + assertEquals(ExternalUserStatus.INACTIVE, userStatusDeleted.toExternalUserStatusViaRegularSwitch()); + assertEquals(ExternalUserStatus.INACTIVE, userStatusPending.toExternalUserStatusViaRegularSwitch()); + assertEquals(ExternalUserStatus.ACTIVE, userStatusActive.toExternalUserStatusViaRegularSwitch()); + } + + @Test + void whenUsingFieldVariable_thenEnumConverted() { + UserStatusWithFieldVariable userStatusDeleted = UserStatusWithFieldVariable.DELETED; + UserStatusWithFieldVariable userStatusPending = UserStatusWithFieldVariable.PENDING; + UserStatusWithFieldVariable userStatusActive = UserStatusWithFieldVariable.ACTIVE; + + assertEquals(ExternalUserStatus.INACTIVE, userStatusDeleted.toExternalUserStatus()); + assertEquals(ExternalUserStatus.INACTIVE, userStatusPending.toExternalUserStatus()); + assertEquals(ExternalUserStatus.ACTIVE, userStatusActive.toExternalUserStatus()); + } + + @Test + void whenUsingEnumMap_thenEnumConverted() { + UserStatus userStatusDeleted = UserStatus.DELETED; + UserStatus userStatusPending = UserStatus.PENDING; + UserStatus userStatusActive = UserStatus.ACTIVE; + + assertEquals(ExternalUserStatus.INACTIVE, UserStatusMapper.toExternalUserStatus(userStatusDeleted)); + assertEquals(ExternalUserStatus.INACTIVE, UserStatusMapper.toExternalUserStatus(userStatusPending)); + assertEquals(ExternalUserStatus.ACTIVE, UserStatusMapper.toExternalUserStatus(userStatusActive)); + } + + @Test + void whenUsingOrdinalApproach_thenEnumConverted() { + OrderStatus orderStatusApproved = OrderStatus.APPROVED; + OrderStatus orderStatusDelivered = OrderStatus.DELIVERED; + OrderStatus orderStatusPending = OrderStatus.PENDING; + + assertEquals(CmsOrderStatus.APPROVED, orderStatusApproved.toCmsOrderStatusOrdinal()); + assertEquals(CmsOrderStatus.DELIVERED, orderStatusDelivered.toCmsOrderStatusOrdinal()); + assertEquals(CmsOrderStatus.PENDING, orderStatusPending.toCmsOrderStatusOrdinal()); + } + + @Test + void whenUsingEnumName_thenEnumConverted() { + OrderStatus orderStatusApproved = OrderStatus.APPROVED; + OrderStatus orderStatusDelivered = OrderStatus.DELIVERED; + OrderStatus orderStatusPending = OrderStatus.PENDING; + + assertEquals(CmsOrderStatus.APPROVED, orderStatusApproved.toCmsOrderStatus()); + assertEquals(CmsOrderStatus.DELIVERED, orderStatusDelivered.toCmsOrderStatus()); + assertEquals(CmsOrderStatus.PENDING, orderStatusPending.toCmsOrderStatus()); + } + + @Test + void whenUsingDefaultMapstruct_thenEnumConverted() { + UserStatus userStatusDeleted = UserStatus.DELETED; + UserStatus userStatusPending = UserStatus.PENDING; + UserStatus userStatusActive = UserStatus.ACTIVE; + + EnumMapper enumMapper = new EnumMapperImpl(); + + assertEquals(ExternalUserStatus.INACTIVE, enumMapper.map(userStatusDeleted)); + assertEquals(ExternalUserStatus.INACTIVE, enumMapper.map(userStatusPending)); + assertEquals(ExternalUserStatus.ACTIVE, enumMapper.map(userStatusActive)); + } + + @Test + void whenUsingConfiguredMapstruct_thenEnumConverted() { + OrderStatus orderStatusApproved = OrderStatus.APPROVED; + OrderStatus orderStatusDelivered = OrderStatus.DELIVERED; + OrderStatus orderStatusPending = OrderStatus.PENDING; + + EnumMapper enumMapper = new EnumMapperImpl(); + + assertEquals(CmsOrderStatus.APPROVED, enumMapper.map(orderStatusApproved)); + assertEquals(CmsOrderStatus.DELIVERED, enumMapper.map(orderStatusDelivered)); + assertEquals(CmsOrderStatus.PENDING, enumMapper.map(orderStatusPending)); + } + + @Test + void whenUsingConfiguredWithRemainingMapstruct_thenEnumConverted() { + UserStatus userStatusDeleted = UserStatus.DELETED; + UserStatus userStatusPending = UserStatus.PENDING; + UserStatus userStatusActive = UserStatus.ACTIVE; + + EnumMapper enumMapper = new EnumMapperImpl(); + + assertEquals(ExternalUserStatus.INACTIVE, enumMapper.mapDefault(userStatusDeleted)); + assertEquals(ExternalUserStatus.INACTIVE, enumMapper.mapDefault(userStatusPending)); + assertEquals(ExternalUserStatus.ACTIVE, enumMapper.mapDefault(userStatusActive)); + } +} 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 ea3309dc0a..ba18c57ab0 100644 --- a/core-java-modules/core-java-lang-oop-patterns/README.md +++ b/core-java-modules/core-java-lang-oop-patterns/README.md @@ -9,3 +9,4 @@ This module contains articles about Object-oriented programming (OOP) patterns i - [How to Make a Deep Copy of an Object in Java](https://www.baeldung.com/java-deep-copy) - [Using an Interface vs. Abstract Class in Java](https://www.baeldung.com/java-interface-vs-abstract-class) - [Should We Create an Interface for Only One Implementation?](https://www.baeldung.com/java-interface-single-implementation) +- [How to Deep Copy an ArrayList in Java](https://www.baeldung.com/java-arraylist-deep-copy) diff --git a/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/niovsnio2/NioVsNio2UnitTest.java b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/niovsnio2/NioVsNio2UnitTest.java index 7413ebda13..6d6ed0ebbf 100644 --- a/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/niovsnio2/NioVsNio2UnitTest.java +++ b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/niovsnio2/NioVsNio2UnitTest.java @@ -65,6 +65,7 @@ public class NioVsNio2UnitTest { public void listFilesUsingWalk() throws Exception { Path path = Paths.get("src/test"); Stream walk = Files.walk(path); - walk.forEach(System.out::println); + + assertThat(walk.findAny()).isPresent(); } } diff --git a/core-java-modules/core-java-numbers-6/README.md b/core-java-modules/core-java-numbers-6/README.md index 959d434935..560a84f851 100644 --- a/core-java-modules/core-java-numbers-6/README.md +++ b/core-java-modules/core-java-numbers-6/README.md @@ -1,4 +1,6 @@ ### Relevant Articles: - [Java Program to Estimate Pi](https://www.baeldung.com/java-monte-carlo-compute-pi) - [Convert Integer to Hexadecimal in Java](https://www.baeldung.com/java-convert-int-to-hex) +- [Integer.class Vs. Integer.TYPE Vs. int.class](https://www.baeldung.com/java-integer-class-vs-type-vs-int) +- [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian) - More articles: [[<-- prev]](../core-java-numbers-5) diff --git a/core-java-modules/core-java-numbers-6/src/main/java/com/baeldung/endianness/Endianness.java b/core-java-modules/core-java-numbers-6/src/main/java/com/baeldung/endianness/Endianness.java new file mode 100644 index 0000000000..b84f301ee8 --- /dev/null +++ b/core-java-modules/core-java-numbers-6/src/main/java/com/baeldung/endianness/Endianness.java @@ -0,0 +1,17 @@ +package com.baeldung.endianness; + +import java.nio.ByteBuffer; + +public class Endianness { + + public static void main(String[] args) { + int value = 123456789; + byte[] bytes = ByteBuffer.allocate(4) + .putInt(value) + .array(); + + for (byte b : bytes) { + System.out.format("0x%x ", b); + } + } +} diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integerclassintegertypeintclass/IntegerClassIntegerTYPEIntClassUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integerclassintegertypeintclass/IntegerClassIntegerTYPEIntClassUnitTest.java new file mode 100644 index 0000000000..53d6c7f71e --- /dev/null +++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integerclassintegertypeintclass/IntegerClassIntegerTYPEIntClassUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.integerclassintegertypeintclass; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class IntegerClassIntegerTYPEIntClassUnitTest { + + @Test + public void givenIntegerClass_whenGetName_thenVerifyClassName() { + Class integerClass = Integer.class; + Assertions.assertEquals("java.lang.Integer", integerClass.getName()); + Assertions.assertEquals(Number.class, integerClass.getSuperclass()); + Assertions.assertFalse(integerClass.isPrimitive()); + } + + public int sum(int a, int b) { + return a + b; + } + + public int sum(Integer a, Integer b) { + return a + b; + } + + public int sum(int a, Integer b) { + return a + b; + } + + @Test + public void givenIntAndInteger_whenAddingValues_thenVerifySum() { + int primitiveValue = 10; + Integer wrapperValue = Integer.valueOf(primitiveValue); + Assertions.assertEquals(20, sum(primitiveValue, primitiveValue)); + Assertions.assertEquals(20, sum(primitiveValue, wrapperValue)); + Assertions.assertEquals(20, sum(wrapperValue, wrapperValue)); + Assertions.assertEquals(Integer.TYPE.getName(), int.class.getName()); + } + + @Test + public void givenIntValue_whenUsingIntClass_thenVerifyIntClassProperties() { + Class intClass = int.class; + Assertions.assertEquals("int", intClass.getName()); + Assertions.assertTrue(intClass.isPrimitive()); + Assertions.assertEquals(int.class, intClass); + } +} diff --git a/core-java-modules/core-java-numbers-conversions/README.md b/core-java-modules/core-java-numbers-conversions/README.md index 21810834bd..b4c593c494 100644 --- a/core-java-modules/core-java-numbers-conversions/README.md +++ b/core-java-modules/core-java-numbers-conversions/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Convert a Number to a Letter in Java](https://www.baeldung.com/java-convert-number-to-letter) +- [Convert Long to BigDecimal in Java](https://www.baeldung.com/java-convert-long-bigdecimal) diff --git a/core-java-modules/core-java-scanner/README.md b/core-java-modules/core-java-scanner/README.md new file mode 100644 index 0000000000..87bd9c41bc --- /dev/null +++ b/core-java-modules/core-java-scanner/README.md @@ -0,0 +1,15 @@ +## Core Java Scanner + +This module contains articles about the Scanner. + +### Relevant Articles: +- [Java Scanner](https://www.baeldung.com/java-scanner) +- [Scanner nextLine() Method](https://www.baeldung.com/java-scanner-nextline) +- [Java Scanner hasNext() vs. hasNextLine()](https://www.baeldung.com/java-scanner-hasnext-vs-hasnextline) +- [Read Date in Java Using Scanner](https://www.baeldung.com/java-scanner-read-date) +- [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input) +- [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer) +- [Storing Java Scanner Input in an Array](https://www.baeldung.com/java-store-scanner-input-in-array) +- [How to Take Input as String With Spaces in Java Using Scanner?](https://www.baeldung.com/java-scanner-input-with-spaces) +- [What’s the difference between Scanner next() and nextLine() methods?](https://www.baeldung.com/java-scanner-next-vs-nextline) +- [Handle NoSuchElementException When Reading a File Through Scanner](https://www.baeldung.com/java-scanner-nosuchelementexception-reading-file) diff --git a/core-java-modules/core-java-scanner/pom.xml b/core-java-modules/core-java-scanner/pom.xml new file mode 100644 index 0000000000..f149f51955 --- /dev/null +++ b/core-java-modules/core-java-scanner/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + core-java-scanner + core-java-scanner + 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 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-io-apis-3/src/main/java/com/baeldung/scanner/DateScanner.java b/core-java-modules/core-java-scanner/src/main/java/com/baeldung/scanner/DateScanner.java similarity index 96% rename from core-java-modules/core-java-io-apis-3/src/main/java/com/baeldung/scanner/DateScanner.java rename to core-java-modules/core-java-scanner/src/main/java/com/baeldung/scanner/DateScanner.java index a9f3ba820a..79fda8dc35 100644 --- a/core-java-modules/core-java-io-apis-3/src/main/java/com/baeldung/scanner/DateScanner.java +++ b/core-java-modules/core-java-scanner/src/main/java/com/baeldung/scanner/DateScanner.java @@ -1,29 +1,29 @@ -package com.baeldung.scanner; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.Scanner; - -public class DateScanner { - - LocalDate scanToLocalDate(String input) { - try (Scanner scanner = new Scanner(input)) { - String dateString = scanner.next(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - return LocalDate.parse(dateString, formatter); - } - } - - Date scanToDate(String input) throws ParseException { - try (Scanner scanner = new Scanner(input)) { - String dateString = scanner.next(); - DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); - return formatter.parse(dateString); - } - } - -} +package com.baeldung.scanner; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.Scanner; + +public class DateScanner { + + LocalDate scanToLocalDate(String input) { + try (Scanner scanner = new Scanner(input)) { + String dateString = scanner.next(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + return LocalDate.parse(dateString, formatter); + } + } + + Date scanToDate(String input) throws ParseException { + try (Scanner scanner = new Scanner(input)) { + String dateString = scanner.next(); + DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); + return formatter.parse(dateString); + } + } + +} diff --git a/core-java-modules/core-java-io-apis/src/main/java/com/baeldung/scanner/HasNextVsHasNextLineDemo.java b/core-java-modules/core-java-scanner/src/main/java/com/baeldung/scanner/HasNextVsHasNextLineDemo.java similarity index 100% rename from core-java-modules/core-java-io-apis/src/main/java/com/baeldung/scanner/HasNextVsHasNextLineDemo.java rename to core-java-modules/core-java-scanner/src/main/java/com/baeldung/scanner/HasNextVsHasNextLineDemo.java diff --git a/core-java-modules/core-java-io-apis/src/main/java/com/baeldung/scanner/NextLineAfterNextMethods.java b/core-java-modules/core-java-scanner/src/main/java/com/baeldung/scanner/NextLineAfterNextMethods.java similarity index 100% rename from core-java-modules/core-java-io-apis/src/main/java/com/baeldung/scanner/NextLineAfterNextMethods.java rename to core-java-modules/core-java-scanner/src/main/java/com/baeldung/scanner/NextLineAfterNextMethods.java diff --git a/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/scanner/ScannerNoSuchElementException.java b/core-java-modules/core-java-scanner/src/main/java/com/baeldung/scanner/ScannerNoSuchElementException.java similarity index 100% rename from core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/scanner/ScannerNoSuchElementException.java rename to core-java-modules/core-java-scanner/src/main/java/com/baeldung/scanner/ScannerNoSuchElementException.java diff --git a/core-java-modules/core-java-io-apis-3/src/test/java/com/baeldung/emptyfile/CheckFileIsEmptyUnitTest.java b/core-java-modules/core-java-scanner/src/test/java/com/baeldung/emptyfile/CheckFileIsEmptyUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-apis-3/src/test/java/com/baeldung/emptyfile/CheckFileIsEmptyUnitTest.java rename to core-java-modules/core-java-scanner/src/test/java/com/baeldung/emptyfile/CheckFileIsEmptyUnitTest.java diff --git a/core-java-modules/core-java-io-apis-3/src/test/java/com/baeldung/scanner/DateScannerUnitTest.java b/core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/DateScannerUnitTest.java similarity index 96% rename from core-java-modules/core-java-io-apis-3/src/test/java/com/baeldung/scanner/DateScannerUnitTest.java rename to core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/DateScannerUnitTest.java index 1ecd440d95..0a02db12f3 100644 --- a/core-java-modules/core-java-io-apis-3/src/test/java/com/baeldung/scanner/DateScannerUnitTest.java +++ b/core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/DateScannerUnitTest.java @@ -1,26 +1,26 @@ -package com.baeldung.scanner; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; - -import org.junit.jupiter.api.Test; - -class DateScannerUnitTest { - - @Test - void whenScanToLocalDate_ThenCorrectLocalDate() { - String dateString = "2018-09-09"; - assertEquals(LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd")), new DateScanner().scanToLocalDate(dateString)); - } - - @Test - void whenScanToDate_ThenCorrectDate() throws ParseException { - String dateString = "2018-09-09"; - assertEquals(new SimpleDateFormat("yyyy-MM-dd").parse(dateString), new DateScanner().scanToDate(dateString)); - } - -} +package com.baeldung.scanner; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +import org.junit.jupiter.api.Test; + +class DateScannerUnitTest { + + @Test + void whenScanToLocalDate_ThenCorrectLocalDate() { + String dateString = "2018-09-09"; + assertEquals(LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd")), new DateScanner().scanToLocalDate(dateString)); + } + + @Test + void whenScanToDate_ThenCorrectDate() throws ParseException { + String dateString = "2018-09-09"; + assertEquals(new SimpleDateFormat("yyyy-MM-dd").parse(dateString), new DateScanner().scanToDate(dateString)); + } + +} 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-scanner/src/test/java/com/baeldung/scanner/InputWithSpacesUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/InputWithSpacesUnitTest.java rename to core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/InputWithSpacesUnitTest.java diff --git a/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/scanner/JavaScannerUnitTest.java b/core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/JavaScannerUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-apis/src/test/java/com/baeldung/scanner/JavaScannerUnitTest.java rename to core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/JavaScannerUnitTest.java 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-scanner/src/test/java/com/baeldung/scanner/NextLineVsNextIntUnitTest.java similarity index 96% rename from core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextLineVsNextIntUnitTest.java rename to core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/NextLineVsNextIntUnitTest.java index 3aae0469d0..8fab7c62e9 100644 --- a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextLineVsNextIntUnitTest.java +++ b/core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/NextLineVsNextIntUnitTest.java @@ -1,85 +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); - } - +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-scanner/src/test/java/com/baeldung/scanner/NextVsNextLineUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextVsNextLineUnitTest.java rename to core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/NextVsNextLineUnitTest.java 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-scanner/src/test/java/com/baeldung/scanner/ScanACharacterUnitTest.java similarity index 96% rename from core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScanACharacterUnitTest.java rename to core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/ScanACharacterUnitTest.java index 340b58bbf6..1a70c6e3af 100644 --- a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScanACharacterUnitTest.java +++ b/core-java-modules/core-java-scanner/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/ScannerNoSuchElementExceptionUnitTest.java b/core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/ScannerNoSuchElementExceptionUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScannerNoSuchElementExceptionUnitTest.java rename to core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/ScannerNoSuchElementExceptionUnitTest.java 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-scanner/src/test/java/com/baeldung/scanner/ScannerToArrayUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScannerToArrayUnitTest.java rename to core-java-modules/core-java-scanner/src/test/java/com/baeldung/scanner/ScannerToArrayUnitTest.java diff --git a/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/scannernextline/ScannerNextLineUnitTest.java b/core-java-modules/core-java-scanner/src/test/java/com/baeldung/scannernextline/ScannerNextLineUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-apis/src/test/java/com/baeldung/scannernextline/ScannerNextLineUnitTest.java rename to core-java-modules/core-java-scanner/src/test/java/com/baeldung/scannernextline/ScannerNextLineUnitTest.java index f3e76229da..5ea29e63e0 100644 --- a/core-java-modules/core-java-io-apis/src/test/java/com/baeldung/scannernextline/ScannerNextLineUnitTest.java +++ b/core-java-modules/core-java-scanner/src/test/java/com/baeldung/scannernextline/ScannerNextLineUnitTest.java @@ -1,11 +1,11 @@ package com.baeldung.scannernextline; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.util.NoSuchElementException; import java.util.Scanner; -import static org.junit.Assert.assertEquals; +import org.junit.Test; public class ScannerNextLineUnitTest { diff --git a/core-java-modules/core-java-io-apis-2/src/test/resources/emptyFile.txt b/core-java-modules/core-java-scanner/src/test/resources/emptyFile.txt similarity index 100% rename from core-java-modules/core-java-io-apis-2/src/test/resources/emptyFile.txt rename to core-java-modules/core-java-scanner/src/test/resources/emptyFile.txt diff --git a/core-java-modules/core-java-io-apis/src/test/resources/test_read.in b/core-java-modules/core-java-scanner/src/test/resources/test_read.in similarity index 100% rename from core-java-modules/core-java-io-apis/src/test/resources/test_read.in rename to core-java-modules/core-java-scanner/src/test/resources/test_read.in diff --git a/core-java-modules/core-java-io-apis/src/test/resources/test_read_d.in b/core-java-modules/core-java-scanner/src/test/resources/test_read_d.in similarity index 100% rename from core-java-modules/core-java-io-apis/src/test/resources/test_read_d.in rename to core-java-modules/core-java-scanner/src/test/resources/test_read_d.in diff --git a/core-java-modules/core-java-io-apis/src/test/resources/test_read_multiple.in b/core-java-modules/core-java-scanner/src/test/resources/test_read_multiple.in similarity index 100% rename from core-java-modules/core-java-io-apis/src/test/resources/test_read_multiple.in rename to core-java-modules/core-java-scanner/src/test/resources/test_read_multiple.in diff --git a/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamToImmutableUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamToImmutableUnitTest.java index e5339d8327..ba99a6eaf7 100644 --- a/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamToImmutableUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamToImmutableUnitTest.java @@ -1,57 +1,59 @@ package com.baeldung.streams; import com.google.common.collect.ImmutableList; -import org.junit.Test; import java.util.*; import java.util.stream.IntStream; import static java.util.stream.Collectors.*; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class StreamToImmutableUnitTest { +import org.junit.jupiter.api.Test; + +class StreamToImmutableUnitTest { @Test - public void whenUsingCollectingToImmutableSet_thenSuccess() { + void whenUsingCollectingToImmutableSet_thenSuccess() { List givenList = Arrays.asList("a", "b", "c"); List result = givenList.stream() .collect(collectingAndThen(toSet(), ImmutableList::copyOf)); - System.out.println(result.getClass()); + assertEquals("com.google.common.collect.RegularImmutableList", result.getClass().getName()); } @Test - public void whenUsingCollectingToUnmodifiableList_thenSuccess() { + void whenUsingCollectingToUnmodifiableList_thenSuccess() { List givenList = new ArrayList<>(Arrays.asList("a", "b", "c")); List result = givenList.stream() .collect(collectingAndThen(toList(), Collections::unmodifiableList)); - System.out.println(result.getClass()); + assertEquals("java.util.Collections$UnmodifiableRandomAccessList", result.getClass().getName()); } @Test - public void whenCollectToImmutableList_thenSuccess() { + void whenCollectToImmutableList_thenSuccess() { List list = IntStream.range(0, 9) .boxed() .collect(ImmutableList.toImmutableList()); - System.out.println(list.getClass()); + assertEquals("com.google.common.collect.RegularImmutableList", list.getClass().getName()); } @Test - public void whenCollectToMyImmutableListCollector_thenSuccess() { + void whenCollectToMyImmutableListCollector_thenSuccess() { List givenList = Arrays.asList("a", "b", "c", "d"); List result = givenList.stream() .collect(MyImmutableListCollector.toImmutableList()); - System.out.println(result.getClass()); + assertEquals("java.util.Collections$UnmodifiableRandomAccessList", result.getClass().getName()); } @Test - public void whenPassingSupplier_thenSuccess() { + void whenPassingSupplier_thenSuccess() { List givenList = Arrays.asList("a", "b", "c", "d"); List result = givenList.stream() .collect(MyImmutableListCollector.toImmutableList(LinkedList::new)); - System.out.println(result.getClass()); + assertEquals("java.util.Collections$UnmodifiableList", result.getClass().getName()); } } diff --git a/core-java-modules/core-java-string-operations-6/README.md b/core-java-modules/core-java-string-operations-6/README.md index e866f50860..134f67d15d 100644 --- a/core-java-modules/core-java-string-operations-6/README.md +++ b/core-java-modules/core-java-string-operations-6/README.md @@ -5,4 +5,6 @@ - [Check if a String Is All Uppercase or Lowercase in Java](https://www.baeldung.com/java-check-string-uppercase-lowercase) - [Java – Generate Random String](https://www.baeldung.com/java-random-string) - [Fixing “constant string too long” Build Error](https://www.baeldung.com/java-constant-string-too-long-error) -- [Compact Strings in Java 9](https://www.baeldung.com/java-9-compact-string) \ No newline at end of file +- [Compact Strings in Java 9](https://www.baeldung.com/java-9-compact-string) +- [Split a String Into Digit and Non-Digit Substrings](https://www.baeldung.com/java-split-string-digits-letters) +- [Check if a String Contains Non-Alphanumeric Characters](https://www.baeldung.com/java-string-test-special-characters) diff --git a/core-java-modules/core-java-string-operations-6/src/main/java/com/baeldung/uniquecharcheck/UniqueCharChecker.java b/core-java-modules/core-java-string-operations-6/src/main/java/com/baeldung/uniquecharcheck/UniqueCharChecker.java new file mode 100644 index 0000000000..365307708c --- /dev/null +++ b/core-java-modules/core-java-string-operations-6/src/main/java/com/baeldung/uniquecharcheck/UniqueCharChecker.java @@ -0,0 +1,60 @@ +package com.baeldung.uniquecharcheck; + +import org.apache.commons.lang3.StringUtils; + +import java.util.*; +import java.util.stream.Collectors; + +public class UniqueCharChecker { + + public static boolean checkV1(String str) { + char[] chars = str.toUpperCase().toCharArray(); + for (int i = 0; i < chars.length; i++) { + for (int j = i + 1; j < chars.length; j++) { + if(chars[i] == chars[j]) { + return false; + } + } + } + return true; + } + + public static boolean checkV2(String str) { + char[] chars = str.toUpperCase().toCharArray(); + Arrays.sort(chars); + for (int i = 0; i < chars.length - 1; i++) { + if(chars[i] == chars[i+1]) { + return false; + } + } + return true; + } + + public static boolean checkV3(String str) { + char[] chars = str.toUpperCase().toCharArray(); + Set set = new HashSet <>(); + for (char c: chars) { + set.add(c); + } + return set.size() == str.length(); + } + + public static boolean checkV4(String str) { + boolean isUnique = str.toUpperCase().chars() + .mapToObj(c -> (char)c) + .collect(Collectors.toSet()) + .size() == str.length(); + return isUnique; + } + + public static boolean checkV5(String str) { + for (int i = 0; i < str.length(); i++) { + String curChar = String.valueOf(str.charAt(i)); + String remainingStr = str.substring(i+1); + if(StringUtils.containsIgnoreCase(remainingStr, curChar)) { + return false; + } + } + return true; + } +} diff --git a/core-java-modules/core-java-string-operations-6/src/test/java/com/baeldung/uniquecharcheck/UniqueCharCheckerUnitTest.java b/core-java-modules/core-java-string-operations-6/src/test/java/com/baeldung/uniquecharcheck/UniqueCharCheckerUnitTest.java new file mode 100644 index 0000000000..938787662f --- /dev/null +++ b/core-java-modules/core-java-string-operations-6/src/test/java/com/baeldung/uniquecharcheck/UniqueCharCheckerUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.uniquecharcheck; + +import org.junit.Test; + +import java.util.Arrays; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + + +public class UniqueCharCheckerUnitTest { + + @Test + public void givenMethCheck1_whenUnique_returnTrue() { + String[] sampleStrings = new String[]{"Justfewdi123", "$%&Hibusc", "Hibusc%$#", "მშვნიერ"}; + final String MSG = "Duplicate found"; + Arrays.stream(sampleStrings) + .forEach(sampleStr -> assertTrue(MSG + " in " + sampleStr, UniqueCharChecker.checkV1(sampleStr))); + } + @Test + public void givenMethCheck2_whenUnique_returnTrue() { + String[] sampleStrings = new String[]{"Justfewdi123", "$%&Hibusc", "Hibusc%$#", "მშვნიერ"}; + final String MSG = "Duplicate found"; + Arrays.stream(sampleStrings) + .forEach(sampleStr -> assertTrue(MSG + " in " + sampleStr, UniqueCharChecker.checkV2(sampleStr))); + } + + @Test + public void givenMethCheck3_whenUnique_returnTrue() { + String[] sampleStrings = new String[]{"Justfewdi123", "$%&Hibusc", "Hibusc%$#", "მშვნიერ"}; + final String MSG = "Duplicate found"; + Arrays.stream(sampleStrings) + .forEach(sampleStr -> assertTrue(MSG + " in " + sampleStr, UniqueCharChecker.checkV3(sampleStr))); + } + + @Test + public void givenMethCheck4_whenUnique_returnTrue() { + String[] sampleStrings = new String[]{"Justfewdi123", "$%&Hibusc", "Hibusc%$#", "მშვნიერ"}; + final String MSG = "Duplicate found"; + Arrays.stream(sampleStrings) + .forEach(sampleStr -> assertTrue(MSG + " in " + sampleStr, UniqueCharChecker.checkV1(sampleStr))); + } + @Test + public void givenMethCheck5_whenUnique_returnTrue() { + String[] sampleStrings = new String[]{"Justfewdi123", "$%&Hibusc", "Hibusc%$#", "მშვნიერ"}; + final String MSG = "Duplicate found"; + Arrays.stream(sampleStrings) + .forEach(sampleStr -> assertTrue(MSG + " in " + sampleStr, UniqueCharChecker.checkV5(sampleStr))); + } + + @Test + public void givenMethCheck1_whenNotUnique_returnFalse() { + String[] sampleStrings = new String[]{"Justfewdif123", "$%&Hibushc", "Hibusuc%$#", "Hi%busc%$#", "მშვენიერი"}; + final String MSG = "Duplicate not found"; + Arrays.stream(sampleStrings) + .forEach(sampleStr -> assertFalse(MSG + " in " + sampleStr, UniqueCharChecker.checkV1(sampleStr))); + } + + @Test + public void givenMethCheck2_whenNotUnique_returnFalse() { + String[] sampleStrings = new String[]{"Justfewdif123", "$%&Hibushc", "Hibusuc%$#", "Hi%busc%$#", "მშვენიერი"}; + final String MSG = "Duplicate not found"; + Arrays.stream(sampleStrings) + .forEach(sampleStr -> assertFalse(MSG + " in " + sampleStr, UniqueCharChecker.checkV2(sampleStr))); + + } + + @Test + public void givenMethCheck3_whenNotUnique_returnFalse() { + String[] sampleStrings = new String[]{"Justfewdif123", "$%&Hibushc", "Hibusuc%$#", "Hi%busc%$#", "მშვენიერი"}; + final String MSG = "Duplicate not found"; + Arrays.stream(sampleStrings) + .forEach(sampleStr -> assertFalse(MSG + " in " + sampleStr, UniqueCharChecker.checkV3(sampleStr))); + } + + @Test + public void givenMethCheck4_whenNotUnique_returnFalse() { + String[] sampleStrings = new String[]{"Justfewdif123", "$%&Hibushc", "Hibusuc%$#", "Hi%busc%$#", "მშვენიერი"}; + final String MSG = "Duplicate not found"; + Arrays.stream(sampleStrings) + .forEach(sampleStr -> assertFalse(MSG + " in " + sampleStr, UniqueCharChecker.checkV4(sampleStr))); + } + +@Test +public void givenMethCheck5_whenNotUnique_returnFalse() { + String[] sampleStrings = new String[]{"Justfewdif123", "$%&Hibushc", "Hibusuc%$#", "Hi%busc%$#", "მშვენიერი"}; + final String MSG = "Duplicate not found"; + Arrays.stream(sampleStrings) + .forEach(sampleStr -> assertFalse(MSG + " in " + sampleStr, UniqueCharChecker.checkV5(sampleStr))); +} + +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 9144e16359..bfa48893e9 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -81,7 +81,6 @@ core-java-io-4 core-java-io-apis core-java-io-apis-2 - core-java-io-apis-3 core-java-io-conversions core-java-jar core-java-jndi @@ -93,6 +92,7 @@ core-java-lang-3 core-java-lang-4 core-java-lang-5 + core-java-lang-6 core-java-lang-math core-java-lang-math-2 core-java-lang-oop-constructors @@ -124,6 +124,7 @@ core-java-properties core-java-reflection core-java-reflection-2 + core-java-scanner core-java-security-2 core-java-security-3 core-java-security-algorithms diff --git a/gradle-modules/gradle-7/README.md b/gradle-modules/gradle-7/README.md index 98fb968e82..e59b59f9fd 100644 --- a/gradle-modules/gradle-7/README.md +++ b/gradle-modules/gradle-7/README.md @@ -6,3 +6,4 @@ - [Different Dependency Version Declarations in Gradle](https://www.baeldung.com/gradle-different-dependency-version-declarations) - [Generating Javadoc With Gradle](https://www.baeldung.com/java-gradle-javadoc) - [Generating WSDL Stubs With Gradle](https://www.baeldung.com/java-gradle-create-wsdl-stubs) +- [Gradle Toolchains Support for JVM Projects](https://www.baeldung.com/java-gradle-toolchains-jvm-projects) diff --git a/gradle-modules/gradle-7/toolchains-feature/.gitattributes b/gradle-modules/gradle-7/toolchains-feature/.gitattributes new file mode 100644 index 0000000000..097f9f98d9 --- /dev/null +++ b/gradle-modules/gradle-7/toolchains-feature/.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/toolchains-feature/.gitignore b/gradle-modules/gradle-7/toolchains-feature/.gitignore new file mode 100644 index 0000000000..1b6985c009 --- /dev/null +++ b/gradle-modules/gradle-7/toolchains-feature/.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/toolchains-feature/build.gradle b/gradle-modules/gradle-7/toolchains-feature/build.gradle new file mode 100644 index 0000000000..de1f6ad6e3 --- /dev/null +++ b/gradle-modules/gradle-7/toolchains-feature/build.gradle @@ -0,0 +1,49 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * This is a general purpose Gradle build. + * Learn more about Gradle by exploring our samples at https://docs.gradle.org/8.1.1/samples + */ +plugins { + id 'java' +} +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} + +tasks { + compileTestJava { + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + } +} + +//compileTestJava.getOptions().setFork(true) +//compileTestJava.getOptions().getForkOptions().setExecutable('/home/mpolivaha/.jdks/corretto-17.0.4.1/bin/javac') + +//compileJava.getOptions().setFork(true) +//compileJava.getOptions().getForkOptions().setExecutable('/home/mpolivaha/.jdks/corretto-17.0.4.1/bin/javac') + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + vendor = JvmVendorSpec.AMAZON + implementation = JvmImplementation.VENDOR_SPECIFIC + } +} + +tasks.named('compileJava').get().configure { + javaCompiler = javaToolchains.compilerFor { + languageVersion = JavaLanguageVersion.of(17) + vendor = JvmVendorSpec.AMAZON + implementation = JvmImplementation.VENDOR_SPECIFIC + } +} +tasks.register("testOnAmazonJdk", Test.class, { + javaLauncher = javaToolchains.launcherFor { + languageVersion = JavaLanguageVersion.of(17) + vendor = JvmVendorSpec.AMAZON + } +}) +tasks.named("testClasses").get().finalizedBy("testOnAmazonJdk") \ No newline at end of file diff --git a/gradle-modules/gradle-7/toolchains-feature/gradle/wrapper/gradle-wrapper.properties b/gradle-modules/gradle-7/toolchains-feature/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..37aef8d3f0 --- /dev/null +++ b/gradle-modules/gradle-7/toolchains-feature/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/gradle-modules/gradle-7/toolchains-feature/gradlew b/gradle-modules/gradle-7/toolchains-feature/gradlew new file mode 100755 index 0000000000..aeb74cbb43 --- /dev/null +++ b/gradle-modules/gradle-7/toolchains-feature/gradlew @@ -0,0 +1,245 @@ +#!/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 + +# 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 + + +# 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"' + +# 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/toolchains-feature/gradlew.bat b/gradle-modules/gradle-7/toolchains-feature/gradlew.bat new file mode 100644 index 0000000000..93e3f59f13 --- /dev/null +++ b/gradle-modules/gradle-7/toolchains-feature/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/toolchains-feature/settings.gradle b/gradle-modules/gradle-7/toolchains-feature/settings.gradle new file mode 100644 index 0000000000..1de93d5f8c --- /dev/null +++ b/gradle-modules/gradle-7/toolchains-feature/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.1.1/userguide/multi_project_builds.html + */ + +rootProject.name = 'toolchains-feature' diff --git a/jackson-jr/src/main/java/com/baeldung/jacksonjr/JacksonJrFeatures.java b/jackson-jr/src/main/java/com/baeldung/jacksonjr/JacksonJrFeatures.java deleted file mode 100644 index 26adbf12d2..0000000000 --- a/jackson-jr/src/main/java/com/baeldung/jacksonjr/JacksonJrFeatures.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.baeldung.jacksonjr; - -import com.fasterxml.jackson.jr.annotationsupport.JacksonAnnotationExtension; -import com.fasterxml.jackson.jr.ob.JSON; -import com.fasterxml.jackson.jr.ob.JacksonJrExtension; -import com.fasterxml.jackson.jr.ob.api.ExtensionContext; - -import java.io.IOException; -import java.util.LinkedHashMap; - -public class JacksonJrFeatures { - - public static String jsonObject() throws IOException { - return JSON.std - .with(JSON.Feature.PRETTY_PRINT_OUTPUT) - .asString(new LinkedHashMap() {{ - put("name", "John Doe"); - put("age", 30); - }}); - } - - public static String jsonComposer() throws IOException { - return JSON.std - .with(JSON.Feature.PRETTY_PRINT_OUTPUT) - .composeString() - .startObject() - .startArrayField("objectArray") - .startObject() - .put("name", "name1") - .put("age", 11) - .end() - .startObject() - .put("name", "name2") - .put("age", 12) - .end() - .end() - .startArrayField("array") - .add(1) - .add(2) - .add(3) - .end() - .startObjectField("object") - .put("name", "name3") - .put("age", 13) - .end() - .put("last", true) - .end() - .finish(); - } - - public static String objectSerialization(Person person) throws IOException { - return JSON.std - .with(JSON.Feature.PRETTY_PRINT_OUTPUT) - .asString(person); - } - - public static String objectAnnotationSerialization(Person person) throws IOException { - return JSON.builder() - .register(JacksonAnnotationExtension.std) - .build() - .with(JSON.Feature.PRETTY_PRINT_OUTPUT) - .asString(person); - } - - public static String customObjectSerialization(Person person) throws IOException { - return JSON.builder() - .register(new JacksonJrExtension() { - @Override - protected void register (ExtensionContext extensionContext) { - extensionContext.insertProvider(new MyHandlerProvider()); - } - }) - .build() - .with(JSON.Feature.PRETTY_PRINT_OUTPUT) - .asString(person); - } - - public static Person objectDeserialization(String json) throws IOException { - return JSON.std - .with(JSON.Feature.PRETTY_PRINT_OUTPUT) - .beanFrom(Person.class, json); - } - - public static Person customObjectDeserialization(String json) throws IOException { - return JSON.builder() - .register(new JacksonJrExtension() { - @Override - protected void register (ExtensionContext extensionContext) { - extensionContext.insertProvider(new MyHandlerProvider()); - } - }) - .build() - .with(JSON.Feature.PRETTY_PRINT_OUTPUT) - .beanFrom(Person.class, json); - } -} diff --git a/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/defaultvalues/JsonSetterDefaultValue.java b/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/defaultvalues/SetterDefaultValue.java similarity index 82% rename from jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/defaultvalues/JsonSetterDefaultValue.java rename to jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/defaultvalues/SetterDefaultValue.java index 5d8c758e86..e1e0c9332c 100644 --- a/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/defaultvalues/JsonSetterDefaultValue.java +++ b/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/defaultvalues/SetterDefaultValue.java @@ -1,13 +1,10 @@ package com.baeldung.jackson.defaultvalues; -import com.fasterxml.jackson.annotation.JsonSetter; - -public class JsonSetterDefaultValue { +public class SetterDefaultValue { private String required; private String optional = "valueIfMissingEntirely"; - @JsonSetter("optional") public void setOptional(String optional){ if(optional == null){ this.optional = "valueIfNull"; diff --git a/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/defaultvalues/DefaultValuesUnitTest.java b/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/defaultvalues/DefaultValuesUnitTest.java index 813cfaae16..a7d41be764 100644 --- a/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/defaultvalues/DefaultValuesUnitTest.java +++ b/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/defaultvalues/DefaultValuesUnitTest.java @@ -17,10 +17,10 @@ public class DefaultValuesUnitTest { } @Test - public void givenAClassWithAJsonSetter_whenReadingJsonWithNullOptionalValue_thenExpectDefaultValueInResult() throws JsonProcessingException { + public void givenAClassWithASetter_whenReadingJsonWithNullOptionalValue_thenExpectDefaultValueInResult() throws JsonProcessingException { String nullOptionalField = "{\"required\": \"value\", \"optional\": null}"; ObjectMapper objectMapper = new ObjectMapper(); - JsonSetterDefaultValue createdObject = objectMapper.readValue(nullOptionalField, JsonSetterDefaultValue.class); + SetterDefaultValue createdObject = objectMapper.readValue(nullOptionalField, SetterDefaultValue.class); assert(createdObject.getRequired()).equals("value"); assert(createdObject.getOptional()).equals("valueIfNull"); } diff --git a/jackson-jr/pom.xml b/jackson-modules/jackson-jr/pom.xml similarity index 79% rename from jackson-jr/pom.xml rename to jackson-modules/jackson-jr/pom.xml index 0dcb62fdae..7f806f0d89 100644 --- a/jackson-jr/pom.xml +++ b/jackson-modules/jackson-jr/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-java + jackson-modules 0.0.1-SNAPSHOT - ../parent-java @@ -35,4 +34,14 @@ + + jackson-jr + + + src/main/resources + true + + + + \ No newline at end of file diff --git a/jackson-jr/src/main/java/com/baeldung/jacksonjr/CustomDateDeserializer.java b/jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/CustomDateDeserializer.java similarity index 81% rename from jackson-jr/src/main/java/com/baeldung/jacksonjr/CustomDateDeserializer.java rename to jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/CustomDateDeserializer.java index df977de966..3edaee8be0 100644 --- a/jackson-jr/src/main/java/com/baeldung/jacksonjr/CustomDateDeserializer.java +++ b/jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/CustomDateDeserializer.java @@ -1,22 +1,22 @@ package com.baeldung.jacksonjr; -import com.fasterxml.jackson.jr.ob.api.ValueReader; -import com.fasterxml.jackson.jr.ob.impl.JSONReader; -import com.fasterxml.jackson.jr.private_.JsonParser; - import java.io.IOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; +import com.fasterxml.jackson.jr.ob.api.ValueReader; +import com.fasterxml.jackson.jr.ob.impl.JSONReader; +import com.fasterxml.jackson.jr.private_.JsonParser; + public class CustomDateDeserializer extends ValueReader { private final static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - public CustomDateDeserializer () { + public CustomDateDeserializer() { super(LocalDate.class); } @Override - public Object read (JSONReader jsonReader, JsonParser jsonParser) throws IOException { + public Object read(JSONReader jsonReader, JsonParser jsonParser) throws IOException { return LocalDate.parse(jsonParser.getText(), dtf); } } diff --git a/jackson-jr/src/main/java/com/baeldung/jacksonjr/CustomDateSerializer.java b/jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/CustomDateSerializer.java similarity index 74% rename from jackson-jr/src/main/java/com/baeldung/jacksonjr/CustomDateSerializer.java rename to jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/CustomDateSerializer.java index 9b2596cd2c..cfd08548c6 100644 --- a/jackson-jr/src/main/java/com/baeldung/jacksonjr/CustomDateSerializer.java +++ b/jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/CustomDateSerializer.java @@ -1,20 +1,20 @@ package com.baeldung.jacksonjr; +import java.io.IOException; +import java.time.LocalDate; + import com.fasterxml.jackson.jr.ob.api.ValueWriter; import com.fasterxml.jackson.jr.ob.impl.JSONWriter; import com.fasterxml.jackson.jr.private_.JsonGenerator; -import java.io.IOException; -import java.time.LocalDate; - public class CustomDateSerializer implements ValueWriter { @Override - public void writeValue (JSONWriter jsonWriter, JsonGenerator jsonGenerator, Object o) throws IOException { + public void writeValue(JSONWriter jsonWriter, JsonGenerator jsonGenerator, Object o) throws IOException { jsonGenerator.writeString(o.toString()); } @Override - public Class valueType () { + public Class valueType() { return LocalDate.class; } } diff --git a/jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/JacksonJrFeatures.java b/jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/JacksonJrFeatures.java new file mode 100644 index 0000000000..6e99638ca6 --- /dev/null +++ b/jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/JacksonJrFeatures.java @@ -0,0 +1,92 @@ +package com.baeldung.jacksonjr; + +import java.io.IOException; +import java.util.LinkedHashMap; + +import com.fasterxml.jackson.jr.annotationsupport.JacksonAnnotationExtension; +import com.fasterxml.jackson.jr.ob.JSON; +import com.fasterxml.jackson.jr.ob.JacksonJrExtension; +import com.fasterxml.jackson.jr.ob.api.ExtensionContext; + +public class JacksonJrFeatures { + + public static String jsonObject() throws IOException { + return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT) + .asString(new LinkedHashMap() {{ + put("name", "John Doe"); + put("age", 30); + }}); + } + + public static String jsonComposer() throws IOException { + return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT) + .composeString() + .startObject() + .startArrayField("objectArray") + .startObject() + .put("name", "name1") + .put("age", 11) + .end() + .startObject() + .put("name", "name2") + .put("age", 12) + .end() + .end() + .startArrayField("array") + .add(1) + .add(2) + .add(3) + .end() + .startObjectField("object") + .put("name", "name3") + .put("age", 13) + .end() + .put("last", true) + .end() + .finish(); + } + + public static String objectSerialization(Person person) throws IOException { + return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT) + .asString(person); + } + + public static String objectAnnotationSerialization(Person person) throws IOException { + return JSON.builder() + .register(JacksonAnnotationExtension.std) + .build() + .with(JSON.Feature.PRETTY_PRINT_OUTPUT) + .asString(person); + } + + public static String customObjectSerialization(Person person) throws IOException { + return JSON.builder() + .register(new JacksonJrExtension() { + @Override + protected void register(ExtensionContext extensionContext) { + extensionContext.insertProvider(new MyHandlerProvider()); + } + }) + .build() + .with(JSON.Feature.PRETTY_PRINT_OUTPUT) + .asString(person); + } + + public static Person objectDeserialization(String json) throws IOException { + return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT) + .beanFrom(Person.class, json); + } + + public static Person customObjectDeserialization(String json) throws IOException { + return JSON.builder() + .register(new JacksonJrExtension() { + @Override + protected void register(ExtensionContext extensionContext) { + extensionContext.insertProvider(new MyHandlerProvider()); + } + }) + .build() + .with(JSON.Feature.PRETTY_PRINT_OUTPUT) + .beanFrom(Person.class, json); + } +} diff --git a/jackson-jr/src/main/java/com/baeldung/jacksonjr/MyHandlerProvider.java b/jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/MyHandlerProvider.java similarity index 82% rename from jackson-jr/src/main/java/com/baeldung/jacksonjr/MyHandlerProvider.java rename to jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/MyHandlerProvider.java index 266a09eecc..8fc67c6591 100644 --- a/jackson-jr/src/main/java/com/baeldung/jacksonjr/MyHandlerProvider.java +++ b/jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/MyHandlerProvider.java @@ -1,17 +1,17 @@ package com.baeldung.jacksonjr; +import java.time.LocalDate; + import com.fasterxml.jackson.jr.ob.api.ReaderWriterProvider; import com.fasterxml.jackson.jr.ob.api.ValueReader; import com.fasterxml.jackson.jr.ob.api.ValueWriter; import com.fasterxml.jackson.jr.ob.impl.JSONReader; import com.fasterxml.jackson.jr.ob.impl.JSONWriter; -import java.time.LocalDate; - public class MyHandlerProvider extends ReaderWriterProvider { @Override - public ValueWriter findValueWriter (JSONWriter writeContext, Class type) { + public ValueWriter findValueWriter(JSONWriter writeContext, Class type) { if (type == LocalDate.class) { return new CustomDateSerializer(); } @@ -19,7 +19,7 @@ public class MyHandlerProvider extends ReaderWriterProvider { } @Override - public ValueReader findValueReader (JSONReader readContext, Class type) { + public ValueReader findValueReader(JSONReader readContext, Class type) { if (type.equals(LocalDate.class)) { return new CustomDateDeserializer(); } diff --git a/jackson-jr/src/main/java/com/baeldung/jacksonjr/Person.java b/jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/Person.java similarity index 88% rename from jackson-jr/src/main/java/com/baeldung/jacksonjr/Person.java rename to jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/Person.java index 8effc64cd9..12c48c3270 100644 --- a/jackson-jr/src/main/java/com/baeldung/jacksonjr/Person.java +++ b/jackson-modules/jackson-jr/src/main/java/com/baeldung/jacksonjr/Person.java @@ -1,13 +1,13 @@ package com.baeldung.jacksonjr; -import com.fasterxml.jackson.annotation.JsonFormat; +import java.time.LocalDate; + import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import java.time.LocalDate; - @Data @NoArgsConstructor @AllArgsConstructor diff --git a/jackson-jr/src/test/java/com/baeldung/jacksonjr/JacksonJrFeaturesUnitTest.java b/jackson-modules/jackson-jr/src/test/java/com/baeldung/jacksonjr/JacksonJrFeaturesUnitTest.java similarity index 92% rename from jackson-jr/src/test/java/com/baeldung/jacksonjr/JacksonJrFeaturesUnitTest.java rename to jackson-modules/jackson-jr/src/test/java/com/baeldung/jacksonjr/JacksonJrFeaturesUnitTest.java index db17d2e175..04719c9303 100644 --- a/jackson-jr/src/test/java/com/baeldung/jacksonjr/JacksonJrFeaturesUnitTest.java +++ b/jackson-modules/jackson-jr/src/test/java/com/baeldung/jacksonjr/JacksonJrFeaturesUnitTest.java @@ -1,11 +1,13 @@ package com.baeldung.jacksonjr; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.time.LocalDate; -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class JacksonJrFeaturesUnitTest { diff --git a/jackson-modules/pom.xml b/jackson-modules/pom.xml index 531d5628f7..1f4a22e379 100644 --- a/jackson-modules/pom.xml +++ b/jackson-modules/pom.xml @@ -21,6 +21,7 @@ jackson-core jackson-custom-conversions jackson-exceptions + jackson-jr diff --git a/jeromq/pom.xml b/jeromq/pom.xml new file mode 100644 index 0000000000..dfb5086683 --- /dev/null +++ b/jeromq/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + jeromq + 0.0.1-SNAPSHOT + jeromq + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.zeromq + jeromq + 0.5.3 + + + org.junit.platform + junit-platform-engine + ${junit-platform.version} + test + + + org.junit.platform + junit-platform-console-standalone + ${junit-platform.version} + test + + + org.junit.jupiter + junit-jupiter-migrationsupport + ${junit-jupiter.version} + test + + + + + + + src/main/resources + true + + + src/test/resources + true + + + + + + + diff --git a/jeromq/src/test/java/com/baeldung/jeromq/DealerRouterLiveTest.java b/jeromq/src/test/java/com/baeldung/jeromq/DealerRouterLiveTest.java new file mode 100644 index 0000000000..1f2eff1325 --- /dev/null +++ b/jeromq/src/test/java/com/baeldung/jeromq/DealerRouterLiveTest.java @@ -0,0 +1,256 @@ +package com.baeldung.jeromq; + +import org.junit.jupiter.api.Test; +import org.zeromq.SocketType; +import org.zeromq.ZContext; +import org.zeromq.ZMQ; + +import java.util.Random; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class DealerRouterLiveTest { + @Test + public void single() throws Exception { + Thread brokerThread = new Thread(() -> { + try (ZContext context = new ZContext()) { + + ZMQ.Socket broker = context.createSocket(SocketType.ROUTER); + broker.bind("tcp://*:5555"); + + String identity = broker.recvStr(); + System.out.println(Thread.currentThread().getName() + " - Received identity " + identity); + + broker.recv(0); // Envelope delimiter + System.out.println(Thread.currentThread().getName() + " - Received envelope"); + String message = broker.recvStr(0); // Response from worker + System.out.println(Thread.currentThread().getName() + " - Received message " + message); + + broker.sendMore(identity); + broker.sendMore("xxx"); + broker.send("Hello back"); + } + }); + brokerThread.setName("broker"); + + Thread workerThread = new Thread(() -> { + try (ZContext context = new ZContext()) { + ZMQ.Socket worker = context.createSocket(SocketType.DEALER); + worker.setIdentity(Thread.currentThread().getName().getBytes(ZMQ.CHARSET)); + + worker.connect("tcp://localhost:5555"); + System.out.println(Thread.currentThread().getName() + " - Connected"); + + worker.sendMore(""); + worker.send("Hello " + Thread.currentThread().getName()); + System.out.println(Thread.currentThread().getName() + " - Sent Hello"); + + worker.recvStr(); // Envelope delimiter + System.out.println(Thread.currentThread().getName() + " - Received Envelope"); + String workload = worker.recvStr(); + System.out.println(Thread.currentThread().getName() + " - Received " + workload); + } + }); + workerThread.setName("worker"); + + brokerThread.start(); + workerThread.start(); + + workerThread.join(); + brokerThread.join(); + } + + @Test + public void asynchronous() throws Exception { + Thread brokerThread = new Thread(() -> { + try (ZContext context = new ZContext()) { + + ZMQ.Socket broker = context.createSocket(SocketType.ROUTER); + broker.bind("tcp://*:5555"); + + while (true) { + String identity = broker.recvStr(ZMQ.DONTWAIT); + System.out.println(Thread.currentThread().getName() + " - Received identity " + identity); + + if (identity == null) { + try { + Thread.sleep(100); + } catch (InterruptedException e) {} + } else { + + broker.recv(0); // Envelope delimiter + System.out.println(Thread.currentThread().getName() + " - Received envelope"); + String message = broker.recvStr(0); // Response from worker + System.out.println(Thread.currentThread().getName() + " - Received message " + message); + + broker.sendMore(identity); + broker.sendMore("xxx"); + broker.send("Hello back"); + + break; + } + } + } + }); + brokerThread.setName("broker"); + + Thread workerThread = new Thread(() -> { + try (ZContext context = new ZContext()) { + ZMQ.Socket worker = context.createSocket(SocketType.DEALER); + worker.setIdentity(Thread.currentThread().getName().getBytes(ZMQ.CHARSET)); + + worker.connect("tcp://localhost:5555"); + System.out.println(Thread.currentThread().getName() + " - Connected"); + + worker.sendMore(""); + worker.send("Hello " + Thread.currentThread().getName()); + System.out.println(Thread.currentThread().getName() + " - Sent Hello"); + + worker.recvStr(); // Envelope delimiter + System.out.println(Thread.currentThread().getName() + " - Received Envelope"); + String workload = worker.recvStr(); + System.out.println(Thread.currentThread().getName() + " - Received " + workload); + } + }); + workerThread.setName("worker"); + + brokerThread.start(); + workerThread.start(); + + workerThread.join(); + brokerThread.join(); + } + + + @Test + public void many() throws Exception { + Thread brokerThread = new Thread(() -> { + try (ZContext context = new ZContext()) { + + ZMQ.Socket broker = context.createSocket(SocketType.ROUTER); + broker.bind("tcp://*:5555"); + + while (!Thread.currentThread().isInterrupted()) { + String identity = broker.recvStr(); + System.out.println(Thread.currentThread().getName() + " - Received identity " + identity); + + broker.recv(0); // Envelope delimiter + String message = broker.recvStr(0); // Response from worker + System.out.println(Thread.currentThread().getName() + " - Received message " + message); + + broker.sendMore(identity); + broker.sendMore(""); + broker.send("Hello back to " + identity); + } + } + }); + brokerThread.setName("broker"); + + Set workers = IntStream.range(0, 10) + .mapToObj(index -> { + Thread workerThread = new Thread(() -> { + try (ZContext context = new ZContext()) { + ZMQ.Socket worker = context.createSocket(SocketType.DEALER); + worker.setIdentity(Thread.currentThread().getName().getBytes(ZMQ.CHARSET)); + + worker.connect("tcp://localhost:5555"); + System.out.println(Thread.currentThread().getName() + " - Connected"); + + worker.sendMore(""); + worker.send("Hello " + Thread.currentThread().getName()); + System.out.println(Thread.currentThread().getName() + " - Sent Hello"); + + worker.recvStr(); // Envelope delimiter + String workload = worker.recvStr(); + System.out.println(Thread.currentThread().getName() + " - Received " + workload); + } + }); + workerThread.setName("worker-" + index); + + return workerThread; + }) + .collect(Collectors.toSet()); + + brokerThread.start(); + workers.forEach(Thread::start); + + for (Thread worker : workers) { + worker.join(); + } + brokerThread.interrupt(); + } + + @Test + public void threaded() throws Exception { + Thread brokerThread = new Thread(() -> { + try (ZContext context = new ZContext()) { + + ZMQ.Socket broker = context.createSocket(SocketType.ROUTER); + broker.bind("tcp://*:5555"); + + ExecutorService threadPool = Executors.newFixedThreadPool(5); + Random rng = new Random(); + + while (!Thread.currentThread().isInterrupted()) { + String identity = broker.recvStr(); + System.out.println(Thread.currentThread().getName() + " - Received identity " + identity); + + broker.recv(0); // Envelope delimiter + String message = broker.recvStr(0); // Response from worker + System.out.println(Thread.currentThread().getName() + " - Received message " + message); + + threadPool.submit(() -> { + try { + Thread.sleep(rng.nextInt(1000) + 1000 ); + } catch (Exception e) {} + + synchronized(broker) { + broker.sendMore(identity); + broker.sendMore(""); + broker.send("Hello back to " + identity + " from " + Thread.currentThread().getName()); + } + }); + } + + threadPool.shutdown(); + } + }); + brokerThread.setName("broker"); + + Set workers = IntStream.range(0, 10) + .mapToObj(index -> { + Thread workerThread = new Thread(() -> { + try (ZContext context = new ZContext()) { + ZMQ.Socket worker = context.createSocket(SocketType.DEALER); + worker.setIdentity(Thread.currentThread().getName().getBytes(ZMQ.CHARSET)); + + worker.connect("tcp://localhost:5555"); + System.out.println(Thread.currentThread().getName() + " - Connected"); + + worker.sendMore(""); + worker.send("Hello " + Thread.currentThread().getName()); + System.out.println(Thread.currentThread().getName() + " - Sent Hello"); + + worker.recvStr(); // Envelope delimiter + String workload = worker.recvStr(); + System.out.println(Thread.currentThread().getName() + " - Received " + workload); + } + }); + workerThread.setName("worker-" + index); + + return workerThread; + }) + .collect(Collectors.toSet()); + + brokerThread.start(); + workers.forEach(Thread::start); + + for (Thread worker : workers) { + worker.join(); + } + brokerThread.interrupt(); + } +} diff --git a/jeromq/src/test/java/com/baeldung/jeromq/PubSubLiveTest.java b/jeromq/src/test/java/com/baeldung/jeromq/PubSubLiveTest.java new file mode 100644 index 0000000000..44699646b5 --- /dev/null +++ b/jeromq/src/test/java/com/baeldung/jeromq/PubSubLiveTest.java @@ -0,0 +1,101 @@ +package com.baeldung.jeromq; + +import org.junit.jupiter.api.Test; +import org.zeromq.SocketType; +import org.zeromq.ZContext; +import org.zeromq.ZMQ; + +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class PubSubLiveTest { + @Test + public void singleSub() throws Exception { + Thread server = new Thread(() -> { + try (ZContext context = new ZContext()) { + ZMQ.Socket pub = context.createSocket(SocketType.PUB); + pub.bind("tcp://*:5555"); + + try { + Thread.sleep(3000); + } catch (InterruptedException e) {} + + System.out.println(Thread.currentThread().getName() + " - Sending"); + pub.send("Hello"); + } + }); + server.setName("server"); + + Thread client = new Thread(() -> { + try (ZContext context = new ZContext()) { + ZMQ.Socket sub = context.createSocket(SocketType.SUB); + sub.connect("tcp://localhost:5555"); + System.out.println(Thread.currentThread().getName() + " - Connected"); + + sub.subscribe("".getBytes()); + System.out.println(Thread.currentThread().getName() + " - Subscribed"); + + String message = sub.recvStr(); + System.out.println(Thread.currentThread().getName() + " - " + message); + } + }); + client.setName("client"); + + server.start(); + client.start(); + + client.join(); + server.join(); + } + + + @Test + public void manySub() throws Exception { + Thread server = new Thread(() -> { + try (ZContext context = new ZContext()) { + ZMQ.Socket pub = context.createSocket(SocketType.PUB); + pub.bind("tcp://*:5555"); + + try { + Thread.sleep(3000); + } catch (InterruptedException e) {} + + System.out.println(Thread.currentThread().getName() + " - Sending"); + pub.send("Hello"); + } + }); + server.setName("server"); + + Set clients = IntStream.range(0, 10) + .mapToObj(index -> { + Thread client = new Thread(() -> { + try (ZContext context = new ZContext()) { + ZMQ.Socket sub = context.createSocket(SocketType.SUB); + sub.connect("tcp://localhost:5555"); + System.out.println(Thread.currentThread().getName() + " - Connected"); + + sub.subscribe("".getBytes()); + System.out.println(Thread.currentThread().getName() + " - Subscribed"); + + String message = sub.recvStr(); + System.out.println(Thread.currentThread().getName() + " - " + message); + } + }); + client.setName("client-" + index); + + return client; + }) + .collect(Collectors.toSet()); + + + server.start(); + clients.forEach(Thread::start); + + for (Thread client : clients) { + client.join(); + } + + server.join(); + } +} diff --git a/jeromq/src/test/java/com/baeldung/jeromq/RequestResponseLiveTest.java b/jeromq/src/test/java/com/baeldung/jeromq/RequestResponseLiveTest.java new file mode 100644 index 0000000000..8c0728e446 --- /dev/null +++ b/jeromq/src/test/java/com/baeldung/jeromq/RequestResponseLiveTest.java @@ -0,0 +1,96 @@ +package com.baeldung.jeromq; + +import org.junit.jupiter.api.Test; +import org.zeromq.SocketType; +import org.zeromq.ZContext; +import org.zeromq.ZMQ; + +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class RequestResponseLiveTest { + @Test + public void requestResponse() throws Exception { + try (ZContext context = new ZContext()) { + Thread server = new Thread(() -> { + ZMQ.Socket socket = context.createSocket(SocketType.REP); + socket.bind("inproc://test"); + + while (!Thread.currentThread().isInterrupted()) { + byte[] reply = socket.recv(0); + System.out.println("Server Received " + ": [" + new String(reply, ZMQ.CHARSET) + "]"); + + String response = new String(reply, ZMQ.CHARSET) + ", world"; + socket.send(response.getBytes(ZMQ.CHARSET), 0); + } + }); + + Thread client = new Thread(() -> { + ZMQ.Socket socket = context.createSocket(SocketType.REQ); + socket.connect("inproc://test"); + + for (int requestNbr = 0; requestNbr != 10; requestNbr++) { + String request = "Hello " + requestNbr; + System.out.println("Sending " + request); + socket.send(request.getBytes(ZMQ.CHARSET), 0); + + byte[] reply = socket.recv(0); + System.out.println("Client Received " + new String(reply, ZMQ.CHARSET)); + } + + }); + + server.start(); + client.start(); + + client.join(); + server.interrupt(); + } + } + + @Test + public void manyRequestResponse() throws Exception { + try (ZContext context = new ZContext()) { + Thread server = new Thread(() -> { + ZMQ.Socket socket = context.createSocket(SocketType.REP); + socket.bind("tcp://*:5555"); + + while (!Thread.currentThread().isInterrupted()) { + byte[] reply = socket.recv(0); + System.out.println("Server Received " + ": [" + new String(reply, ZMQ.CHARSET) + "]"); + + String response = new String(reply, ZMQ.CHARSET) + ", world"; + socket.send(response.getBytes(ZMQ.CHARSET), 0); + } + }); + + Set clients = IntStream.range(0, 10).mapToObj(index -> + new Thread(() -> { + ZMQ.Socket socket = context.createSocket(SocketType.REQ); + socket.connect("tcp://localhost:5555"); + + for (int requestNbr = 0; requestNbr != 10; requestNbr++) { + String request = "Hello " + index + " - " + requestNbr; + System.out.println("Sending " + request); + socket.send(request.getBytes(ZMQ.CHARSET), 0); + + byte[] reply = socket.recv(0); + System.out.println("Client " + index + " Received " + new String(reply, ZMQ.CHARSET)); + } + + }) + ).collect(Collectors.toSet()); + + server.start(); + clients.forEach(Thread::start); + + for (Thread client : clients) { + client.join(); + } + + server.interrupt(); + } + + } +} diff --git a/json-modules/gson-2/src/test/java/com/baeldung/gson/exposevsserializedname/PersonSerializerUnitTest.java b/json-modules/gson-2/src/test/java/com/baeldung/gson/exposevsserializedname/PersonSerializerUnitTest.java index 007b34c032..11cf33937d 100644 --- a/json-modules/gson-2/src/test/java/com/baeldung/gson/exposevsserializedname/PersonSerializerUnitTest.java +++ b/json-modules/gson-2/src/test/java/com/baeldung/gson/exposevsserializedname/PersonSerializerUnitTest.java @@ -33,7 +33,7 @@ public class PersonSerializerUnitTest { } @Test - public void WhenUseCustomGson_ThenDonotSerializeAccountNumAndPassword () { + public void whenUseCustomGson_thenDonotSerializeAccountNumAndPassword () { String personJson = PersonSerializer.serializeWithConfiguredGson(person); logger.info(personJson); @@ -42,7 +42,7 @@ public class PersonSerializerUnitTest { } @Test - public void WhenUseDefaultGson_ThenSerializeAccountNumAndPassword () { + public void whenUseDefaultGson_thenSerializeAccountNumAndPassword () { String personJson = PersonSerializer.serializeWithDefaultGson(person); logger.info(personJson); @@ -51,7 +51,7 @@ public class PersonSerializerUnitTest { } @Test - public void whenUseSerializedAnnotation_ThenUseSerializedNameinJsonString() { + public void whenUseSerializedAnnotation_thenUseSerializedNameinJsonString() { String countryJson = PersonSerializer.toJsonString(country); logger.info(countryJson); assertFalse("Test failed: No change in the keys", countryJson.contains("countryName")); @@ -64,7 +64,7 @@ public class PersonSerializerUnitTest { } @Test - public void whenJsonStrCreatedWithCustomKeys_ThenCreateObjUsingGson() { + public void whenJsonStrCreatedWithCustomKeys_thenCreateObjUsingGson() { String countryJson = PersonSerializer.toJsonString(country); Country country = PersonSerializer.fromJsonString(countryJson); logger.info(country.toString()); diff --git a/json-modules/json-2/README.md b/json-modules/json-2/README.md index bf2cb06aba..adf55c3618 100644 --- a/json-modules/json-2/README.md +++ b/json-modules/json-2/README.md @@ -11,5 +11,6 @@ This module contains articles about JSON. - [A Guide to FastJson](https://www.baeldung.com/fastjson) - [Check Whether a String Is Valid JSON in Java](https://www.baeldung.com/java-validate-json-string) - [Getting a Value in JSONObject](https://www.baeldung.com/java-jsonobject-get-value) +- [Pretty-Print a JSON in Java](https://www.baeldung.com/java-json-pretty-print) - More Articles: [[<-- prev]](/json-modules/json) diff --git a/json-modules/json-2/src/main/java/com/baeldung/jsonprettyprinter/JsonPrettyPrinter.java b/json-modules/json-2/src/main/java/com/baeldung/jsonprettyprinter/JsonPrettyPrinter.java new file mode 100644 index 0000000000..85bd3197d6 --- /dev/null +++ b/json-modules/json-2/src/main/java/com/baeldung/jsonprettyprinter/JsonPrettyPrinter.java @@ -0,0 +1,34 @@ +package com.baeldung.jsonprettyprinter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + + +/* + * Class to print string JSON to well-formatted JSON using Jackson and Gson. + */ +public class JsonPrettyPrinter { + private ObjectMapper mapper = new ObjectMapper(); + + public String prettyPrintJsonUsingDefaultPrettyPrinter(String uglyJsonString) throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + Object jsonObject = objectMapper.readValue(uglyJsonString, Object.class); + return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject); + } + + public String prettyPrintUsingGlobalSetting(String uglyJsonString) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); + Object jsonObject = mapper.readValue(uglyJsonString, Object.class); + return mapper.writeValueAsString(jsonObject); + } + + public String prettyPrintUsingGson(String uglyJsonString) { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + Object jsonObject = gson.fromJson(uglyJsonString, Object.class); + return gson.toJson(jsonObject); + } +} diff --git a/json-modules/json-2/src/test/java/com/baeldung/jsonprettyprinter/JsonPrettyPrinterUnitTest.java b/json-modules/json-2/src/test/java/com/baeldung/jsonprettyprinter/JsonPrettyPrinterUnitTest.java new file mode 100644 index 0000000000..245c2436a4 --- /dev/null +++ b/json-modules/json-2/src/test/java/com/baeldung/jsonprettyprinter/JsonPrettyPrinterUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.jsonprettyprinter; + +import com.fasterxml.jackson.core.JsonProcessingException; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class JsonPrettyPrinterUnitTest { + + private String uglyJsonString = "{\"one\":\"AAA\",\"two\":[\"BBB\",\"CCC\"],\"three\":{\"four\":\"DDD\",\"five\":[\"EEE\",\"FFF\"]}}"; + private JsonPrettyPrinter jsonPrettyPrinter = new JsonPrettyPrinter(); + + @Test + public void shouldPrettyPrintJsonStringUsingDefaultPrettyPrinter() throws JsonProcessingException { + String formattedJsonString = jsonPrettyPrinter.prettyPrintJsonUsingDefaultPrettyPrinter(uglyJsonString); + String expectedJson = "{\n" + + " \"one\" : \"AAA\",\n" + + " \"two\" : [ \"BBB\", \"CCC\" ],\n" + + " \"three\" : {\n" + + " \"four\" : \"DDD\",\n" + + " \"five\" : [ \"EEE\", \"FFF\" ]\n" + + " }\n" + + "}"; + System.out.println("Formatted String: " + formattedJsonString); + assertEquals(expectedJson, formattedJsonString); + } + + @Test + public void shouldPrettyPrintJsonStringUsingGlobalSetting() throws JsonProcessingException { + String formattedJsonString = jsonPrettyPrinter.prettyPrintUsingGlobalSetting(uglyJsonString); + String expectedJson = "{\n" + + " \"one\" : \"AAA\",\n" + + " \"two\" : [ \"BBB\", \"CCC\" ],\n" + + " \"three\" : {\n" + + " \"four\" : \"DDD\",\n" + + " \"five\" : [ \"EEE\", \"FFF\" ]\n" + + " }\n" + + "}"; + System.out.println("Formatted String: " + formattedJsonString); + assertEquals(expectedJson, formattedJsonString); + } + + @Test + public void shouldPrettyPrintJsonStringUsingGson() { + String formattedJsonString = jsonPrettyPrinter.prettyPrintUsingGson(uglyJsonString); + String expectedPrettyJson = "{\n" + + " \"one\": \"AAA\",\n" + + " \"two\": [\n" + + " \"BBB\",\n" + + " \"CCC\"\n" + + " ],\n" + + " \"three\": {\n" + + " \"four\": \"DDD\",\n" + + " \"five\": [\n" + + " \"EEE\",\n" + + " \"FFF\"\n" + + " ]\n" + + " }\n" + + "}"; + System.out.println("Formatted String: " + formattedJsonString); + assertEquals(expectedPrettyJson, formattedJsonString); + } +} diff --git a/microservices-modules/helidon/helidon-se/pom.xml b/microservices-modules/helidon/helidon-se/pom.xml index e26390a99d..a400cbe85e 100644 --- a/microservices-modules/helidon/helidon-se/pom.xml +++ b/microservices-modules/helidon/helidon-se/pom.xml @@ -28,13 +28,13 @@ io.helidon.webserver helidon-webserver-netty - ${helidon.version} + ${helidon-webserver-netty.version} runtime io.helidon.webserver helidon-webserver-json - ${helidon.version} + ${helidon-webserver-json.version} @@ -43,19 +43,26 @@ ${helidon.version} - io.helidon.security - helidon-security-provider-http-auth + io.helidon.security.providers + helidon-security-providers-http-auth ${helidon.version} - io.helidon.security + io.helidon.security.integration helidon-security-integration-webserver ${helidon.version} + + io.helidon.webserver + helidon-webserver-http2 + ${helidon.version} + - 0.10.4 + 3.2.2 + 0.10.6 + 0.11.0 \ No newline at end of file diff --git a/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/config/ConfigApplication.java b/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/config/ConfigApplication.java index beac5511c1..4ef0d5a8d2 100644 --- a/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/config/ConfigApplication.java +++ b/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/config/ConfigApplication.java @@ -6,7 +6,7 @@ import io.helidon.config.spi.ConfigSource; public class ConfigApplication { - public static void main(String... args) throws Exception { + public static void main(String... args) { ConfigSource configSource = ConfigSources.classpath("application.yaml").build(); Config config = Config.builder() @@ -15,10 +15,10 @@ public class ConfigApplication { .sources(configSource) .build(); - int port = config.get("server.port").asInt(); - int pageSize = config.get("web.page-size").asInt(); - boolean debug = config.get("web.debug").asBoolean(); - String userHome = config.get("user.home").asString(); + int port = config.get("server.port").asInt().get(); + int pageSize = config.get("web.page-size").asInt().get(); + boolean debug = config.get("web.debug").asBoolean().get(); + String userHome = config.get("user.home").asString().get(); System.out.println("port: " + port); System.out.println("pageSize: " + pageSize); diff --git a/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/BookResource.java b/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/BookResource.java index b0db191851..278bbfefcf 100644 --- a/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/BookResource.java +++ b/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/BookResource.java @@ -50,9 +50,7 @@ public class BookResource implements Service { private JsonArray from(List books) { JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder(); - books.forEach(book -> { - jsonArrayBuilder.add(from(book)); - }); + books.forEach(book -> jsonArrayBuilder.add(from(book))); return jsonArrayBuilder.build(); } } diff --git a/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/WebApplicationRouting.java b/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/WebApplicationRouting.java index 17bf2bcc8f..805afd5ecb 100644 --- a/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/WebApplicationRouting.java +++ b/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/WebApplicationRouting.java @@ -1,25 +1,21 @@ package com.baeldung.helidon.se.routing; import io.helidon.webserver.Routing; -import io.helidon.webserver.ServerConfiguration; import io.helidon.webserver.WebServer; import io.helidon.webserver.json.JsonSupport; public class WebApplicationRouting { - public static void main(String... args) throws Exception { - - ServerConfiguration serverConfig = ServerConfiguration.builder() - .port(9080) - .build(); + public static void main(String... args) { Routing routing = Routing.builder() - .register(JsonSupport.get()) + .register(JsonSupport.create()) .register("/books", new BookResource()) .get("/greet", (request, response) -> response.send("Hello World !")) .build(); - WebServer.create(serverConfig, routing) + WebServer.builder().port(9080).addRouting(routing) + .build() .start() .thenAccept(ws -> System.out.println("Server started at: http://localhost:" + ws.port()) diff --git a/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/MyUser.java b/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/MyUser.java index d1a8446f6a..0f7b536121 100644 --- a/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/MyUser.java +++ b/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/MyUser.java @@ -1,10 +1,11 @@ package com.baeldung.helidon.se.security; -import io.helidon.security.provider.httpauth.UserStore; +import io.helidon.security.providers.httpauth.SecureUserStore; +import java.util.Arrays; import java.util.Collection; -public class MyUser implements UserStore.User { +public class MyUser implements SecureUserStore.User { private String login; private char[] password; @@ -17,17 +18,17 @@ public class MyUser implements UserStore.User { } @Override - public String getLogin() { + public String login() { return login; } @Override - public char[] getPassword() { - return password; + public boolean isPasswordValid(char[] chars) { + return Arrays.equals(chars, password); } @Override - public Collection getRoles() { + public Collection roles() { return roles; } } diff --git a/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/WebApplicationSecurity.java b/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/WebApplicationSecurity.java index 4eb7c6c01f..a3429b20fe 100644 --- a/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/WebApplicationSecurity.java +++ b/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/WebApplicationSecurity.java @@ -3,30 +3,28 @@ package com.baeldung.helidon.se.security; import io.helidon.config.Config; import io.helidon.security.Security; import io.helidon.security.SubjectType; -import io.helidon.security.provider.httpauth.HttpBasicAuthProvider; -import io.helidon.security.provider.httpauth.UserStore; -import io.helidon.security.webserver.WebSecurity; +import io.helidon.security.integration.webserver.WebSecurity; +import io.helidon.security.providers.httpauth.HttpBasicAuthProvider; +import io.helidon.security.providers.httpauth.SecureUserStore; import io.helidon.webserver.Routing; -import io.helidon.webserver.ServerConfiguration; import io.helidon.webserver.WebServer; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class WebApplicationSecurity { - public static void main(String... args) throws Exception { + public static void main(String... args) { Config config = Config.create(); - ServerConfiguration serverConfig = - ServerConfiguration.fromConfig(config.get("server")); Map users = new HashMap<>(); - users.put("user", new MyUser("user", "user".toCharArray(), Arrays.asList("ROLE_USER"))); + users.put("user", new MyUser("user", "user".toCharArray(), Collections.singletonList("ROLE_USER"))); users.put("admin", new MyUser("admin", "admin".toCharArray(), Arrays.asList("ROLE_USER", "ROLE_ADMIN"))); - UserStore store = user -> Optional.ofNullable(users.get(user)); + SecureUserStore store = user -> Optional.ofNullable(users.get(user)); HttpBasicAuthProvider httpBasicAuthProvider = HttpBasicAuthProvider.builder() .realm("myRealm") @@ -38,13 +36,12 @@ public class WebApplicationSecurity { Security security = Security.builder() .addAuthenticationProvider(httpBasicAuthProvider) .build(); - //Security security = Security.fromConfig(config); + //Security security = Security.create(config); //2. WebSecurity from Security or from Config - // WebSecurity webSecurity = WebSecurity.from(security) - // .securityDefaults(WebSecurity.authenticate()); + // WebSecurity webSecurity = WebSecurity.create(security).securityDefaults(WebSecurity.authenticate()); - WebSecurity webSecurity = WebSecurity.from(config); + WebSecurity webSecurity = WebSecurity.create(config); Routing routing = Routing.builder() .register(webSecurity) @@ -52,7 +49,7 @@ public class WebApplicationSecurity { .get("/admin", (request, response) -> response.send("Hello, I'm a Helidon SE user with ROLE_ADMIN")) .build(); - WebServer webServer = WebServer.create(serverConfig, routing); + WebServer webServer = WebServer.create(routing, config.get("server")); webServer.start().thenAccept(ws -> System.out.println("Server started at: http://localhost:" + ws.port()) diff --git a/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/webserver/SimpleWebApplication.java b/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/webserver/SimpleWebApplication.java index a9a92cf1b9..c528c57782 100644 --- a/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/webserver/SimpleWebApplication.java +++ b/microservices-modules/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/webserver/SimpleWebApplication.java @@ -1,22 +1,18 @@ package com.baeldung.helidon.se.webserver; import io.helidon.webserver.Routing; -import io.helidon.webserver.ServerConfiguration; import io.helidon.webserver.WebServer; public class SimpleWebApplication { - public static void main(String... args) throws Exception { - - ServerConfiguration serverConfig = ServerConfiguration.builder() - .port(9001) - .build(); + public static void main(String... args) { Routing routing = Routing.builder() .get("/greet", (request, response) -> response.send("Hello World !")) .build(); - WebServer.create(serverConfig, routing) + WebServer.builder(routing) + .port(9001).addRouting(routing).build() .start() .thenAccept(ws -> System.out.println("Server started at: http://localhost:" + ws.port()) diff --git a/muleesb/src/test/resources/log4j2-test.xml b/muleesb/src/test/resources/log4j2-test.xml index 6351ae041c..771817a1bc 100644 --- a/muleesb/src/test/resources/log4j2-test.xml +++ b/muleesb/src/test/resources/log4j2-test.xml @@ -18,8 +18,8 @@ - - + + diff --git a/persistence-modules/deltaspike/src/test/resources/logback-test.xml b/persistence-modules/deltaspike/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..bdc292924b --- /dev/null +++ b/persistence-modules/deltaspike/src/test/resources/logback-test.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/README.md b/persistence-modules/hibernate-annotations/README.md index a03fb7e8e3..dad29edc32 100644 --- a/persistence-modules/hibernate-annotations/README.md +++ b/persistence-modules/hibernate-annotations/README.md @@ -11,3 +11,4 @@ This module contains articles about Annotations used in Hibernate. - [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) +- [Difference Between @JoinColumn and @PrimaryKeyJoinColumn in JPA](https://www.baeldung.com/java-jpa-join-vs-primarykeyjoin) diff --git a/persistence-modules/java-cassandra/src/test/resources/logback-test.xml b/persistence-modules/java-cassandra/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..d2c2764154 --- /dev/null +++ b/persistence-modules/java-cassandra/src/test/resources/logback-test.xml @@ -0,0 +1,17 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 9eb7ca1f1d..3569f83d7b 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -85,6 +85,7 @@ spring-data-jpa-query-3 spring-data-jpa-repo spring-data-jpa-repo-2 + spring-data-jpa-repo-4 spring-data-jdbc spring-data-keyvalue spring-data-mongodb diff --git a/persistence-modules/spring-boot-persistence-2/README.md b/persistence-modules/spring-boot-persistence-2/README.md index d7c13fd363..66c91ca3ed 100644 --- a/persistence-modules/spring-boot-persistence-2/README.md +++ b/persistence-modules/spring-boot-persistence-2/README.md @@ -7,4 +7,5 @@ - [Oracle Connection Pooling With Spring](https://www.baeldung.com/spring-oracle-connection-pooling) - [Object States in Hibernate’s Session](https://www.baeldung.com/hibernate-session-object-states) - [Storing Files Indexed by a Database](https://www.baeldung.com/java-db-storing-files) -- More articles: [[<-- prev]](../spring-boot-persistence) +- More articles: [[<-- prev]](../spring-boot-persistence) [[next -->]](../spring-boot-persistence-3) + diff --git a/persistence-modules/spring-boot-persistence-3/README.md b/persistence-modules/spring-boot-persistence-3/README.md index ba97a02a9d..34bbe10dc3 100644 --- a/persistence-modules/spring-boot-persistence-3/README.md +++ b/persistence-modules/spring-boot-persistence-3/README.md @@ -1,3 +1,5 @@ ### Relevant Articles: - [Patterns for Iterating Over Large Result Sets With Spring Data JPA](https://www.baeldung.com/spring-data-jpa-iterate-large-result-sets) +- [Count the Number of Rows in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-row-count) +- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source) - More articles: [[<-- prev]](../spring-boot-persistence-2) diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/ClientDao.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientDao.java similarity index 100% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/ClientDao.java rename to persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientDao.java diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/ClientDataSourceRouter.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientDataSourceRouter.java similarity index 100% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/ClientDataSourceRouter.java rename to persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientDataSourceRouter.java diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/ClientDatabase.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientDatabase.java similarity index 100% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/ClientDatabase.java rename to persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientDatabase.java diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/ClientDatabaseContextHolder.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientDatabaseContextHolder.java similarity index 100% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/ClientDatabaseContextHolder.java rename to persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientDatabaseContextHolder.java diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/ClientService.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientService.java similarity index 100% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/ClientService.java rename to persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientService.java diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/model/ClientADetails.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/model/ClientADetails.java similarity index 100% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/model/ClientADetails.java rename to persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/model/ClientADetails.java diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/model/ClientBDetails.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/model/ClientBDetails.java similarity index 100% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dsrouting/model/ClientBDetails.java rename to persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/model/ClientBDetails.java diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/dsrouting/DataSourceRoutingIntegrationTest.java similarity index 90% rename from persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java rename to persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/dsrouting/DataSourceRoutingIntegrationTest.java index 0430d9e3af..6359761120 100644 --- a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/dsrouting/DataSourceRoutingIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.dsrouting; +package com.baeldung.boot.dsrouting; import static org.junit.Assert.assertEquals; @@ -13,6 +13,10 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.dsrouting.ClientDatabase; +import com.baeldung.dsrouting.ClientDatabaseContextHolder; +import com.baeldung.dsrouting.ClientService; + @RunWith(SpringRunner.class) @ContextConfiguration(classes = DataSourceRoutingTestConfiguration.class) @DirtiesContext diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/dsrouting/DataSourceRoutingTestConfiguration.java similarity index 88% rename from persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java rename to persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/dsrouting/DataSourceRoutingTestConfiguration.java index 957114eba5..e7be8678de 100644 --- a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java +++ b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/dsrouting/DataSourceRoutingTestConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.dsrouting; +package com.baeldung.boot.dsrouting; import java.util.HashMap; import java.util.Map; @@ -10,6 +10,11 @@ import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import com.baeldung.dsrouting.ClientDao; +import com.baeldung.dsrouting.ClientDataSourceRouter; +import com.baeldung.dsrouting.ClientDatabase; +import com.baeldung.dsrouting.ClientService; + @Configuration public class DataSourceRoutingTestConfiguration { diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/dsrouting/SpringBootDataSourceRoutingIntegrationTest.java b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/dsrouting/SpringBootDataSourceRoutingIntegrationTest.java similarity index 92% rename from persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/dsrouting/SpringBootDataSourceRoutingIntegrationTest.java rename to persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/dsrouting/SpringBootDataSourceRoutingIntegrationTest.java index 75829c2153..4db411e283 100644 --- a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/dsrouting/SpringBootDataSourceRoutingIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/dsrouting/SpringBootDataSourceRoutingIntegrationTest.java @@ -1,9 +1,12 @@ -package com.baeldung.dsrouting; +package com.baeldung.boot.dsrouting; import static org.junit.Assert.assertEquals; import javax.sql.DataSource; +import com.baeldung.dsrouting.ClientDatabase; +import com.baeldung.dsrouting.ClientDatabaseContextHolder; +import com.baeldung.dsrouting.ClientService; import com.baeldung.dsrouting.model.ClientADetails; import com.baeldung.dsrouting.model.ClientBDetails; import org.junit.Before; diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/dsrouting/SpringBootDataSourceRoutingTestConfiguration.java b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/dsrouting/SpringBootDataSourceRoutingTestConfiguration.java similarity index 90% rename from persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/dsrouting/SpringBootDataSourceRoutingTestConfiguration.java rename to persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/dsrouting/SpringBootDataSourceRoutingTestConfiguration.java index 01f157998f..426dbbdb80 100644 --- a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/dsrouting/SpringBootDataSourceRoutingTestConfiguration.java +++ b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/dsrouting/SpringBootDataSourceRoutingTestConfiguration.java @@ -1,5 +1,9 @@ -package com.baeldung.dsrouting; +package com.baeldung.boot.dsrouting; +import com.baeldung.dsrouting.ClientDao; +import com.baeldung.dsrouting.ClientDataSourceRouter; +import com.baeldung.dsrouting.ClientDatabase; +import com.baeldung.dsrouting.ClientService; import com.baeldung.dsrouting.model.ClientADetails; import com.baeldung.dsrouting.model.ClientBDetails; import org.springframework.beans.factory.annotation.Autowired; diff --git a/persistence-modules/spring-boot-persistence-3/src/test/resources/application.properties b/persistence-modules/spring-boot-persistence-3/src/test/resources/application.properties new file mode 100644 index 0000000000..10bd344c28 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-3/src/test/resources/application.properties @@ -0,0 +1,13 @@ +# spring.datasource.x +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=sa + +#database details for CLIENT_A +client-a.datasource.name=CLIENT_A +client-a.datasource.script=dsrouting-db.sql + +#database details for CLIENT_B +client-b.datasource.name=CLIENT_B +client-b.datasource.script=dsrouting-db.sql \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/src/test/resources/dsrouting-db.sql b/persistence-modules/spring-boot-persistence-3/src/test/resources/dsrouting-db.sql similarity index 100% rename from persistence-modules/spring-boot-persistence/src/test/resources/dsrouting-db.sql rename to persistence-modules/spring-boot-persistence-3/src/test/resources/dsrouting-db.sql diff --git a/persistence-modules/spring-boot-persistence/README.md b/persistence-modules/spring-boot-persistence/README.md index 6bbc2b37ae..88526cdb89 100644 --- a/persistence-modules/spring-boot-persistence/README.md +++ b/persistence-modules/spring-boot-persistence/README.md @@ -7,5 +7,4 @@ - [Resolving “Failed to Configure a DataSource” Error](https://www.baeldung.com/spring-boot-failed-to-configure-data-source) - [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot) - [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate) -- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source) - More articles: [[more -->]](../spring-boot-persistence-2) diff --git a/persistence-modules/spring-boot-persistence/src/test/resources/application.properties b/persistence-modules/spring-boot-persistence/src/test/resources/application.properties index 9f6f3f60d2..45af449122 100644 --- a/persistence-modules/spring-boot-persistence/src/test/resources/application.properties +++ b/persistence-modules/spring-boot-persistence/src/test/resources/application.properties @@ -4,14 +4,6 @@ spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 spring.datasource.username=sa spring.datasource.password=sa -#database details for CLIENT_A -client-a.datasource.name=CLIENT_A -client-a.datasource.script=dsrouting-db.sql - -#database details for CLIENT_B -client-b.datasource.name=CLIENT_B -client-b.datasource.script=dsrouting-db.sql - # hibernate.X hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=true diff --git a/persistence-modules/spring-data-cassandra-reactive/src/test/resources/logback-test.xml b/persistence-modules/spring-data-cassandra-reactive/src/test/resources/logback-test.xml index 8d4771e308..1daccde00e 100644 --- a/persistence-modules/spring-data-cassandra-reactive/src/test/resources/logback-test.xml +++ b/persistence-modules/spring-data-cassandra-reactive/src/test/resources/logback-test.xml @@ -6,6 +6,10 @@ + + + + diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md index 12eeddae7f..23134ec02d 100644 --- a/persistence-modules/spring-data-jpa-repo-2/README.md +++ b/persistence-modules/spring-data-jpa-repo-2/README.md @@ -9,6 +9,4 @@ - [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) -- [TRUNCATE TABLE in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-truncate-table) - More articles: [[<-- prev]](../spring-data-jpa-repo) diff --git a/persistence-modules/spring-data-jpa-repo-4/README.md b/persistence-modules/spring-data-jpa-repo-4/README.md new file mode 100644 index 0000000000..a8afbbe733 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/README.md @@ -0,0 +1,7 @@ +## Spring Data JPA - Repositories + +### Relevant Articles: + +- [Unidirectional One-to-Many and Cascading Delete in JPA](https://www.baeldung.com/spring-jpa-unidirectional-one-to-many-and-cascading-delete) +- [TRUNCATE TABLE in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-truncate-table) +- More articles: [[<-- prev]](../spring-data-jpa-repo-3) diff --git a/persistence-modules/spring-data-jpa-repo-4/pom.xml b/persistence-modules/spring-data-jpa-repo-4/pom.xml new file mode 100644 index 0000000000..c823391d9f --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + spring-data-jpa-repo-4 + spring-data-jpa-repo-4 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + javax.persistence + javax.persistence-api + + + org.springframework.data + spring-data-jpa + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + com.querydsl + querydsl-apt + + + com.querydsl + querydsl-jpa + + + com.google.guava + guava + ${guava.version} + + + + + + + com.mysema.maven + apt-maven-plugin + 1.1.3 + + + generate-sources + + process + + + ${project.build.directory}/generated-sources + com.querydsl.apt.jpa.JPAAnnotationProcessor + + + + + + org.bsc.maven + maven-processor-plugin + 3.3.3 + + + process + + process + + generate-sources + + ${project.build.directory}/generated-sources + + org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor + + + + + + + org.hibernate + hibernate-jpamodelgen + 5.6.11.Final + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/EntityManagerRepository.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/truncate/EntityManagerRepository.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/EntityManagerRepository.java rename to persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/truncate/EntityManagerRepository.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/JdbcTemplateRepository.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/truncate/JdbcTemplateRepository.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/JdbcTemplateRepository.java rename to persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/truncate/JdbcTemplateRepository.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntity.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntity.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntity.java rename to persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntity.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntityRepository.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntityRepository.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntityRepository.java rename to persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntityRepository.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/TruncateSpringBootApplication.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/truncate/TruncateSpringBootApplication.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/TruncateSpringBootApplication.java rename to persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/truncate/TruncateSpringBootApplication.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Article.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Article.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Article.java rename to persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Article.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleRepository.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleRepository.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleRepository.java rename to persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleRepository.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleService.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleService.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleService.java rename to persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleService.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CascadingDeleteApplication.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CascadingDeleteApplication.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CascadingDeleteApplication.java rename to persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CascadingDeleteApplication.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Comment.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Comment.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Comment.java rename to persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Comment.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CommentRepository.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CommentRepository.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CommentRepository.java rename to persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CommentRepository.java diff --git a/persistence-modules/spring-data-jpa-repo-4/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-repo-4/src/main/resources/application.properties new file mode 100644 index 0000000000..db4837d8d2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/src/main/resources/application.properties @@ -0,0 +1,11 @@ +spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +spring.datasource.username=sa +spring.datasource.password=sa + +spring.jpa.properties.hibernate.globally_quoted_identifiers=true +logging.level.com.baeldung.spring.data.persistence.search=debug + +spring.jpa.show-sql=true +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE +spring.jpa.properties.hibernate.format_sql=true diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/deletionCascading/ArticleRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/deletionCascading/ArticleRepositoryIntegrationTest.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/deletionCascading/ArticleRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/deletionCascading/ArticleRepositoryIntegrationTest.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/truncate/TruncateIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/truncate/TruncateIntegrationTest.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/truncate/TruncateIntegrationTest.java rename to persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/truncate/TruncateIntegrationTest.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/test/resources/logback-test.xml b/persistence-modules/spring-data-jpa-repo-4/src/test/resources/logback-test.xml similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/test/resources/logback-test.xml rename to persistence-modules/spring-data-jpa-repo-4/src/test/resources/logback-test.xml diff --git a/persistence-modules/spring-data-yugabytedb/README.md b/persistence-modules/spring-data-yugabytedb/README.md new file mode 100644 index 0000000000..a6e7ec0fd5 --- /dev/null +++ b/persistence-modules/spring-data-yugabytedb/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Quick Guide to YugabyteDB](https://www.baeldung.com/yugabytedb) diff --git a/pom.xml b/pom.xml index a82f898689..73bf48b195 100644 --- a/pom.xml +++ b/pom.xml @@ -369,6 +369,7 @@ persistence-modules/spring-data-cassandra-reactive persistence-modules/spring-data-neo4j java-nashorn + jeromq @@ -703,6 +704,7 @@ osgi spring-katharsis logging-modules + spring-boot-documentation spring-boot-modules apache-httpclient apache-httpclient4 @@ -778,7 +780,6 @@ custom-pmd data-structures ddd-contexts - jackson-jr jackson-modules jmh deeplearning4j @@ -974,6 +975,7 @@ osgi spring-katharsis logging-modules + spring-boot-documentation spring-boot-modules apache-httpclient apache-httpclient4 diff --git a/security-modules/pom.xml b/security-modules/pom.xml index b779c0d46d..08e0315698 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-aop-2/pom.xml b/spring-aop-2/pom.xml index e4748cdcbf..056e248a3c 100644 --- a/spring-aop-2/pom.xml +++ b/spring-aop-2/pom.xml @@ -51,8 +51,4 @@ - - 1.14.0 - - \ No newline at end of file diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml index 810ddcdcdd..7d9becf089 100644 --- a/spring-batch/pom.xml +++ b/spring-batch/pom.xml @@ -25,7 +25,7 @@ jakarta.xml.bind jakarta.xml.bind-api - 4.0.0 + ${jakarta.xml.bind-api} org.glassfish.jaxb @@ -75,6 +75,7 @@ 6.0.6 5.7.1 + 4.0.0 4.0.2 2.14.2 4.5.14 diff --git a/spring-boot-documentation/README.md b/spring-boot-documentation/README.md new file mode 100644 index 0000000000..69e50f68dc --- /dev/null +++ b/spring-boot-documentation/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Documenting Spring Event-Driven API Using AsyncAPI and Springwolf](https://www.baeldung.com/java-spring-doc-asyncapi-springwolf) diff --git a/spring-boot-documentation/pom.xml b/spring-boot-documentation/pom.xml new file mode 100644 index 0000000000..d718f33a99 --- /dev/null +++ b/spring-boot-documentation/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + com.baeldung.spring-boot-documentation + spring-boot-documentation + 1.0.0-SNAPSHOT + spring-boot-documentation + pom + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../parent-boot-3 + + + + springwolf + + + + + + org.junit + junit-bom + ${junit-jupiter.version} + pom + import + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + 3.3.2 + + + diff --git a/spring-boot-documentation/springwolf/docker-compose.yml b/spring-boot-documentation/springwolf/docker-compose.yml new file mode 100644 index 0000000000..214e2d2ace --- /dev/null +++ b/spring-boot-documentation/springwolf/docker-compose.yml @@ -0,0 +1,37 @@ +version: '3' +services: + zookeeper: + image: confluentinc/cp-zookeeper:latest + environment: + ZOOKEEPER_CLIENT_PORT: 2181 + ZOOKEEPER_TICK_TIME: + + kafka: + image: confluentinc/cp-kafka:latest + depends_on: + - zookeeper + ports: + - "9092:9092" + environment: + KAFKA_BROKER_ID: 1 + KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 + KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092,PLAINTEXT_HOST://kafka:29092 + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT + + + akhq: + image: tchiotludo/akhq + restart: unless-stopped + environment: + AKHQ_CONFIGURATION: | + akhq: + connections: + docker-kafka-server: + properties: + bootstrap.servers: "kafka:29092" + + ports: + - "9090:8080" + links: + - kafka diff --git a/spring-boot-documentation/springwolf/pom.xml b/spring-boot-documentation/springwolf/pom.xml new file mode 100644 index 0000000000..4bd9f24065 --- /dev/null +++ b/spring-boot-documentation/springwolf/pom.xml @@ -0,0 +1,82 @@ + + + 4.0.0 + springwolf + 0.0.1-SNAPSHOT + springwolf + Documentation Spring Event Driven API Using AsyncAPI and Springwolf + + + com.baeldung.spring-boot-documentation + spring-boot-documentation + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.kafka + spring-kafka + + + io.swagger.core.v3 + swagger-core-jakarta + ${swagger-core.version} + + + io.github.springwolf + springwolf-kafka + ${springwolf-kafka.version} + + + io.github.springwolf + springwolf-ui + ${springwolf-ui.version} + + + org.projectlombok + lombok + ${lombok.version} + + + org.springframework.kafka + spring-kafka-test + test + + + org.testcontainers + junit-jupiter + ${testcontainers-kafka.version} + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.boot.documentation.springwolf.SpringwolfApplication + + + + + + + 2.2.11 + 0.12.1 + 0.8.0 + 1.18.3 + + + diff --git a/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/SpringwolfApplication.java b/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/SpringwolfApplication.java new file mode 100644 index 0000000000..1eed112a40 --- /dev/null +++ b/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/SpringwolfApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.boot.documentation.springwolf; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringwolfApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringwolfApplication.class, args); + } +} diff --git a/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/incoming/IncomingConsumer.java b/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/incoming/IncomingConsumer.java new file mode 100644 index 0000000000..ae201dbf30 --- /dev/null +++ b/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/incoming/IncomingConsumer.java @@ -0,0 +1,48 @@ +package com.baeldung.boot.documentation.springwolf.adapter.incoming; + +import com.baeldung.boot.documentation.springwolf.dto.IncomingPayloadDto; +import com.baeldung.boot.documentation.springwolf.service.ProcessorService; +import io.github.stavshamir.springwolf.asyncapi.scanners.channels.operationdata.annotation.AsyncListener; +import io.github.stavshamir.springwolf.asyncapi.scanners.channels.operationdata.annotation.AsyncOperation; +import io.github.stavshamir.springwolf.asyncapi.scanners.channels.operationdata.annotation.KafkaAsyncOperationBinding; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +import static org.springframework.kafka.support.mapping.AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME; + +@AllArgsConstructor +@Component +@Slf4j +public class IncomingConsumer { + + private static final String TOPIC_NAME = "incoming-topic"; + + private final ProcessorService processorService; + + @KafkaListener(topics = TOPIC_NAME) + @AsyncListener(operation = @AsyncOperation( + channelName = TOPIC_NAME, + description = "More details for the incoming topic", + headers = @AsyncOperation.Headers( + schemaName = "SpringKafkaDefaultHeadersIncomingPayloadDto", + values = { + // this header is generated by Spring by default + @AsyncOperation.Headers.Header( + name = DEFAULT_CLASSID_FIELD_NAME, + description = "Spring Type Id Header", + value = "com.baeldung.boot.documentation.springwolf.dto.IncomingPayloadDto" + ), + } + ) + ) + ) + @KafkaAsyncOperationBinding + public void consume(IncomingPayloadDto payload) { + log.info("Received new message: {}", payload.toString()); + + processorService.doHandle(payload); + } + +} diff --git a/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/outgoing/OutgoingProducer.java b/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/outgoing/OutgoingProducer.java new file mode 100644 index 0000000000..5630cd9a04 --- /dev/null +++ b/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/outgoing/OutgoingProducer.java @@ -0,0 +1,47 @@ +package com.baeldung.boot.documentation.springwolf.adapter.outgoing; + +import com.baeldung.boot.documentation.springwolf.dto.OutgoingPayloadDto; +import io.github.stavshamir.springwolf.asyncapi.scanners.channels.operationdata.annotation.AsyncOperation; +import io.github.stavshamir.springwolf.asyncapi.scanners.channels.operationdata.annotation.AsyncPublisher; +import io.github.stavshamir.springwolf.asyncapi.scanners.channels.operationdata.annotation.KafkaAsyncOperationBinding; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +import static org.springframework.kafka.support.mapping.AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME; + +@AllArgsConstructor +@Component +@Slf4j +public class OutgoingProducer { + + private static final String TOPIC_NAME = "outgoing-topic"; + + private final KafkaTemplate kafkaTemplate; + + @AsyncPublisher( + operation = @AsyncOperation( + channelName = TOPIC_NAME, + description = "More details for the outgoing topic", + headers = @AsyncOperation.Headers( + schemaName = "SpringKafkaDefaultHeadersOutgoingPayloadDto", + values = { + // this header is generated by Spring by default + @AsyncOperation.Headers.Header( + name = DEFAULT_CLASSID_FIELD_NAME, + description = "Spring Type Id Header", + value = "com.baeldung.boot.documentation.springwolf.dto.OutgoingPayloadDto" + ), + } + ) + ) + ) + @KafkaAsyncOperationBinding + public void publish(OutgoingPayloadDto payload) { + log.info("Publishing new message: {}", payload.toString()); + + kafkaTemplate.send(TOPIC_NAME, payload); + } + +} diff --git a/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/dto/IncomingPayloadDto.java b/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/dto/IncomingPayloadDto.java new file mode 100644 index 0000000000..a547d55db7 --- /dev/null +++ b/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/dto/IncomingPayloadDto.java @@ -0,0 +1,25 @@ +package com.baeldung.boot.documentation.springwolf.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import static io.swagger.v3.oas.annotations.media.Schema.RequiredMode.NOT_REQUIRED; +import static io.swagger.v3.oas.annotations.media.Schema.RequiredMode.REQUIRED; + +@Data +@Schema(description = "Incoming payload model") +public class IncomingPayloadDto { + @Schema(description = "Some string field", example = "some string value", requiredMode = REQUIRED) + private String someString; + + @Schema(description = "Some long field", example = "5", requiredMode = NOT_REQUIRED) + private long someLong; + + @Schema(description = "Some enum field", example = "FOO2", requiredMode = REQUIRED) + private IncomingPayloadEnum someEnum; + + public enum IncomingPayloadEnum { + FOO1, FOO2, FOO3 + } + +} diff --git a/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/dto/OutgoingPayloadDto.java b/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/dto/OutgoingPayloadDto.java new file mode 100644 index 0000000000..2fb1ab1647 --- /dev/null +++ b/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/dto/OutgoingPayloadDto.java @@ -0,0 +1,20 @@ +package com.baeldung.boot.documentation.springwolf.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Builder; +import lombok.Data; + +import static io.swagger.v3.oas.annotations.media.Schema.RequiredMode.NOT_REQUIRED; +import static io.swagger.v3.oas.annotations.media.Schema.RequiredMode.REQUIRED; + +@Data +@Builder +@Schema(description = "Outgoing payload model") +public class OutgoingPayloadDto { + + @Schema(description = "Foo field", example = "bar", requiredMode = NOT_REQUIRED) + private String foo; + + @Schema(description = "IncomingPayload field", requiredMode = REQUIRED) + private IncomingPayloadDto incomingWrapped; +} diff --git a/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/service/ProcessorService.java b/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/service/ProcessorService.java new file mode 100644 index 0000000000..980f978f4e --- /dev/null +++ b/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/service/ProcessorService.java @@ -0,0 +1,23 @@ +package com.baeldung.boot.documentation.springwolf.service; + +import com.baeldung.boot.documentation.springwolf.adapter.outgoing.OutgoingProducer; +import com.baeldung.boot.documentation.springwolf.dto.OutgoingPayloadDto; +import com.baeldung.boot.documentation.springwolf.dto.IncomingPayloadDto; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@AllArgsConstructor +public class ProcessorService { + + private final OutgoingProducer outgoingProducer; + + public void doHandle(IncomingPayloadDto payload) { + OutgoingPayloadDto message = OutgoingPayloadDto.builder() + .foo("Foo message") + .incomingWrapped(payload) + .build(); + + outgoingProducer.publish(message); + } +} diff --git a/spring-boot-documentation/springwolf/src/main/resources/application.properties b/spring-boot-documentation/springwolf/src/main/resources/application.properties new file mode 100644 index 0000000000..74cb93499e --- /dev/null +++ b/spring-boot-documentation/springwolf/src/main/resources/application.properties @@ -0,0 +1,30 @@ +######### +# Spring Configuration +spring.application.name=Baeldung Tutorial Springwolf Application + +######### +# Spring Kafka Configuration +spring.kafka.bootstrap-servers=localhost:9092 +spring.kafka.consumer.group-id=baeldung-kafka-group-id +spring.kafka.consumer.properties.spring.json.trusted.packages=com.baeldung.boot.documentation.springwolf.* +spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer +spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer +spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer +spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer + +######### +# Springwolf Configuration +springwolf.docket.base-package=com.baeldung.boot.documentation.springwolf.adapter +springwolf.docket.info.title=${spring.application.name} +springwolf.docket.info.version=1.0.0 +springwolf.docket.info.description=Baeldung Tutorial Application to Demonstrate AsyncAPI Documentation using Springwolf + +# Springwolf Kafka Configuration +springwolf.docket.servers.kafka.protocol=kafka +springwolf.docket.servers.kafka.url=localhost:9092 + +springwolf.plugin.kafka.publishing.enabled=true +springwolf.plugin.kafka.publishing.producer.bootstrap-servers=localhost:9092 +springwolf.plugin.kafka.publishing.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer +springwolf.plugin.kafka.publishing.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer +springwolf.plugin.kafka.publishing.producer.properties.spring.json.add.type.headers=false diff --git a/spring-boot-documentation/springwolf/src/test/java/com/baeldung/boot/documentation/springwolf/ApiIntegrationTest.java b/spring-boot-documentation/springwolf/src/test/java/com/baeldung/boot/documentation/springwolf/ApiIntegrationTest.java new file mode 100644 index 0000000000..ac237c0da9 --- /dev/null +++ b/spring-boot-documentation/springwolf/src/test/java/com/baeldung/boot/documentation/springwolf/ApiIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.boot.documentation.springwolf; + +import org.json.JSONException; +import org.junit.jupiter.api.Test; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +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.kafka.test.context.EmbeddedKafka; +import org.springframework.test.annotation.DirtiesContext; +import org.testcontainers.shaded.org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +@SpringBootTest(classes = {SpringwolfApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@EmbeddedKafka( + partitions = 1, brokerProperties = { + "listeners=PLAINTEXT://localhost:9092", + "port=9092", +}) +@DirtiesContext +public class ApiIntegrationTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void asyncApiResourceArtifactTest() throws JSONException, IOException { + // given + InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); + String expected = IOUtils.toString(s, StandardCharsets.UTF_8); + + String url = "/springwolf/docs"; + String actual = restTemplate.getForObject(url, String.class); + + JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT); + } +} diff --git a/spring-boot-documentation/springwolf/src/test/resources/asyncapi.json b/spring-boot-documentation/springwolf/src/test/resources/asyncapi.json new file mode 100644 index 0000000000..0198733c1c --- /dev/null +++ b/spring-boot-documentation/springwolf/src/test/resources/asyncapi.json @@ -0,0 +1,168 @@ +{ + "asyncapi": "2.6.0", + "info": { + "title": "Baeldung Tutorial Springwolf Application", + "version": "1.0.0", + "description": "Baeldung Tutorial Application to Demonstrate AsyncAPI Documentation using Springwolf" + }, + "defaultContentType": "application/json", + "servers": { + "kafka": { + "url": "localhost:9092", + "protocol": "kafka" + } + }, + "channels": { + "incoming-topic": { + "publish": { + "operationId": "incoming-topic_publish", + "description": "More details for the incoming topic", + "bindings": { + "kafka": { } + }, + "message": { + "schemaFormat": "application/vnd.oai.openapi+json;version=3.0.0", + "name": "com.baeldung.boot.documentation.springwolf.dto.IncomingPayloadDto", + "title": "IncomingPayloadDto", + "description": "Incoming payload model", + "payload": { + "$ref": "#/components/schemas/IncomingPayloadDto" + }, + "headers": { + "$ref": "#/components/schemas/SpringKafkaDefaultHeadersIncomingPayloadDto" + }, + "bindings": { + "kafka": { } + } + } + } + }, + "outgoing-topic": { + "subscribe": { + "operationId": "outgoing-topic_subscribe", + "description": "More details for the outgoing topic", + "bindings": { + "kafka": { } + }, + "message": { + "schemaFormat": "application/vnd.oai.openapi+json;version=3.0.0", + "name": "com.baeldung.boot.documentation.springwolf.dto.OutgoingPayloadDto", + "title": "OutgoingPayloadDto", + "description": "Outgoing payload model", + "payload": { + "$ref": "#/components/schemas/OutgoingPayloadDto" + }, + "headers": { + "$ref": "#/components/schemas/SpringKafkaDefaultHeadersOutgoingPayloadDto" + }, + "bindings": { + "kafka": { } + } + } + } + } + }, + "components": { + "schemas": { + "HeadersNotDocumented": { + "type": "object", + "properties": { }, + "example": { } + }, + "IncomingPayloadDto": { + "required": [ + "someEnum", + "someString" + ], + "type": "object", + "properties": { + "someEnum": { + "type": "string", + "description": "Some enum field", + "example": "FOO2", + "enum": [ + "FOO1", + "FOO2", + "FOO3" + ] + }, + "someLong": { + "type": "integer", + "description": "Some long field", + "format": "int64", + "example": 5 + }, + "someString": { + "type": "string", + "description": "Some string field", + "example": "some string value" + } + }, + "description": "Incoming payload model", + "example": { + "someEnum": "FOO2", + "someLong": 5, + "someString": "some string value" + } + }, + "OutgoingPayloadDto": { + "required": [ + "incomingWrapped" + ], + "type": "object", + "properties": { + "foo": { + "type": "string", + "description": "Foo field", + "example": "bar" + }, + "incomingWrapped": { + "$ref": "#/components/schemas/IncomingPayloadDto" + } + }, + "description": "Outgoing payload model", + "example": { + "foo": "bar", + "incomingWrapped": { + "someEnum": "FOO2", + "someLong": 5, + "someString": "some string value" + } + } + }, + "SpringKafkaDefaultHeadersIncomingPayloadDto": { + "type": "object", + "properties": { + "__TypeId__": { + "type": "string", + "description": "Spring Type Id Header", + "example": "com.baeldung.boot.documentation.springwolf.dto.IncomingPayloadDto", + "enum": [ + "com.baeldung.boot.documentation.springwolf.dto.IncomingPayloadDto" + ] + } + }, + "example": { + "__TypeId__": "com.baeldung.boot.documentation.springwolf.dto.IncomingPayloadDto" + } + }, + "SpringKafkaDefaultHeadersOutgoingPayloadDto": { + "type": "object", + "properties": { + "__TypeId__": { + "type": "string", + "description": "Spring Type Id Header", + "example": "com.baeldung.boot.documentation.springwolf.dto.OutgoingPayloadDto", + "enum": [ + "com.baeldung.boot.documentation.springwolf.dto.OutgoingPayloadDto" + ] + } + }, + "example": { + "__TypeId__": "com.baeldung.boot.documentation.springwolf.dto.OutgoingPayloadDto" + } + } + } + }, + "tags": [ ] +} diff --git a/spring-boot-modules/spring-boot-3-observation/pom.xml b/spring-boot-modules/spring-boot-3-observation/pom.xml index f69ce699bc..b0d179e365 100644 --- a/spring-boot-modules/spring-boot-3-observation/pom.xml +++ b/spring-boot-modules/spring-boot-3-observation/pom.xml @@ -66,7 +66,7 @@ com.github.gavlyukovskiy p6spy-spring-boot-starter - 1.9.0 + ${p6spy-spring-boot-starter.version} com.h2database @@ -84,6 +84,7 @@ com.baeldung.samples.SimpleObservationApplication + 1.9.0 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 f3ed67e87b..4aa4ab470b 100644 --- a/spring-boot-modules/spring-boot-3-test-pitfalls/pom.xml +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/pom.xml @@ -69,7 +69,7 @@ org.projectlombok lombok-mapstruct-binding - 0.2.0 + ${lombok-mapstruct-binding.version} @@ -80,6 +80,7 @@ 1.5.3.Final + 0.2.0 3.0.0-M7 diff --git a/spring-boot-modules/spring-boot-3-url-matching/pom.xml b/spring-boot-modules/spring-boot-3-url-matching/pom.xml index 0ed6fdbd9b..aa83a676d7 100644 --- a/spring-boot-modules/spring-boot-3-url-matching/pom.xml +++ b/spring-boot-modules/spring-boot-3-url-matching/pom.xml @@ -46,13 +46,13 @@ org.springframework spring-test - 6.0.6 + ${spring-test.version} test javax.servlet javax.servlet-api - 3.1.0 + ${javax.servlet-api.version} provided @@ -62,12 +62,12 @@ io.projectreactor reactor-core - 3.5.4 + ${reactor-core.version} io.projectreactor reactor-test - 3.5.4 + ${reactor-test.version} test @@ -78,7 +78,6 @@ org.apache.maven.plugins maven-compiler-plugin - org.springframework.boot @@ -95,6 +94,10 @@ + 6.0.6 + 3.1.0 + 3.5.4 + 3.5.4> 3.0.0-M7 diff --git a/spring-boot-modules/spring-boot-3/pom.xml b/spring-boot-modules/spring-boot-3/pom.xml index 8fe995ca91..369ba30b5a 100644 --- a/spring-boot-modules/spring-boot-3/pom.xml +++ b/spring-boot-modules/spring-boot-3/pom.xml @@ -107,7 +107,7 @@ org.projectlombok lombok-mapstruct-binding - 0.2.0 + ${lombok-mapstruct-binding.version} @@ -149,6 +149,7 @@ 3.0.0-M7 com.baeldung.sample.TodoApplication 5.14.0 + 0.2.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-artifacts/pom.xml b/spring-boot-modules/spring-boot-artifacts/pom.xml index 996ed92014..dedeb0ab2a 100644 --- a/spring-boot-modules/spring-boot-artifacts/pom.xml +++ b/spring-boot-modules/spring-boot-artifacts/pom.xml @@ -99,7 +99,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 2.18 + ${maven-failsafe-plugin.version} @@ -193,6 +193,7 @@ 2.2.4 3.1.7 4.5.8 + 2.18 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-aws/pom.xml b/spring-boot-modules/spring-boot-aws/pom.xml index 2abce7df76..12a65908af 100644 --- a/spring-boot-modules/spring-boot-aws/pom.xml +++ b/spring-boot-modules/spring-boot-aws/pom.xml @@ -14,9 +14,6 @@ spring-boot-modules 1.0.0-SNAPSHOT - - 1.9.1 - @@ -43,7 +40,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + ${maven-shade-plugin.version} false @@ -74,4 +71,9 @@ + + 1.9.1 + 3.2.4 + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/pom.xml b/spring-boot-modules/spring-boot-basic-customization/pom.xml index 20b2980f29..4b1009d38a 100644 --- a/spring-boot-modules/spring-boot-basic-customization/pom.xml +++ b/spring-boot-modules/spring-boot-basic-customization/pom.xml @@ -34,11 +34,6 @@ - - - com.baeldung.changeport.CustomApplication - - errorhandling @@ -77,7 +72,7 @@ org.springframework.boot spring-boot-maven-plugin - 1.5.2.RELEASE + ${spring-boot-maven-plugin.version} ${spring.boot.mainclass} @@ -85,4 +80,11 @@ + + 1.5.2.RELEASE + + com.baeldung.changeport.CustomApplication + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-jsp/README.md b/spring-boot-modules/spring-boot-jsp/README.md index 535f86531d..f67587b949 100644 --- a/spring-boot-modules/spring-boot-jsp/README.md +++ b/spring-boot-modules/spring-boot-jsp/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Spring Boot With JavaServer Pages (JSP)](https://www.baeldung.com/spring-boot-jsp) +- [Reading a JSP Variable From JavaScript](https://www.baeldung.com/java-jsp-read-variable-js) diff --git a/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/postman/controller/PostmanUploadController.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/postman/controller/PostmanUploadController.java index ac19110318..6225a6b34b 100644 --- a/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/postman/controller/PostmanUploadController.java +++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/postman/controller/PostmanUploadController.java @@ -5,6 +5,7 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import com.baeldung.postman.model.JsonRequest; @@ -23,4 +24,10 @@ public class PostmanUploadController { return ResponseEntity.ok() .body(json.getId() + json.getName()); } + + @PostMapping("/uploadJsonAndMultipartData") + public ResponseEntity handleJsonAndMultipartInput(@RequestPart("data") JsonRequest json, @RequestPart("file") MultipartFile file) { + return ResponseEntity.ok() + .body(json.getId() + json.getName()); + } } diff --git a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-server/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-server/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..c270ba92f6 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-server/src/test/resources/logback-test.xml @@ -0,0 +1,17 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-netflix-feign/src/test/java/com/baeldung/cloud/netflix/feign/NetflixFeignUnitTest.java b/spring-cloud-modules/spring-cloud-netflix-feign/src/test/java/com/baeldung/cloud/netflix/feign/NetflixFeignIntegrationTest.java similarity index 98% rename from spring-cloud-modules/spring-cloud-netflix-feign/src/test/java/com/baeldung/cloud/netflix/feign/NetflixFeignUnitTest.java rename to spring-cloud-modules/spring-cloud-netflix-feign/src/test/java/com/baeldung/cloud/netflix/feign/NetflixFeignIntegrationTest.java index 9ee925201d..1cba547e0e 100644 --- a/spring-cloud-modules/spring-cloud-netflix-feign/src/test/java/com/baeldung/cloud/netflix/feign/NetflixFeignUnitTest.java +++ b/spring-cloud-modules/spring-cloud-netflix-feign/src/test/java/com/baeldung/cloud/netflix/feign/NetflixFeignIntegrationTest.java @@ -31,7 +31,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(properties = {"external.api.url=http://localhost:${wiremock.server.port}"}) @AutoConfigureWireMock(port = 0) -public class NetflixFeignUnitTest { +public class NetflixFeignIntegrationTest { @Autowired private JSONPlaceHolderService jsonPlaceHolderService; diff --git a/spring-cloud-modules/spring-cloud-netflix-feign/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-netflix-feign/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..83bf131763 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-netflix-feign/src/test/resources/logback-test.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/README.md b/spring-cloud-modules/spring-cloud-openfeign-2/README.md new file mode 100644 index 0000000000..d537907403 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-openfeign-2/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Setup Http Patch Request With OpenFeign](https://www.baeldung.com/openfeign-http-patch-request) diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/client/FormClientUnitTest.java b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/client/FormClientIntegrationTest.java similarity index 98% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/client/FormClientUnitTest.java rename to spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/client/FormClientIntegrationTest.java index f374e8e0bd..390deb3dfb 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/client/FormClientUnitTest.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/client/FormClientIntegrationTest.java @@ -29,7 +29,7 @@ import lombok.extern.slf4j.Slf4j; @ExtendWith(SpringExtension.class) @SpringBootTest @Slf4j -class FormClientUnitTest { +class FormClientIntegrationTest { private static WireMockServer wireMockServer; diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientIntegrationTest.java similarity index 98% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java rename to spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientIntegrationTest.java index 385ce900f5..c0d1227f62 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientIntegrationTest.java @@ -22,7 +22,7 @@ import com.github.tomakehurst.wiremock.WireMockServer; @RunWith(SpringRunner.class) @SpringBootTest(classes = ExampleApplication.class) -public class ProductClientUnitTest { +public class ProductClientIntegrationTest { @Autowired private ProductClient productClient; diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerIntegrationTest.java similarity index 98% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java rename to spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerIntegrationTest.java index 3d103d1333..d0302d3daa 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerIntegrationTest.java @@ -31,7 +31,7 @@ import com.github.tomakehurst.wiremock.client.WireMock; @RunWith(SpringRunner.class) @WebMvcTest(ProductController.class) @ImportAutoConfiguration({FeignAutoConfiguration.class}) -public class ProductControllerUnitTest { +public class ProductControllerIntegrationTest { @Autowired private ProductClient productClient; diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClientUnitTest.java b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClientIntegrationTest.java similarity index 98% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClientUnitTest.java rename to spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClientIntegrationTest.java index ed4cf75890..09c9466fbf 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClientUnitTest.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClientIntegrationTest.java @@ -25,7 +25,7 @@ import feign.FeignException; @RunWith(SpringRunner.class) @SpringBootTest(classes = ExampleApplication.class) -public class ProductClientUnitTest { +public class ProductClientIntegrationTest { @Autowired private ProductClient productClient; diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductControllerUnitTest.java b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductControllerIntegrationTest.java similarity index 98% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductControllerUnitTest.java rename to spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductControllerIntegrationTest.java index 7271aa2672..cd776a0eea 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductControllerUnitTest.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductControllerIntegrationTest.java @@ -29,7 +29,7 @@ import com.github.tomakehurst.wiremock.client.WireMock; @WebMvcTest(ProductController.class) @ImportAutoConfiguration({FeignAutoConfiguration.class, TestControllerAdvice.class}) @EnableWebMvc -public class ProductControllerUnitTest { +public class ProductControllerIntegrationTest { @Autowired private ProductClient productClient; diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-openfeign/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..612e4e0e9d --- /dev/null +++ b/spring-cloud-modules/spring-cloud-openfeign/src/test/resources/logback-test.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..0e8e2b4a06 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/src/test/resources/logback-test.xml @@ -0,0 +1,15 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-zookeeper/spring-cloud-zookeeper-greeting/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-zookeeper/spring-cloud-zookeeper-greeting/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..98a596c8ad --- /dev/null +++ b/spring-cloud-modules/spring-cloud-zookeeper/spring-cloud-zookeeper-greeting/src/test/resources/logback-test.xml @@ -0,0 +1,15 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-zookeeper/spring-cloud-zookeeper-helloworld/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-zookeeper/spring-cloud-zookeeper-helloworld/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..98a596c8ad --- /dev/null +++ b/spring-cloud-modules/spring-cloud-zookeeper/spring-cloud-zookeeper-helloworld/src/test/resources/logback-test.xml @@ -0,0 +1,15 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-zuul-eureka-integration/eureka-server/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-zuul-eureka-integration/eureka-server/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..a037859a0c --- /dev/null +++ b/spring-cloud-modules/spring-cloud-zuul-eureka-integration/eureka-server/src/test/resources/logback-test.xml @@ -0,0 +1,15 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + \ No newline at end of file diff --git a/spring-jenkins-pipeline/src/test/resources/logback-test.xml b/spring-jenkins-pipeline/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..b9242f40a8 --- /dev/null +++ b/spring-jenkins-pipeline/src/test/resources/logback-test.xml @@ -0,0 +1,14 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-rest-custom/src/main/java/com/baeldung/web/controller/SecurityController4.java b/spring-security-modules/spring-security-web-rest-custom/src/main/java/com/baeldung/web/controller/SecurityController4.java new file mode 100644 index 0000000000..93a2bfcacd --- /dev/null +++ b/spring-security-modules/spring-security-web-rest-custom/src/main/java/com/baeldung/web/controller/SecurityController4.java @@ -0,0 +1,16 @@ +package com.baeldung.web.controller; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SecurityController4 { + + @GetMapping("/user") + public String getUser(@AuthenticationPrincipal UserDetails userDetails) { + return "User Details: " + userDetails.getUsername(); + } + +} diff --git a/spring-security-modules/spring-security-web-rest/README.md b/spring-security-modules/spring-security-web-rest/README.md index a11bc7e8d6..a50f0d315d 100644 --- a/spring-security-modules/spring-security-web-rest/README.md +++ b/spring-security-modules/spring-security-web-rest/README.md @@ -14,3 +14,4 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Servlet 3 Async Support with Spring MVC and Spring Security](https://www.baeldung.com/spring-mvc-async-security) - [Intro to Spring Security Expressions](https://www.baeldung.com/spring-security-expressions) - [Error Handling for REST with Spring](https://www.baeldung.com/exception-handling-for-rest-with-spring) +- [How to Solve 403 Error in Spring Boot POST Request](https://www.baeldung.com/java-spring-fix-403-error) diff --git a/spring-web-modules/spring-thymeleaf-2/README.md b/spring-web-modules/spring-thymeleaf-2/README.md index e21b7b6be7..c5db9a8e0f 100644 --- a/spring-web-modules/spring-thymeleaf-2/README.md +++ b/spring-web-modules/spring-thymeleaf-2/README.md @@ -11,4 +11,4 @@ This module contains articles about Spring with Thymeleaf - [Working With Arrays in Thymeleaf](https://www.baeldung.com/thymeleaf-arrays) - [Working with Boolean in Thymeleaf](https://www.baeldung.com/thymeleaf-boolean) - [Working With Custom HTML Attributes in Thymeleaf](https://www.baeldung.com/thymeleaf-custom-html-attributes) -- [[<-- prev]](/spring-thymeleaf) +- More articles: [[<-- prev]](../spring-thymeleaf) [[next -->]](../spring-thymeleaf-3) diff --git a/spring-web-modules/spring-thymeleaf-3/README.md b/spring-web-modules/spring-thymeleaf-3/README.md index 46ddd6c03f..12f300a6a3 100644 --- a/spring-web-modules/spring-thymeleaf-3/README.md +++ b/spring-web-modules/spring-thymeleaf-3/README.md @@ -11,4 +11,4 @@ This module contains articles about Spring with Thymeleaf - [Using Hidden Inputs with Spring and Thymeleaf](https://www.baeldung.com/spring-thymeleaf-hidden-inputs) - [Thymeleaf Variables](https://www.baeldung.com/thymeleaf-variables) - [Displaying Error Messages with Thymeleaf in Spring](https://www.baeldung.com/spring-thymeleaf-error-messages) -- [[next -->]](/spring-thymeleaf-4) +- More articles: [[<-- prev]](../spring-thymeleaf-2) [[next -->]](../spring-thymeleaf-4) diff --git a/spring-web-modules/spring-thymeleaf-4/README.md b/spring-web-modules/spring-thymeleaf-4/README.md index f8dc4c8b4e..b8c18965bc 100644 --- a/spring-web-modules/spring-thymeleaf-4/README.md +++ b/spring-web-modules/spring-thymeleaf-4/README.md @@ -2,26 +2,14 @@ This module contains articles about Spring with Thymeleaf -### Relevant Articles: -- [CSRF Protection with Spring MVC and Thymeleaf](https://www.baeldung.com/csrf-thymeleaf-with-spring-security) -- [Conditionals in Thymeleaf](https://www.baeldung.com/spring-thymeleaf-conditionals) -- [Iteration in Thymeleaf](https://www.baeldung.com/thymeleaf-iteration) -- [Spring with Thymeleaf Pagination for a List](https://www.baeldung.com/spring-thymeleaf-pagination) +## Relevant Articles: -### Build the Project - -mvn clean install - -### Run the Project - -mvn cargo:run -- **note**: starts on port '8082' - -Access the pages using the URLs: - - - http://localhost:8082/spring-thymeleaf-4/ - - http://localhost:8082/spring-thymeleaf-4/addStudent/ - - http://localhost:8082/spring-thymeleaf-4/listStudents/ - -The first URL is the home page of the application. The home page has links to the second and third pages. +- [Changing the Thymeleaf Template Directory in Spring Boot](https://www.baeldung.com/spring-thymeleaf-template-directory) +- [Add a Checked Attribute to Input Conditionally in Thymeleaf](https://www.baeldung.com/thymeleaf-conditional-checked-attribute) +- [Spring MVC Data and Thymeleaf](https://www.baeldung.com/spring-mvc-thymeleaf-data) +- [Upload Image With Spring Boot and Thymeleaf](https://www.baeldung.com/spring-boot-thymeleaf-image-upload) +- [Getting a URL Attribute Value in Thymeleaf](https://www.baeldung.com/thymeleaf-url-attribute-value) +- [Expression Types in Thymeleaf](https://www.baeldung.com/java-thymeleaf-expression-types) +- [Difference Between th:text and th:value in Thymeleaf](https://www.baeldung.com/java-thymeleaf-text-vs-value) +- More articles: [[<-- prev]](../spring-thymeleaf-3) [[next -->]](../spring-thymeleaf-5) diff --git a/spring-web-modules/spring-thymeleaf-4/pom.xml b/spring-web-modules/spring-thymeleaf-4/pom.xml index 163d590c9f..2582044c0f 100644 --- a/spring-web-modules/spring-thymeleaf-4/pom.xml +++ b/spring-web-modules/spring-thymeleaf-4/pom.xml @@ -9,139 +9,33 @@ com.baeldung - parent-spring-5 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-spring-5 + ../../parent-boot-2 - - org.springframework - spring-context - ${spring.version} - - - - commons-logging - commons-logging - - + org.springframework.boot + spring-boot-starter-web - org.springframework - spring-webmvc - ${spring.version} + org.springframework.boot + spring-boot-starter-thymeleaf - org.springframework.data - spring-data-commons - ${spring-data.version} - - - javax.validation - validation-api - ${javax.validation-version} - - - org.hibernate.validator - hibernate-validator - ${hibernate-validator.version} - - - - org.springframework.security - spring-security-web - ${spring-security.version} - - - org.springframework.security - spring-security-config - ${spring-security.version} - - - - org.thymeleaf - thymeleaf - ${org.thymeleaf-version} - - - org.thymeleaf - thymeleaf-spring5 - ${org.thymeleaf-version} - - - nz.net.ultraq.thymeleaf - thymeleaf-layout-dialect - ${thymeleaf-layout-dialect.version} - - - org.thymeleaf.extras - thymeleaf-extras-java8time - ${org.thymeleaf.extras-version} - - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - provided - - - - org.springframework - spring-test - ${spring.version} - test - - - org.springframework.security - spring-security-test - ${spring-security.version} + org.springframework.boot + spring-boot-starter-test test - - - org.apache.maven.plugins - maven-war-plugin - - false - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty9x - embedded - - - - - - 8082 - - - - - + spring-thymeleaf-4 - 2.3.2.RELEASE - 3.0.11.RELEASE - 3.0.4.RELEASE - 2.4.1 - 2.0.1.Final - 6.0.11.Final - - 1.6.1 + 2.2 \ No newline at end of file diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/Application.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/Application.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/Application.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/Application.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/attribute/CheckedAttributeController.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/attribute/CheckedAttributeController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/attribute/CheckedAttributeController.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/attribute/CheckedAttributeController.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/attributes/AttributeController.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/attributes/AttributeController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/attributes/AttributeController.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/attributes/AttributeController.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/expression/Dino.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/expression/Dino.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/expression/Dino.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/expression/Dino.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/expression/DinoController.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/expression/DinoController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/expression/DinoController.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/expression/DinoController.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/imageupload/UploadController.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/imageupload/UploadController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/imageupload/UploadController.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/imageupload/UploadController.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/url/UrlController.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/url/UrlController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/url/UrlController.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/url/UrlController.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/application.properties b/spring-web-modules/spring-thymeleaf-4/src/main/resources/application.properties similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/application.properties rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/application.properties diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/messages.properties b/spring-web-modules/spring-thymeleaf-4/src/main/resources/messages.properties similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/messages.properties rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/messages.properties diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-2/hello.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates-2/hello.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-2/hello.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates-2/hello.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-3/form.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates-3/form.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-3/form.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates-3/form.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-3/index.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates-3/index.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-3/index.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates-3/index.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-3/result.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates-3/result.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-3/result.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates-3/result.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/attribute/index.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/attribute/index.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/attribute/index.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/attribute/index.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/attributes/index.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/attributes/index.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/attributes/index.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/attributes/index.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/imageupload/index.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/imageupload/index.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/imageupload/index.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/imageupload/index.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-bean-data.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/mvcdata/email-bean-data.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-bean-data.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/mvcdata/email-bean-data.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-model-attributes.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/mvcdata/email-model-attributes.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-model-attributes.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/mvcdata/email-model-attributes.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-request-parameters.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/mvcdata/email-request-parameters.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-request-parameters.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/mvcdata/email-request-parameters.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-servlet-context.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/mvcdata/email-servlet-context.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-servlet-context.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/mvcdata/email-servlet-context.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-session-attributes.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/mvcdata/email-session-attributes.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-session-attributes.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/mvcdata/email-session-attributes.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/url/index.html b/spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/url/index.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/url/index.html rename to spring-web-modules/spring-thymeleaf-4/src/main/resources/templates/url/index.html diff --git a/spring-web-modules/spring-thymeleaf-5/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java b/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-5/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java rename to spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/test/resources/logback-test.xml b/spring-web-modules/spring-thymeleaf-4/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/spring-web-modules/spring-thymeleaf-5/README.md b/spring-web-modules/spring-thymeleaf-5/README.md index 7e2f8c37b4..7b64a4e423 100644 --- a/spring-web-modules/spring-thymeleaf-5/README.md +++ b/spring-web-modules/spring-thymeleaf-5/README.md @@ -2,13 +2,9 @@ This module contains articles about Spring with Thymeleaf -## Relevant Articles: - -- [Changing the Thymeleaf Template Directory in Spring Boot](https://www.baeldung.com/spring-thymeleaf-template-directory) -- [How to Create an Executable JAR with Maven](https://www.baeldung.com/executable-jar-with-maven) -- [Spring MVC Data and Thymeleaf](https://www.baeldung.com/spring-mvc-thymeleaf-data) -- [Upload Image With Spring Boot and Thymeleaf](https://www.baeldung.com/spring-boot-thymeleaf-image-upload) -- [Getting a URL Attribute Value in Thymeleaf](https://www.baeldung.com/thymeleaf-url-attribute-value) -- [Expression Types in Thymeleaf](https://www.baeldung.com/java-thymeleaf-expression-types) -- [Difference Between th:text and th:value in Thymeleaf](https://www.baeldung.com/java-thymeleaf-text-vs-value) -- [[<-- prev]](/spring-thymeleaf) +### Relevant Articles: +- [CSRF Protection with Spring MVC and Thymeleaf](https://www.baeldung.com/csrf-thymeleaf-with-spring-security) +- [Conditionals in Thymeleaf](https://www.baeldung.com/spring-thymeleaf-conditionals) +- [Iteration in Thymeleaf](https://www.baeldung.com/thymeleaf-iteration) +- [Spring with Thymeleaf Pagination for a List](https://www.baeldung.com/spring-thymeleaf-pagination) +- More articles: [[<-- prev]](../spring-thymeleaf-4) diff --git a/spring-web-modules/spring-thymeleaf-5/pom.xml b/spring-web-modules/spring-thymeleaf-5/pom.xml index e7c54d83c9..0717e41bac 100644 --- a/spring-web-modules/spring-thymeleaf-5/pom.xml +++ b/spring-web-modules/spring-thymeleaf-5/pom.xml @@ -9,33 +9,139 @@ com.baeldung - parent-boot-2 + parent-spring-5 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-spring-5 + - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-context + ${spring.version} + + + + commons-logging + commons-logging + + - org.springframework.boot - spring-boot-starter-thymeleaf + org.springframework + spring-webmvc + ${spring.version} - org.springframework.boot - spring-boot-starter-test + org.springframework.data + spring-data-commons + ${spring-data.version} + + + javax.validation + validation-api + ${javax.validation-version} + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator.version} + + + + org.springframework.security + spring-security-web + ${spring-security.version} + + + org.springframework.security + spring-security-config + ${spring-security.version} + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring5 + ${org.thymeleaf-version} + + + nz.net.ultraq.thymeleaf + thymeleaf-layout-dialect + ${thymeleaf-layout-dialect.version} + + + org.thymeleaf.extras + thymeleaf-extras-java8time + ${org.thymeleaf.extras-version} + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + + + + org.springframework + spring-test + ${spring.version} + test + + + org.springframework.security + spring-security-test + ${spring-security.version} test - spring-thymeleaf-5 + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty9x + embedded + + + + + + 8082 + + + + + - 2.2 + 2.3.2.RELEASE + 3.0.11.RELEASE + 3.0.4.RELEASE + 2.4.1 + 2.0.1.Final + 6.0.11.Final + + 1.6.1 \ No newline at end of file diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebApp.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/config/WebApp.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebApp.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/config/WebApp.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/BookController.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/controller/BookController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/BookController.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/controller/BookController.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/TeacherController.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/controller/TeacherController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/TeacherController.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/controller/TeacherController.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Book.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/model/Book.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Book.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/model/Book.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Student.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/model/Student.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Student.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/model/Student.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Teacher.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/model/Teacher.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Teacher.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/model/Teacher.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/service/BookService.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/service/BookService.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/service/BookService.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/service/BookService.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/TeacherUtils.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/utils/TeacherUtils.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/TeacherUtils.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/utils/TeacherUtils.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/resources/logback.xml b/spring-web-modules/spring-thymeleaf-5/src/main/resources/logback.xml similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/resources/logback.xml rename to spring-web-modules/spring-thymeleaf-5/src/main/resources/logback.xml diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/resources/messages_en.properties b/spring-web-modules/spring-thymeleaf-5/src/main/resources/messages_en.properties similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/resources/messages_en.properties rename to spring-web-modules/spring-thymeleaf-5/src/main/resources/messages_en.properties diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/addStudent.html b/spring-web-modules/spring-thymeleaf-5/src/main/webapp/WEB-INF/views/addStudent.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/addStudent.html rename to spring-web-modules/spring-thymeleaf-5/src/main/webapp/WEB-INF/views/addStudent.html diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/csrfAttack.html b/spring-web-modules/spring-thymeleaf-5/src/main/webapp/WEB-INF/views/csrfAttack.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/csrfAttack.html rename to spring-web-modules/spring-thymeleaf-5/src/main/webapp/WEB-INF/views/csrfAttack.html diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/home.html b/spring-web-modules/spring-thymeleaf-5/src/main/webapp/WEB-INF/views/home.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/home.html rename to spring-web-modules/spring-thymeleaf-5/src/main/webapp/WEB-INF/views/home.html diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/listBooks.html b/spring-web-modules/spring-thymeleaf-5/src/main/webapp/WEB-INF/views/listBooks.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/listBooks.html rename to spring-web-modules/spring-thymeleaf-5/src/main/webapp/WEB-INF/views/listBooks.html diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/listStudents.html b/spring-web-modules/spring-thymeleaf-5/src/main/webapp/WEB-INF/views/listStudents.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/listStudents.html rename to spring-web-modules/spring-thymeleaf-5/src/main/webapp/WEB-INF/views/listStudents.html diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/listTeachers.html b/spring-web-modules/spring-thymeleaf-5/src/main/webapp/WEB-INF/views/listTeachers.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/listTeachers.html rename to spring-web-modules/spring-thymeleaf-5/src/main/webapp/WEB-INF/views/listTeachers.html diff --git a/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/SpringContextTest.java b/spring-web-modules/spring-thymeleaf-5/src/test/java/com/baeldung/thymeleaf/SpringContextTest.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/SpringContextTest.java rename to spring-web-modules/spring-thymeleaf-5/src/test/java/com/baeldung/thymeleaf/SpringContextTest.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/controller/ControllerIntegrationTest.java b/spring-web-modules/spring-thymeleaf-5/src/test/java/com/baeldung/thymeleaf/controller/ControllerIntegrationTest.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/controller/ControllerIntegrationTest.java rename to spring-web-modules/spring-thymeleaf-5/src/test/java/com/baeldung/thymeleaf/controller/ControllerIntegrationTest.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java b/spring-web-modules/spring-thymeleaf-5/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java rename to spring-web-modules/spring-thymeleaf-5/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java diff --git a/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/README.md b/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/README.md new file mode 100644 index 0000000000..d7ece5ff7f --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-attributes/accessing-session-attributes/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Accessing Session Attributes in Thymeleaf](https://www.baeldung.com/thymeleaf-accessing-session-attributes) diff --git a/spring-web-modules/spring-thymeleaf/README.md b/spring-web-modules/spring-thymeleaf/README.md index 2d1bc848d8..b49095f5b1 100644 --- a/spring-web-modules/spring-thymeleaf/README.md +++ b/spring-web-modules/spring-thymeleaf/README.md @@ -10,8 +10,7 @@ This module contains articles about Spring with Thymeleaf - [How to Work with Dates in Thymeleaf](https://www.baeldung.com/dates-in-thymeleaf) - [Working with Fragments in Thymeleaf](https://www.baeldung.com/spring-thymeleaf-fragments) - [JavaScript Function Call with Thymeleaf](https://www.baeldung.com/thymeleaf-js-function-call) -- [Add a Checked Attribute to Input Conditionally in Thymeleaf](https://www.baeldung.com/thymeleaf-conditional-checked-attribute) -- [[next -->]](/spring-thymeleaf-2) +- [[next -->]](../spring-thymeleaf-2) ### Build the Project diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jmockit/AdvancedCollaborator.java b/testing-modules/mocks/src/main/java/com/baeldung/jmockit/AdvancedCollaborator.java index 61afccc745..2bf116a49c 100644 --- a/testing-modules/mocks/src/main/java/com/baeldung/jmockit/AdvancedCollaborator.java +++ b/testing-modules/mocks/src/main/java/com/baeldung/jmockit/AdvancedCollaborator.java @@ -7,7 +7,7 @@ public class AdvancedCollaborator { public AdvancedCollaborator(String string) throws Exception{ i = string.length(); } - public String methodThatCallsPrivateMethod(int i){ + public String methodThatCallsProtectedMethod(int i){ return protectedMethod() + i; } public int methodThatReturnsThePrivateField(){ diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jmockit/AppManager.java b/testing-modules/mocks/src/main/java/com/baeldung/jmockit/AppManager.java index 6306a94d29..0ecff9899d 100644 --- a/testing-modules/mocks/src/main/java/com/baeldung/jmockit/AppManager.java +++ b/testing-modules/mocks/src/main/java/com/baeldung/jmockit/AppManager.java @@ -20,7 +20,4 @@ public class AppManager { return new Random().nextInt(7); } - private static Integer stringToInteger(String num) { - return Integer.parseInt(num); - } } diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jmockit/AdvancedCollaboratorIntegrationTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jmockit/AdvancedCollaboratorIntegrationTest.java index ff69a701e7..75cbc41274 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jmockit/AdvancedCollaboratorIntegrationTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jmockit/AdvancedCollaboratorIntegrationTest.java @@ -31,7 +31,7 @@ public class AdvancedCollaboratorIntegrationTest { return "mocked: "; } }; - String res = mock.methodThatCallsPrivateMethod(1); + String res = mock.methodThatCallsProtectedMethod(1); assertEquals("mocked: 1", res); } diff --git a/testing-modules/selenide/README.md b/testing-modules/selenide/README.md new file mode 100644 index 0000000000..afe15417f6 --- /dev/null +++ b/testing-modules/selenide/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Introduction to Selenide](https://www.baeldung.com/selenide) diff --git a/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/wait/ExplicitWaitLiveTest.java b/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/wait/ExplicitWaitLiveTest.java index a48857f31d..d9627c2ce2 100644 --- a/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/wait/ExplicitWaitLiveTest.java +++ b/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/wait/ExplicitWaitLiveTest.java @@ -11,6 +11,7 @@ import org.junit.jupiter.api.Test; import org.openqa.selenium.By; import org.openqa.selenium.ElementNotInteractableException; import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.ExpectedConditions; @@ -49,10 +50,8 @@ final class ExplicitWaitLiveTest { @Test void givenPage_whenNavigatingWithoutExplicitWait_thenElementNotInteractable() { driver.navigate().to("https://www.baeldung.com/"); - - driver.findElement(LOCATOR_ABOUT).click(); - - assertThrows(ElementNotInteractableException.class, () -> driver.findElement(LOCATOR_ABOUT_BAELDUNG).click()); + WebElement about = driver.findElement(LOCATOR_ABOUT_BAELDUNG); + assertThrows(ElementNotInteractableException.class, about::click); } @Test diff --git a/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/wait/FluentWaitLiveTest.java b/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/wait/FluentWaitLiveTest.java index 51e14ad210..9de462690d 100644 --- a/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/wait/FluentWaitLiveTest.java +++ b/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/wait/FluentWaitLiveTest.java @@ -11,6 +11,7 @@ import org.junit.jupiter.api.Test; import org.openqa.selenium.By; import org.openqa.selenium.ElementNotInteractableException; import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.ExpectedConditions; @@ -53,10 +54,8 @@ final class FluentWaitLiveTest { @Test void givenPage_whenNavigatingWithoutFluentWait_thenElementNotInteractable() { driver.navigate().to("https://www.baeldung.com/"); - - driver.findElement(LOCATOR_ABOUT).click(); - - assertThrows(ElementNotInteractableException.class, () -> driver.findElement(LOCATOR_ABOUT_BAELDUNG).click()); + WebElement about = driver.findElement(LOCATOR_ABOUT_BAELDUNG); + assertThrows(ElementNotInteractableException.class, about::click); } @Test