diff --git a/algorithms-modules/algorithms-miscellaneous-3/README.md b/algorithms-modules/algorithms-miscellaneous-3/README.md index dd5bbac162..8a606caa22 100644 --- a/algorithms-modules/algorithms-miscellaneous-3/README.md +++ b/algorithms-modules/algorithms-miscellaneous-3/README.md @@ -10,7 +10,7 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Converting Between Roman and Arabic Numerals in Java](https://www.baeldung.com/java-convert-roman-arabic) - [Practical Java Examples of the Big O Notation](https://www.baeldung.com/java-algorithm-complexity) - [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted) -- [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle) +- [Checking if a Java Graph Has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle) - [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique) - [Creating a Triangle with for Loops in Java](https://www.baeldung.com/java-print-triangle) - [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm) diff --git a/algorithms-modules/algorithms-miscellaneous-4/README.md b/algorithms-modules/algorithms-miscellaneous-4/README.md index e2ae542bf8..6f1b6a66b9 100644 --- a/algorithms-modules/algorithms-miscellaneous-4/README.md +++ b/algorithms-modules/algorithms-miscellaneous-4/README.md @@ -5,10 +5,10 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. ### Relevant articles: - [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm) -- [Check If a String Contains All The Letters of The Alphabet with Java](https://www.baeldung.com/java-string-contains-all-letters) +- [Check if a String Contains All the Letters of the Alphabet With Java](https://www.baeldung.com/java-string-contains-all-letters) - [Find the Middle Element of a Linked List in Java](https://www.baeldung.com/java-linked-list-middle-element) - [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings) -- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters) +- [Find the Longest Substring Without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters) - [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations) - [Find the Smallest Missing Integer in an Array](https://www.baeldung.com/java-smallest-missing-integer-in-array) - [Permutations of a String in Java](https://www.baeldung.com/java-string-permutations) diff --git a/algorithms-modules/algorithms-miscellaneous-5/README.md b/algorithms-modules/algorithms-miscellaneous-5/README.md index 54b936586f..72e9b45683 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/README.md +++ b/algorithms-modules/algorithms-miscellaneous-5/README.md @@ -9,7 +9,7 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree) - [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers) - [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack) -- [How to Determine if a Binary Tree is Balanced in Java](https://www.baeldung.com/java-balanced-binary-tree) +- [How to Determine if a Binary Tree Is Balanced in Java](https://www.baeldung.com/java-balanced-binary-tree) - [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms) - [Prim’s Algorithm with a Java Implementation](https://www.baeldung.com/java-prim-algorithm) - [Maximum Subarray Problem in Java](https://www.baeldung.com/java-maximum-subarray) diff --git a/apache-cxf-modules/sse-jaxrs/README.md b/apache-cxf-modules/sse-jaxrs/README.md index 4d39560b46..ee85940b8a 100644 --- a/apache-cxf-modules/sse-jaxrs/README.md +++ b/apache-cxf-modules/sse-jaxrs/README.md @@ -1,3 +1,3 @@ ### Relevant Articles: -- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse) +- [Server-Sent Events (SSE) in JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse) diff --git a/apache-httpclient-2/README.md b/apache-httpclient-2/README.md index a19112476b..05bebfaacb 100644 --- a/apache-httpclient-2/README.md +++ b/apache-httpclient-2/README.md @@ -13,5 +13,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies) - [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging) - [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient) -- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url) - More articles: [[<-- prev]](../apache-httpclient) diff --git a/apache-httpclient/README.md b/apache-httpclient/README.md index 338b416df1..08ec2a8a9c 100644 --- a/apache-httpclient/README.md +++ b/apache-httpclient/README.md @@ -8,7 +8,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Apache HttpClient – Cancel Request](https://www.baeldung.com/httpclient-cancel-request) -- [Apache HttpClient 4 Cookbook](https://www.baeldung.com/httpclient4) +- [Apache HttpClient Cookbook](https://www.baeldung.com/apache-httpclient-cookbook) - [Apache HttpClient – Follow Redirects for POST](https://www.baeldung.com/httpclient-redirect-on-http-post) - [Multipart Upload with Apache HttpClient](https://www.baeldung.com/httpclient-multipart-upload) - [Apache HttpAsyncClient Tutorial](https://www.baeldung.com/httpasyncclient-tutorial) 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 f65558906f..988a89e7af 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java @@ -21,7 +21,7 @@ public class GetRequestMockServer { public static String serviceOneUrl; public static String serviceTwoUrl; - private static int serverPort; + public static int serverPort; public static final String SERVER_ADDRESS = "127.0.0.1"; public static final String PATH_ONE = "/test1"; @@ -29,9 +29,8 @@ public class GetRequestMockServer { public static final String METHOD = "GET"; @BeforeAll - static void startServer() throws IOException, URISyntaxException { - //serverPort = getFreePort(); - serverPort = 8080; + 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; diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java index f4b9266d7e..123c51bb86 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java @@ -9,6 +9,7 @@ import java.util.concurrent.Future; import javax.net.ssl.SSLContext; +import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner; import org.junit.jupiter.api.Test; import org.apache.hc.client5.http.async.methods.SimpleHttpRequest; @@ -55,12 +56,12 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer { @Test void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException { - final HttpHost target = new HttpHost(HOST); + final HttpHost target = new HttpHost(HOST_WITH_COOKIE); final SimpleHttpRequest request = SimpleRequestBuilder.get() .setHttpHost(target) .build(); - final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault(); + final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build(); client.start(); @@ -102,30 +103,15 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer { @Test void whenUseProxyWithHttpClient_thenCorrect() throws Exception { - final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault(); + final HttpHost proxy = new HttpHost("127.0.0.1", GetRequestMockServer.serverPort); + DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); + final CloseableHttpAsyncClient client = HttpAsyncClients.custom() + .setRoutePlanner(routePlanner) + .build(); client.start(); - final HttpHost proxy = new HttpHost("127.0.0.1", 8080); - final RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); + final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,HOST_WITH_PROXY); - request.setConfig(config); - final Future future = client.execute(request, new FutureCallback<>(){ - @Override - public void completed(SimpleHttpResponse response) { - - System.out.println("responseData"); - } - - @Override - public void failed(Exception ex) { - System.out.println("Error executing HTTP request: " + ex.getMessage()); - } - - @Override - public void cancelled() { - System.out.println("HTTP request execution cancelled"); - } - }); - + final Future future = client.execute(request, null); final HttpResponse response = future.get(); assertThat(response.getCode(), equalTo(200)); client.close(); diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java new file mode 100644 index 0000000000..ae432e68f0 --- /dev/null +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java @@ -0,0 +1,77 @@ +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 dc0055c5ae..e097f9f511 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java @@ -31,7 +31,8 @@ import org.apache.http.protocol.HttpContext; import org.apache.http.ssl.SSLContexts; import org.junit.jupiter.api.Test; -class HttpAsyncClientV4LiveTest { + +class HttpAsyncClientV4LiveTest extends GetRequestMockServer { private static final String HOST = "http://www.google.com"; private static final String HOST_WITH_SSL = "https://mms.nw.ru/"; @@ -87,7 +88,7 @@ class HttpAsyncClientV4LiveTest { void whenUseProxyWithHttpClient_thenCorrect() throws Exception { final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault(); client.start(); - final HttpHost proxy = new HttpHost("127.0.0.1", 8080); + final HttpHost proxy = new HttpHost("127.0.0.1", GetRequestMockServer.serverPort); final RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); final HttpGet request = new HttpGet(HOST_WITH_PROXY); request.setConfig(config); diff --git a/apache-kafka-2/README.md b/apache-kafka-2/README.md index e86504d605..9a5f6e15ae 100644 --- a/apache-kafka-2/README.md +++ b/apache-kafka-2/README.md @@ -9,3 +9,5 @@ You can build the project from the command line using: *mvn clean install*, or i - [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running) - [Add Custom Headers to a Kafka Message](https://www.baeldung.com/java-kafka-custom-headers) - [Get Last N Messages in Apache Kafka Topic](https://www.baeldung.com/java-apache-kafka-get-last-n-messages) +- [Is a Key Required as Part of Sending Messages to Kafka?](https://www.baeldung.com/java-kafka-message-key) +- [Read Data From the Beginning Using Kafka Consumer API](https://www.baeldung.com/java-kafka-consumer-api-read) diff --git a/apache-poi-2/README.md b/apache-poi-2/README.md index e2b5160109..0132147201 100644 --- a/apache-poi-2/README.md +++ b/apache-poi-2/README.md @@ -12,4 +12,5 @@ This module contains articles about Apache POI. - [Finding the Last Row in an Excel Spreadsheet From Java](https://www.baeldung.com/java-excel-find-last-row) - [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas) - [Set the Date Format Using Apache POI](https://www.baeldung.com/java-apache-poi-date-format) +- [Replacing Variables in a Document Template with Java](https://www.baeldung.com/java-replace-pattern-word-document-doc-docx) - More articles: [[<-- prev]](../apache-poi) diff --git a/apache-poi-2/pom.xml b/apache-poi-2/pom.xml index af959292fa..9a01a76d73 100644 --- a/apache-poi-2/pom.xml +++ b/apache-poi-2/pom.xml @@ -1,7 +1,7 @@ - + 4.0.0 apache-poi-2 0.0.1-SNAPSHOT @@ -19,10 +19,15 @@ poi-ooxml ${poi.version} + + org.apache.poi + poi-scratchpad + ${poi.version} + - 5.2.0 + 5.2.3 \ No newline at end of file diff --git a/apache-poi-2/src/main/java/com/baeldung/poi/replacevariables/DocTextReplacer.java b/apache-poi-2/src/main/java/com/baeldung/poi/replacevariables/DocTextReplacer.java new file mode 100644 index 0000000000..f661551ce9 --- /dev/null +++ b/apache-poi-2/src/main/java/com/baeldung/poi/replacevariables/DocTextReplacer.java @@ -0,0 +1,38 @@ +package com.baeldung.poi.replacevariables; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.poi.hwpf.HWPFDocument; +import org.apache.poi.hwpf.usermodel.Range; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; + +public class DocTextReplacer { + + public void replaceText() throws IOException { + String filePath = getClass().getClassLoader() + .getResource("baeldung.doc") + .getPath(); + try (InputStream inputStream = new FileInputStream(filePath); POIFSFileSystem fileSystem = new POIFSFileSystem(inputStream)) { + HWPFDocument doc = new HWPFDocument(fileSystem); + doc = replaceText(doc, "Baeldung", "Hello"); + saveFile(filePath, doc); + doc.close(); + } + } + + private HWPFDocument replaceText(HWPFDocument doc, String originalText, String updatedText) { + Range range = doc.getRange(); + range.replaceText(originalText, updatedText); + return doc; + } + + private void saveFile(String filePath, HWPFDocument doc) throws IOException { + try (FileOutputStream out = new FileOutputStream(filePath)) { + doc.write(out); + } + } + +} diff --git a/apache-poi-2/src/main/java/com/baeldung/poi/replacevariables/DocxNaiveTextReplacer.java b/apache-poi-2/src/main/java/com/baeldung/poi/replacevariables/DocxNaiveTextReplacer.java new file mode 100644 index 0000000000..34c2bc43e5 --- /dev/null +++ b/apache-poi-2/src/main/java/com/baeldung/poi/replacevariables/DocxNaiveTextReplacer.java @@ -0,0 +1,63 @@ +package com.baeldung.poi.replacevariables; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; +import org.apache.poi.xwpf.usermodel.XWPFTable; +import org.apache.poi.xwpf.usermodel.XWPFTableCell; +import org.apache.poi.xwpf.usermodel.XWPFTableRow; + +public class DocxNaiveTextReplacer { + + public void replaceText() throws IOException { + String filePath = getClass().getClassLoader() + .getResource("baeldung-copy.docx") + .getPath(); + try (InputStream inputStream = new FileInputStream(filePath)) { + XWPFDocument doc = new XWPFDocument(inputStream); + doc = replaceText(doc, "Baeldung", "Hello"); + saveFile(filePath, doc); + doc.close(); + } + } + + private XWPFDocument replaceText(XWPFDocument doc, String originalText, String updatedText) { + replaceTextInParagraphs(doc.getParagraphs(), originalText, updatedText); + for (XWPFTable tbl : doc.getTables()) { + for (XWPFTableRow row : tbl.getRows()) { + for (XWPFTableCell cell : row.getTableCells()) { + replaceTextInParagraphs(cell.getParagraphs(), originalText, updatedText); + } + } + } + return doc; + } + + private void replaceTextInParagraphs(List paragraphs, String originalText, String updatedText) { + paragraphs.forEach(paragraph -> replaceTextInParagraph(paragraph, originalText, updatedText)); + } + + private void replaceTextInParagraph(XWPFParagraph paragraph, String originalText, String updatedText) { + List runs = paragraph.getRuns(); + for (XWPFRun run : runs) { + String text = run.getText(0); + if (text != null && text.contains(originalText)) { + String updatedRunText = text.replace(originalText, updatedText); + run.setText(updatedRunText, 0); + } + } + } + + private void saveFile(String filePath, XWPFDocument doc) throws IOException { + try (FileOutputStream out = new FileOutputStream(filePath)) { + doc.write(out); + } + } + +} diff --git a/apache-poi-2/src/main/java/com/baeldung/poi/replacevariables/DocxTextReplacer.java b/apache-poi-2/src/main/java/com/baeldung/poi/replacevariables/DocxTextReplacer.java new file mode 100644 index 0000000000..2d08d24a4e --- /dev/null +++ b/apache-poi-2/src/main/java/com/baeldung/poi/replacevariables/DocxTextReplacer.java @@ -0,0 +1,65 @@ +package com.baeldung.poi.replacevariables; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Objects; + +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; +import org.apache.poi.xwpf.usermodel.XWPFTable; +import org.apache.poi.xwpf.usermodel.XWPFTableCell; +import org.apache.poi.xwpf.usermodel.XWPFTableRow; + +public class DocxTextReplacer { + + public void replaceText() throws IOException { + String filePath = getClass().getClassLoader() + .getResource("baeldung.docx") + .getPath(); + try (InputStream inputStream = new FileInputStream(filePath)) { + XWPFDocument doc = new XWPFDocument(inputStream); + doc = replaceText(doc, "Baeldung", "Hello"); + saveFile(filePath, doc); + doc.close(); + } + } + + private XWPFDocument replaceText(XWPFDocument doc, String originalText, String updatedText) { + replaceTextInParagraphs(doc.getParagraphs(), originalText, updatedText); + for (XWPFTable tbl : doc.getTables()) { + for (XWPFTableRow row : tbl.getRows()) { + for (XWPFTableCell cell : row.getTableCells()) { + replaceTextInParagraphs(cell.getParagraphs(), originalText, updatedText); + } + } + } + return doc; + } + + private void replaceTextInParagraphs(List paragraphs, String originalText, String updatedText) { + paragraphs.forEach(paragraph -> replaceTextInParagraph(paragraph, originalText, updatedText)); + } + + private void replaceTextInParagraph(XWPFParagraph paragraph, String originalText, String updatedText) { + String paragraphText = paragraph.getParagraphText(); + if (paragraphText.contains(originalText)) { + String updatedParagraphText = paragraphText.replace(originalText, updatedText); + while (paragraph.getRuns().size() > 0) { + paragraph.removeRun(0); + } + XWPFRun newRun = paragraph.createRun(); + newRun.setText(updatedParagraphText); + } + } + + private void saveFile(String filePath, XWPFDocument doc) throws IOException { + try (FileOutputStream out = new FileOutputStream(filePath)) { + doc.write(out); + } + } + +} diff --git a/apache-poi-2/src/main/resources/baeldung-copy.docx b/apache-poi-2/src/main/resources/baeldung-copy.docx new file mode 100644 index 0000000000..2cb76e8ffd Binary files /dev/null and b/apache-poi-2/src/main/resources/baeldung-copy.docx differ diff --git a/apache-poi-2/src/main/resources/baeldung.doc b/apache-poi-2/src/main/resources/baeldung.doc new file mode 100644 index 0000000000..1b8474d65b Binary files /dev/null and b/apache-poi-2/src/main/resources/baeldung.doc differ diff --git a/apache-poi-2/src/main/resources/baeldung.docx b/apache-poi-2/src/main/resources/baeldung.docx new file mode 100644 index 0000000000..f0de4e057b Binary files /dev/null and b/apache-poi-2/src/main/resources/baeldung.docx differ diff --git a/apache-poi-2/src/test/java/com/baeldung/poi/replacevariables/DocTextReplacerUnitTest.java b/apache-poi-2/src/test/java/com/baeldung/poi/replacevariables/DocTextReplacerUnitTest.java new file mode 100644 index 0000000000..0c3d80a354 --- /dev/null +++ b/apache-poi-2/src/test/java/com/baeldung/poi/replacevariables/DocTextReplacerUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.poi.replacevariables; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Arrays; + +import org.apache.poi.hwpf.HWPFDocument; +import org.apache.poi.hwpf.extractor.WordExtractor; +import org.junit.jupiter.api.Test; + +class DocTextReplacerUnitTest { + + @Test + void whenReplaceText_ThenTextReplaced() throws IOException { + new DocTextReplacer().replaceText(); + + String filePath = getClass().getClassLoader() + .getResource("baeldung.doc") + .getPath(); + try (FileInputStream fis = new FileInputStream(filePath); HWPFDocument document = new HWPFDocument(fis); WordExtractor extractor = new WordExtractor(document)) { + long occurrencesOfHello = Arrays.stream(extractor.getText() + .split("\\s+")) + .filter(s -> s.contains("Hello")) + .count(); + assertEquals(5, occurrencesOfHello); + } + } + +} diff --git a/apache-poi-2/src/test/java/com/baeldung/poi/replacevariables/DocxNaiveTextReplacerUnitTest.java b/apache-poi-2/src/test/java/com/baeldung/poi/replacevariables/DocxNaiveTextReplacerUnitTest.java new file mode 100644 index 0000000000..324e63eb51 --- /dev/null +++ b/apache-poi-2/src/test/java/com/baeldung/poi/replacevariables/DocxNaiveTextReplacerUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.poi.replacevariables; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Arrays; + +import org.apache.poi.xwpf.extractor.XWPFWordExtractor; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.junit.jupiter.api.Test; + +class DocxNaiveTextReplacerUnitTest { + + @Test + void whenReplaceText_ThenTextReplaced() throws IOException { + new DocxNaiveTextReplacer().replaceText(); + + String filePath = getClass().getClassLoader() + .getResource("baeldung-copy.docx") + .getPath(); + try (FileInputStream fis = new FileInputStream(filePath); XWPFDocument document = new XWPFDocument(fis); XWPFWordExtractor extractor = new XWPFWordExtractor(document)) { + long occurrencesOfHello = Arrays.stream(extractor.getText() + .split("\\s+")) + .filter(s -> s.contains("Hello")) + .count(); + assertTrue(occurrencesOfHello < 5); + } + } + +} diff --git a/apache-poi-2/src/test/java/com/baeldung/poi/replacevariables/DocxTestReplacerUnitTest.java b/apache-poi-2/src/test/java/com/baeldung/poi/replacevariables/DocxTestReplacerUnitTest.java new file mode 100644 index 0000000000..d09f6b003d --- /dev/null +++ b/apache-poi-2/src/test/java/com/baeldung/poi/replacevariables/DocxTestReplacerUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.poi.replacevariables; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Arrays; + +import org.apache.poi.xwpf.extractor.XWPFWordExtractor; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.junit.jupiter.api.Test; + +class DocxTestReplacerUnitTest { + + @Test + void whenReplaceText_ThenTextReplaced() throws IOException { + new DocxTextReplacer().replaceText(); + + String filePath = getClass().getClassLoader() + .getResource("baeldung.docx") + .getPath(); + try (FileInputStream fis = new FileInputStream(filePath); XWPFDocument document = new XWPFDocument(fis); XWPFWordExtractor extractor = new XWPFWordExtractor(document)) { + long occurrencesOfHello = Arrays.stream(extractor.getText() + .split("\\s+")) + .filter(s -> s.contains("Hello")) + .count(); + assertEquals(5, occurrencesOfHello); + } + } + +} diff --git a/axon/README.md b/axon/README.md index 28b559b9ea..a781ccecc1 100644 --- a/axon/README.md +++ b/axon/README.md @@ -21,4 +21,4 @@ Two scripts are included to easily start middleware using Docker matching the pr - [Snapshotting Aggregates in Axon](https://www.baeldung.com/axon-snapshotting-aggregates) - [Dispatching Queries in Axon Framework](https://www.baeldung.com/axon-query-dispatching) - [Persisting the Query Model](https://www.baeldung.com/axon-persisting-query-model) -- [Using and Testing Axon Applications via REST](https://www.baeldung.com/using-and-testing-axon-applications-via-rest) +- [Using and Testing Axon Applications via REST](https://www.baeldung.com/axon-using-and-testing-rest) diff --git a/checker-framework/pom.xml b/checker-framework/pom.xml index a348745343..d8a44ec0c9 100644 --- a/checker-framework/pom.xml +++ b/checker-framework/pom.xml @@ -19,24 +19,13 @@ org.checkerframework checker-qual - ${checker-qual.version} + ${checker.version} org.checkerframework checker ${checker.version} - - org.checkerframework - jdk8 - ${jdk8.version} - - - - org.checkerframework - compiler - ${checkerframework.compiler.version} - @@ -45,32 +34,34 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - ${java.version} - ${java.version} - - - - 10000 - 10000 - + true + -Xlint:all + true + + + org.checkerframework + checker + ${checker.version} + + - org.checkerframework.checker.nullness.NullnessChecker org.checkerframework.checker.interning.InterningChecker org.checkerframework.checker.fenum.FenumChecker org.checkerframework.checker.formatter.FormatterChecker org.checkerframework.checker.regex.RegexChecker - - -AprintErrorStack - - - -Xbootclasspath/p:${annotatedJdk} - - - - + -Awarns + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED @@ -78,14 +69,7 @@ - - ${org.checkerframework:jdk8:jar} - - - 2.3.1 - 2.3.1 - 2.3.1 - 2.3.1 + 3.35.0 \ No newline at end of file diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/daysinmonth/DaysInMonthUtils.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/daysinmonth/DaysInMonthUtils.java new file mode 100644 index 0000000000..93140e7459 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/daysinmonth/DaysInMonthUtils.java @@ -0,0 +1,21 @@ +package com.baeldung.daysinmonth; + +import java.time.YearMonth; +import java.util.Calendar; + +public class DaysInMonthUtils { + + public int getDaysInMonthWithYearOfMonth(int month, int year) { + YearMonth yearMonth = YearMonth.of(year, month); + return yearMonth.lengthOfMonth(); + } + + public int getDaysInMonthWithCalendar(int month, int year) { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.DAY_OF_MONTH, 1); + calendar.set(Calendar.YEAR, year); + calendar.set(Calendar.MONTH, month - 1); + return calendar.getActualMaximum(Calendar.DATE); + } + +} diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/daysinmonth/DaysInMonthUtilsUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/daysinmonth/DaysInMonthUtilsUnitTest.java new file mode 100644 index 0000000000..ffaf231f7b --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/daysinmonth/DaysInMonthUtilsUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.daysinmonth; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class DaysInMonthUtilsUnitTest { + + @Test + void whenGetDaysInMonthWithYearOfMonth_thenCorrectResult() { + assertEquals(31, new DaysInMonthUtils().getDaysInMonthWithYearOfMonth(3, 2024)); + assertEquals(30, new DaysInMonthUtils().getDaysInMonthWithYearOfMonth(11, 1999)); + assertEquals(28, new DaysInMonthUtils().getDaysInMonthWithYearOfMonth(2, 2025)); + assertEquals(29, new DaysInMonthUtils().getDaysInMonthWithYearOfMonth(2, 2004)); + } + + @Test + void whenGetDaysInMonthWithCalendar_thenCorrectResult() { + assertEquals(31, new DaysInMonthUtils().getDaysInMonthWithCalendar(3, 2024)); + assertEquals(30, new DaysInMonthUtils().getDaysInMonthWithCalendar(11, 1999)); + assertEquals(28, new DaysInMonthUtils().getDaysInMonthWithCalendar(2, 2025)); + assertEquals(29, new DaysInMonthUtils().getDaysInMonthWithCalendar(2, 2004)); + } + +} diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Article.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Article.java similarity index 95% rename from core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Article.java rename to core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Article.java index 3cd2a00da1..7b9ef00078 100644 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Article.java +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Article.java @@ -1,4 +1,4 @@ -package com.baeldung.spliteratorAPI; +package com.baeldung.spliterator; import java.util.List; diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Author.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Author.java similarity index 94% rename from core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Author.java rename to core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Author.java index 18bbbd073e..ae204657b5 100644 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Author.java +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Author.java @@ -1,4 +1,4 @@ -package com.baeldung.spliteratorAPI; +package com.baeldung.spliterator; public class Author { private String name; diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Executor.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Executor.java similarity index 55% rename from core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Executor.java rename to core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Executor.java index dd124948d8..3dc2fa06bb 100644 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Executor.java +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Executor.java @@ -1,7 +1,5 @@ -package com.baeldung.spliteratorAPI; +package com.baeldung.spliterator; -import java.util.List; -import java.util.stream.Collectors; import java.util.stream.Stream; public class Executor { @@ -11,9 +9,4 @@ public class Executor { RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine); return wordCounter.getCounter(); } - - public static List
generateElements() { - return Stream.generate(() -> new Article("Java")).limit(35000).collect(Collectors.toList()); - } - } \ No newline at end of file diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorCounter.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorCounter.java similarity index 95% rename from core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorCounter.java rename to core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorCounter.java index 282c0be727..8800eac55b 100644 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorCounter.java +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorCounter.java @@ -1,4 +1,4 @@ -package com.baeldung.spliteratorAPI; +package com.baeldung.spliterator; public class RelatedAuthorCounter { private final int counter; diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorSpliterator.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorSpliterator.java similarity index 96% rename from core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorSpliterator.java rename to core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorSpliterator.java index 094638da37..93c83b8127 100644 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorSpliterator.java +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorSpliterator.java @@ -1,4 +1,4 @@ -package com.baeldung.spliteratorAPI; +package com.baeldung.spliterator; import java.util.List; import java.util.Spliterator; diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Task.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Task.java deleted file mode 100644 index 06a124cc98..0000000000 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Task.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.spliteratorAPI; - -import java.util.Spliterator; -import java.util.concurrent.Callable; - -public class Task implements Callable { - private Spliterator
spliterator; - private final static String SUFFIX = "- published by Baeldung"; - - public Task(Spliterator
spliterator) { - this.spliterator = spliterator; - } - - @Override - public String call() { - int current = 0; - while (spliterator.tryAdvance(article -> { - article.setName(article.getName() - .concat(SUFFIX)); - })) { - current++; - } - ; - return Thread.currentThread() - .getName() + ":" + current; - } -} diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/spliterator/ExecutorUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/spliterator/ExecutorUnitTest.java new file mode 100644 index 0000000000..4628f95481 --- /dev/null +++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/spliterator/ExecutorUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.spliterator; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Spliterator; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +import org.junit.Before; +import org.junit.Test; + +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class ExecutorUnitTest { + Article article; + Stream stream; + Spliterator spliterator; + + @Before + public void init() { + article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), + new Author("Alice", 1), new Author("Mike", 0), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), + new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0); + + spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors()); + } + + @Test + public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() { + Stream stream2 = StreamSupport.stream(spliterator, true); + assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9); + } + + @Test + public void givenAStreamOfArticles_whenProcessedSequentiallyWithSpliterator_ProducessRightOutput() { + List
articles = Stream.generate(() -> new Article("Java")) + .limit(35000) + .collect(Collectors.toList()); + + Spliterator
spliterator = articles.spliterator(); + while (spliterator.tryAdvance(article -> article.setName(article.getName() + .concat("- published by Baeldung")))) + ; + + articles.forEach(article -> assertThat(article.getName()).isEqualTo("Java- published by Baeldung")); + } + + @Test + public void givenAStreamOfArticle_whenProcessedUsingTrySplit_thenSplitIntoEqualHalf() { + List
articles = Stream.generate(() -> new Article("Java")) + .limit(35000) + .collect(Collectors.toList()); + + Spliterator
split1 = articles.spliterator(); + Spliterator
split2 = split1.trySplit(); + + log.info("Size: " + split1.estimateSize()); + log.info("Characteristics: " + split1.characteristics()); + + List
articlesListOne = new ArrayList<>(); + List
articlesListTwo = new ArrayList<>(); + + split1.forEachRemaining(articlesListOne::add); + split2.forEachRemaining(articlesListTwo::add); + + assertThat(articlesListOne.size()).isEqualTo(17500); + assertThat(articlesListTwo.size()).isEqualTo(17500); + + assertThat(articlesListOne).doesNotContainAnyElementsOf(articlesListTwo); + } +} diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java deleted file mode 100644 index 6981898500..0000000000 --- a/core-java-modules/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.spliteratorAPI; - -import java.util.Arrays; -import java.util.Spliterator; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; - -import static org.assertj.core.api.Assertions.*; -import org.junit.Before; -import org.junit.Test; - -public class ExecutorUnitTest { - Article article; - Stream stream; - Spliterator spliterator; - Spliterator
split1; - Spliterator
split2; - - @Before - public void init() { - article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1), - new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), - new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), - new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), - new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), - new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0); - stream = article.getListOfAuthors().stream(); - split1 = Executor.generateElements().spliterator(); - split2 = split1.trySplit(); - spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors()); - } - - @Test - public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() { - Stream stream2 = StreamSupport.stream(spliterator, true); - assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9); - } - - @Test - public void givenSpliterator_whenAppliedToAListOfArticle_thenSplittedInHalf() { - assertThat(new Task(split1).call()).containsSequence(Executor.generateElements().size() / 2 + ""); - assertThat(new Task(split2).call()).containsSequence(Executor.generateElements().size() / 2 + ""); - } -} diff --git a/core-java-modules/core-java-arrays-guides/README.md b/core-java-modules/core-java-arrays-guides/README.md index ed10df5b00..0af77980af 100644 --- a/core-java-modules/core-java-arrays-guides/README.md +++ b/core-java-modules/core-java-arrays-guides/README.md @@ -5,7 +5,7 @@ This module contains complete guides about arrays in Java ### Relevant Articles: - [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) - [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays) -- [What is [Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array) +- [What Is [Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array) - [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception) - [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array) - [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size) diff --git a/core-java-modules/core-java-arrays-multidimensional/README.md b/core-java-modules/core-java-arrays-multidimensional/README.md index d92747a4fb..d162eca24a 100644 --- a/core-java-modules/core-java-arrays-multidimensional/README.md +++ b/core-java-modules/core-java-arrays-multidimensional/README.md @@ -3,5 +3,5 @@ This module contains articles about multidimensional arrays in Java ### Relevant Articles: -- [Multi-Dimensional Arrays In Java](https://www.baeldung.com/java-jagged-arrays) -- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array) \ No newline at end of file +- [Multi-Dimensional Arrays in Java](https://www.baeldung.com/java-jagged-arrays) +- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array) diff --git a/core-java-modules/core-java-arrays-operations-advanced/README.md b/core-java-modules/core-java-arrays-operations-advanced/README.md index 808696b580..1f55338644 100644 --- a/core-java-modules/core-java-arrays-operations-advanced/README.md +++ b/core-java-modules/core-java-arrays-operations-advanced/README.md @@ -7,7 +7,7 @@ This module contains articles about advanced operations on arrays in Java. They - [How to Copy an Array in Java](https://www.baeldung.com/java-array-copy) - [Arrays.deepEquals](https://www.baeldung.com/java-arrays-deepequals) - [Find Sum and Average in a Java Array](https://www.baeldung.com/java-array-sum-average) -- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection) +- [Intersection Between Two Integer Arrays](https://www.baeldung.com/java-array-intersection) - [Comparing Arrays in Java](https://www.baeldung.com/java-comparing-arrays) - [Concatenate Two Arrays in Java](https://www.baeldung.com/java-concatenate-arrays) - [Performance of System.arraycopy() vs. Arrays.copyOf()](https://www.baeldung.com/java-system-arraycopy-arrays-copyof-performance) diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arrayconcat/CombiningByteArrays.java b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arrayconcat/CombiningByteArrays.java new file mode 100644 index 0000000000..d05cafc677 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arrayconcat/CombiningByteArrays.java @@ -0,0 +1,49 @@ +package com.baeldung.arrayconcat; + +import com.google.common.primitives.Bytes; +import org.apache.commons.lang3.ArrayUtils; + +import java.nio.ByteBuffer; + +public class CombiningByteArrays { + + public byte[] combineArraysUsingArrayCopy(byte[] first, byte[] second) { + byte[] combined = new byte[first.length + second.length]; + + System.arraycopy(first, 0, combined, 0, first.length); + System.arraycopy(second, 0, combined, first.length, second.length); + return combined; + } + + public byte[] combineArraysUsingByteBuffer(byte[] first, byte[] second, byte[] third) { + byte[] combined = new byte[first.length + second.length + third.length]; + + ByteBuffer buffer = ByteBuffer.wrap(combined); + buffer.put(first); + buffer.put(second); + buffer.put(third); + return buffer.array(); + } + + public byte[] combineArraysUsingCustomMethod(byte[] first, byte[] second) { + byte[] combined = new byte[first.length + second.length]; + + for (int i = 0; i < combined.length; ++i) { + combined[i] = i < first.length ? first[i] : second[i - first.length]; + } + return combined; + } + + public byte[] combineArraysUsingGuava(byte[] first, byte[] second, byte[] third) { + byte[] combined = Bytes.concat(first, second, third); + + return combined; + } + + public byte[] combineArraysUsingApacheCommons(byte[] first, byte[] second) { + byte[] combined = ArrayUtils.addAll(first, second); + + return combined; + } + +} diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arrayconcat/CombiningByteArraysUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arrayconcat/CombiningByteArraysUnitTest.java new file mode 100644 index 0000000000..2aa06b7570 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arrayconcat/CombiningByteArraysUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.arrayconcat; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertArrayEquals; + +public class CombiningByteArraysUnitTest { + + CombiningByteArrays combiningByteArrays; + + @Before + public void init() { + combiningByteArrays = new CombiningByteArrays(); + } + + @Test + public void givenTwoArrays_whenCombinedUsingArraysCopy_thenArrayContainingAllElementsMustBeReturned() { + byte[] first = {69, 121, 101, 45, 62, 118, 114}; + byte[] second = {58, 120, 100, 46, 64, 114, 103, 117}; + + byte[] combined = combiningByteArrays.combineArraysUsingArrayCopy(first, second); + + byte[] expectedArray = {69, 121, 101, 45, 62, 118, 114, 58, 120, 100, 46, 64, 114, 103, 117}; + assertArrayEquals(expectedArray, combined); + } + + @Test + public void givenTwoArrays_whenCombinedUsingByteBuffer_thenArrayContainingAllElementsMustBeReturned() { + byte[] first = {69, 121, 101, 45}; + byte[] second = {64, 114, 103, 117}; + byte[] third = {11, 22, 33}; + + byte[] combined = combiningByteArrays.combineArraysUsingByteBuffer(first, second, third); + + byte[] expectedArray = {69, 121, 101, 45, 64, 114, 103, 117, 11, 22, 33}; + assertArrayEquals(expectedArray, combined); + } + + @Test + public void givenTwoArrays_whenCombinedUsingCustomMethod_thenArrayContainingAllElementsMustBeReturned() { + byte[] first = {101, 45, 62 }; + byte[] second = {58, 120, 100, 46, 64, 114}; + + byte[] combined = combiningByteArrays.combineArraysUsingCustomMethod(first, second); + + byte[] expectedArray = {101, 45, 62, 58, 120, 100, 46, 64, 114}; + assertArrayEquals(expectedArray, combined); + } + + @Test + public void givenTwoArrays_whenCombinedUsingGuava_thenArrayContainingAllElementsMustBeReturned() { + byte[] first = {69, 121, 101, 118, 114}; + byte[] second = {58, 120, 114, 103, 117}; + byte[] third = {11, 22, 33}; + + byte[] combined = combiningByteArrays.combineArraysUsingGuava(first, second, third); + + byte[] expectedArray = {69, 121, 101, 118, 114, 58, 120, 114, 103, 117, 11, 22, 33}; + assertArrayEquals(expectedArray, combined); + } + + @Test + public void givenTwoArrays_whenCombinedUsingApacheCommons_thenArrayContainingAllElementsMustBeReturned() { + byte[] first = {45, 62, 114}; + byte[] second = {58, 120, 100}; + + byte[] combined = combiningByteArrays.combineArraysUsingApacheCommons(first, second); + + byte[] expectedArray = {45, 62, 114, 58, 120, 100}; + assertArrayEquals(expectedArray, combined); + } +} diff --git a/core-java-modules/core-java-collections-2/README.md b/core-java-modules/core-java-collections-2/README.md index 5a9bae8f9f..fa4880bade 100644 --- a/core-java-modules/core-java-collections-2/README.md +++ b/core-java-modules/core-java-collections-2/README.md @@ -8,7 +8,7 @@ - [Join and Split Arrays and Collections in Java](https://www.baeldung.com/java-join-and-split) - [Java – Combine Multiple Collections](https://www.baeldung.com/java-combine-multiple-collections) - [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections) -- [Shuffling Collections In Java](https://www.baeldung.com/java-shuffle-collection) +- [Shuffling Collections in Java](https://www.baeldung.com/java-shuffle-collection) - [Sorting in Java](https://www.baeldung.com/java-sorting) - [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size) - [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections) diff --git a/core-java-modules/core-java-collections-conversions/README.md b/core-java-modules/core-java-collections-conversions/README.md index 5dd1848ce0..21fe45a8ec 100644 --- a/core-java-modules/core-java-collections-conversions/README.md +++ b/core-java-modules/core-java-collections-conversions/README.md @@ -3,7 +3,7 @@ This module contains articles about conversions among Collection types and arrays in Java. ### Relevant Articles: -- [Converting between an Array and a List in Java](https://www.baeldung.com/convert-array-to-list-and-list-to-array) +- [Converting Between an Array and a List in Java](https://www.baeldung.com/convert-array-to-list-and-list-to-array) - [Converting Between an Array and a Set in Java](https://www.baeldung.com/convert-array-to-set-and-set-to-array) - [Convert a Map to an Array, List or Set in Java](https://www.baeldung.com/convert-map-values-to-array-list-set) - [Converting a List to String in Java](https://www.baeldung.com/java-list-to-string) diff --git a/core-java-modules/core-java-collections-list-2/README.md b/core-java-modules/core-java-collections-list-2/README.md index 2e43f610a9..37e8ab0ee2 100644 --- a/core-java-modules/core-java-collections-list-2/README.md +++ b/core-java-modules/core-java-collections-list-2/README.md @@ -3,8 +3,8 @@ This module contains articles about the Java List collection ### Relevant Articles: -- [Check If Two Lists are Equal in Java](https://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) -- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items) +- [Check if Two Lists Are Equal in Java](https://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) +- [Java 8 Streams: Find Items From One List Based on Values From Another List](https://www.baeldung.com/java-streams-find-list-items) - [A Guide to the Java LinkedList](https://www.baeldung.com/java-linkedlist) - [Java List UnsupportedOperationException](https://www.baeldung.com/java-list-unsupported-operation-exception) - [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line) diff --git a/core-java-modules/core-java-collections-list-5/README.md b/core-java-modules/core-java-collections-list-5/README.md index 31688bc9b1..947cf234b9 100644 --- a/core-java-modules/core-java-collections-list-5/README.md +++ b/core-java-modules/core-java-collections-list-5/README.md @@ -7,3 +7,6 @@ This module contains articles about the Java List collection - [Finding All Duplicates in a List in Java](https://www.baeldung.com/java-list-find-duplicates) - [Moving Items Around in an Arraylist](https://www.baeldung.com/java-arraylist-move-items) - [Check if a List Contains an Element From Another List in Java](https://www.baeldung.com/java-check-elements-between-lists) +- [Array vs. List Performance in Java](https://www.baeldung.com/java-array-vs-list-performance) +- [Set Default Value for Elements in List](https://www.baeldung.com/java-list-set-default-values) +- [Get Unique Values From an ArrayList In Java](https://www.baeldung.com/java-unique-values-arraylist) diff --git a/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/uniqueelements/UniqueElementsInListUnitTest.java b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/uniqueelements/UniqueElementsInListUnitTest.java new file mode 100644 index 0000000000..348a7d8807 --- /dev/null +++ b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/uniqueelements/UniqueElementsInListUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.java.uniqueelements; + +import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; + +import org.junit.jupiter.api.Test; + +public class UniqueElementsInListUnitTest { + // @formatter:off + private static final List MY_LIST = Arrays.asList(new String[]{ + "Microsoft Windows", + "Mac OS", + "GNU Linux", + "Free BSD", + "GNU Linux", + "Mac OS"}); + // @formatter:on + + @Test + void whenConvertToSet_thenGetExpectedResult() { + List result = new ArrayList<>(new HashSet<>(MY_LIST)); + assertThat(result).containsExactlyInAnyOrder("Free BSD", "Microsoft Windows", "Mac OS", "GNU Linux"); + + result = new ArrayList<>(new LinkedHashSet<>(MY_LIST)); + assertThat(result).containsExactly("Microsoft Windows", "Mac OS", "GNU Linux", "Free BSD"); + } + + @Test + void whenUsingStream_thenGetExpectedResult() { + List result = MY_LIST.stream() + .distinct() + .collect(toList()); + assertThat(result).containsExactly("Microsoft Windows", "Mac OS", "GNU Linux", "Free BSD"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list/README.md b/core-java-modules/core-java-collections-list/README.md index 5144757c80..919c64270b 100644 --- a/core-java-modules/core-java-collections-list/README.md +++ b/core-java-modules/core-java-collections-list/README.md @@ -4,8 +4,8 @@ This module contains articles about the Java List collection ### Relevant Articles: - [Java – Get Random Item/Element From a List](http://www.baeldung.com/java-random-list-element) -- [Removing all Nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list) -- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list) +- [Removing All Nulls From a List in Java](https://www.baeldung.com/java-remove-nulls-from-list) +- [Removing All Duplicates From a List in Java](https://www.baeldung.com/java-remove-duplicates-from-list) - [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list) - [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards) - [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list) diff --git a/core-java-modules/core-java-collections-maps-2/README.md b/core-java-modules/core-java-collections-maps-2/README.md index f49ba25c8c..befe6ab410 100644 --- a/core-java-modules/core-java-collections-maps-2/README.md +++ b/core-java-modules/core-java-collections-maps-2/README.md @@ -8,7 +8,7 @@ This module contains articles about Map data structures in Java. - [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) - [Guide to WeakHashMap in Java](https://www.baeldung.com/java-weakhashmap) - [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion) -- [Iterate over a Map in Java](https://www.baeldung.com/java-iterate-map) +- [Iterate Over a Map in Java](https://www.baeldung.com/java-iterate-map) - [Merging Two Maps with Java 8](https://www.baeldung.com/java-merge-maps) - [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort) - [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max) diff --git a/core-java-modules/core-java-collections-maps-6/README.md b/core-java-modules/core-java-collections-maps-6/README.md index fc12a1bb25..0b5d69e8f6 100644 --- a/core-java-modules/core-java-collections-maps-6/README.md +++ b/core-java-modules/core-java-collections-maps-6/README.md @@ -1,2 +1,5 @@ ## Relevant Articles - [Copying All Keys and Values From One Hashmap Onto Another Without Replacing Existing Keys and Values](https://www.baeldung.com/java-copy-hashmap-no-changes) +- [Convert Hashmap to JSON Object in Java](https://www.baeldung.com/java-convert-hashmap-to-json-object) +- [Converting Map to Map in Java](https://www.baeldung.com/java-converting-map-string-object-to-string-string) +- [Converting Object To Map in Java](https://www.baeldung.com/java-convert-object-to-map) diff --git a/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/generictypeconversion/ConvertMapWithTypeParamUnitTest.java b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/generictypeconversion/ConvertMapWithTypeParamUnitTest.java new file mode 100644 index 0000000000..9548abd622 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/generictypeconversion/ConvertMapWithTypeParamUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.map.generictypeconversion; + +import static java.util.stream.Collectors.toMap; +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 java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import com.google.common.collect.Maps; + +public class ConvertMapWithTypeParamUnitTest { + private static final Map MAP1 = Maps.newHashMap(); + + static { + MAP1.put("K01", "GNU Linux"); + MAP1.put("K02", "Mac OS"); + MAP1.put("K03", "MS Windows"); + } + + private static final Map EXPECTED_MAP1 = Maps.newHashMap(); + + static { + EXPECTED_MAP1.put("K01", "GNU Linux"); + EXPECTED_MAP1.put("K02", "Mac OS"); + EXPECTED_MAP1.put("K03", "MS Windows"); + } + + private static final Map MAP2 = Maps.newHashMap(); + + static { + MAP2.put("K01", "GNU Linux"); + MAP2.put("K02", "Mac OS"); + MAP2.put("K03", BigDecimal.ONE); + } + + private static final Map EXPECTED_MAP2_STRING_VALUES = Maps.newHashMap(); + + static { + EXPECTED_MAP2_STRING_VALUES.put("K01", "GNU Linux"); + EXPECTED_MAP2_STRING_VALUES.put("K02", "Mac OS"); + EXPECTED_MAP2_STRING_VALUES.put("K03", "1"); + } + + @Test + void whenCastingToMap_shouldGetExpectedResult() { + Map result = (Map) MAP1; + assertEquals(EXPECTED_MAP1, result); + + Map result2 = (Map) MAP2; + assertFalse(result2.get("K03") instanceof String); + } + + Map checkAndTransform(Map inputMap) { + Map result = new HashMap<>(); + for (Map.Entry entry : inputMap.entrySet()) { + try { + result.put(entry.getKey(), (String) entry.getValue()); + } catch (ClassCastException e) { + throw e; + } + } + return result; + } + + @Test + void whenCheckAndTransform_shouldGetExpectedResult() { + Map result = checkAndTransform(MAP1); + assertEquals(EXPECTED_MAP1, result); + + assertThrows(ClassCastException.class, () -> checkAndTransform(MAP2)); + } + + @Test + void whenUsingStringValueOf_shouldGetExpectedResult() { + Map result = MAP1.entrySet() + .stream() + .collect(toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue()))); + + assertEquals(EXPECTED_MAP1, result); + + Map result2 = MAP2.entrySet() + .stream() + .collect(toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue()))); + + assertEquals(EXPECTED_MAP2_STRING_VALUES, result2); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-advanced-3/README.md b/core-java-modules/core-java-concurrency-advanced-3/README.md index 9495d5f479..ab541c73ae 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/README.md +++ b/core-java-modules/core-java-concurrency-advanced-3/README.md @@ -15,5 +15,5 @@ This module contains articles about advanced topics about multithreading with co - [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency) - [Introduction to Lock-Free Data Structures with Java Examples](https://www.baeldung.com/lock-free-programming) - [Introduction to Exchanger in Java](https://www.baeldung.com/java-exchanger) -- [Why Not To Start A Thread In The Constructor?](https://www.baeldung.com/java-thread-constructor) +- [Why Not to Start a Thread in the Constructor?](https://www.baeldung.com/java-thread-constructor) - [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2) diff --git a/core-java-modules/core-java-concurrency-basic-2/README.md b/core-java-modules/core-java-concurrency-basic-2/README.md index 455ff52081..91b84e3749 100644 --- a/core-java-modules/core-java-concurrency-basic-2/README.md +++ b/core-java-modules/core-java-concurrency-basic-2/README.md @@ -7,7 +7,7 @@ This module contains articles about basic Java concurrency - [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) - [Difference Between Wait and Sleep in Java](https://www.baeldung.com/java-wait-and-sleep) - [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference) -- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe) +- [Why Are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe) - [How to Stop Execution After a Certain Time in Java](https://www.baeldung.com/java-stop-execution-after-certain-time) - [How to Get the Number of Threads in a Java Process](https://www.baeldung.com/java-get-number-of-threads) - [Set the Name of a Thread in Java](https://www.baeldung.com/java-set-thread-name) 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 da148599b0..619a68cdef 100644 --- a/core-java-modules/core-java-concurrency-basic-3/README.md +++ b/core-java-modules/core-java-concurrency-basic-3/README.md @@ -7,4 +7,5 @@ This module contains articles about basic Java concurrency. - [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception) - [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await) - [Is CompletableFuture Non-blocking?](https://www.baeldung.com/java-completablefuture-non-blocking) +- [Returning a Value After Finishing Thread’s Job in Java](https://www.baeldung.com/java-return-value-after-thread-finish) - [[<-- Prev]](../core-java-concurrency-basic-2) diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/FactorialCalculator.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/FactorialCalculator.java new file mode 100644 index 0000000000..4d0c5ab69d --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/FactorialCalculator.java @@ -0,0 +1,29 @@ +package com.baeldung.concurrent.threadreturnvalue.task; + +import java.math.BigInteger; + +public class FactorialCalculator { + + public static BigInteger factorial(BigInteger end) { + BigInteger start = BigInteger.ONE; + BigInteger res = BigInteger.ONE; + + for (int i = start.add(BigInteger.ONE) + .intValue(); i <= end.intValue(); i++) { + res = res.multiply(BigInteger.valueOf(i)); + } + + return res; + } + + public static BigInteger factorial(BigInteger start, BigInteger end) { + BigInteger res = start; + + for (int i = start.add(BigInteger.ONE) + .intValue(); i <= end.intValue(); i++) { + res = res.multiply(BigInteger.valueOf(i)); + } + + return res; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/callable/CallableExecutor.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/callable/CallableExecutor.java new file mode 100644 index 0000000000..260870d0a7 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/callable/CallableExecutor.java @@ -0,0 +1,38 @@ +package com.baeldung.concurrent.threadreturnvalue.task.callable; + +import java.math.BigInteger; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class CallableExecutor { + + public BigInteger execute(List tasks) { + + BigInteger result = BigInteger.ZERO; + + ExecutorService cachedPool = Executors.newCachedThreadPool(); + + List> futures; + + try { + futures = cachedPool.invokeAll(tasks); + } catch (InterruptedException e) { + // exception handling example + throw new RuntimeException(e); + } + + for (Future future : futures) { + try { + result = result.add(future.get()); + } catch (InterruptedException | ExecutionException e) { + // exception handling example + throw new RuntimeException(e); + } + } + + return result; + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/callable/CallableFactorialTask.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/callable/CallableFactorialTask.java new file mode 100644 index 0000000000..4c38d2fb19 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/callable/CallableFactorialTask.java @@ -0,0 +1,20 @@ +package com.baeldung.concurrent.threadreturnvalue.task.callable; + +import static com.baeldung.concurrent.threadreturnvalue.task.FactorialCalculator.factorial; + +import java.math.BigInteger; +import java.util.concurrent.Callable; + +public class CallableFactorialTask implements Callable { + + private final Integer value; + + public CallableFactorialTask(int value) { + this.value = value; + } + + @Override + public BigInteger call() { + return factorial(BigInteger.valueOf(value)); + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/fork/ForkExecutor.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/fork/ForkExecutor.java new file mode 100644 index 0000000000..ed199973ce --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/fork/ForkExecutor.java @@ -0,0 +1,34 @@ +package com.baeldung.concurrent.threadreturnvalue.task.fork; + +import java.math.BigInteger; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.Future; + +public class ForkExecutor { + + private final ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); + + public BigInteger execute(ForkFactorialTask forkFactorial) { + return forkJoinPool.invoke(forkFactorial); + } + + public BigInteger execute(List> forkFactorials) { + List> futures = forkJoinPool.invokeAll(forkFactorials); + + BigInteger result = BigInteger.ZERO; + + for (Future future : futures) { + try { + result = result.add(future.get()); + } catch (InterruptedException | ExecutionException e) { + // exception handling example + throw new RuntimeException(e); + } + } + + return result; + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/fork/ForkFactorialTask.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/fork/ForkFactorialTask.java new file mode 100644 index 0000000000..b45a88655c --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/threadreturnvalue/task/fork/ForkFactorialTask.java @@ -0,0 +1,43 @@ +package com.baeldung.concurrent.threadreturnvalue.task.fork; + +import static com.baeldung.concurrent.threadreturnvalue.task.FactorialCalculator.factorial; + +import java.math.BigInteger; +import java.util.concurrent.RecursiveTask; + +public class ForkFactorialTask extends RecursiveTask { + + private final int start; + private final int end; + private final int threshold; + + public ForkFactorialTask(int end, int threshold) { + this.start = 1; + this.end = end; + this.threshold = threshold; + } + + public ForkFactorialTask(int start, int end, int threshold) { + this.start = start; + this.end = end; + this.threshold = threshold; + } + + @Override + protected BigInteger compute() { + + BigInteger sum = BigInteger.ONE; + + if (end - start > threshold) { + + int middle = (end + start) / 2; + + return sum.multiply(new ForkFactorialTask(start, middle, threshold).fork() + .join() + .multiply(new ForkFactorialTask(middle + 1, end, threshold).fork() + .join())); + } + + return sum.multiply(factorial(BigInteger.valueOf(start), BigInteger.valueOf(end))); + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/threadreturnvalue/callable/CallableUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/threadreturnvalue/callable/CallableUnitTest.java new file mode 100644 index 0000000000..d9271b7603 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/threadreturnvalue/callable/CallableUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.concurrent.threadreturnvalue.callable; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.math.BigInteger; +import java.util.Arrays; + +import org.junit.jupiter.api.Test; + +import com.baeldung.concurrent.threadreturnvalue.task.callable.CallableExecutor; +import com.baeldung.concurrent.threadreturnvalue.task.callable.CallableFactorialTask; + +public class CallableUnitTest { + + private final CallableExecutor callableExecutor = new CallableExecutor(); + + @Test + void givenCallableExecutor_whenExecuteFactorial_thenResultOk() { + BigInteger result = callableExecutor.execute(Arrays.asList(new CallableFactorialTask(5), new CallableFactorialTask(3))); + assertEquals(BigInteger.valueOf(126), result); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/threadreturnvalue/completableFuture/CompletableFutureUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/threadreturnvalue/completableFuture/CompletableFutureUnitTest.java new file mode 100644 index 0000000000..4322aa6847 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/threadreturnvalue/completableFuture/CompletableFutureUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.concurrent.threadreturnvalue.completableFuture; + +import static com.baeldung.concurrent.threadreturnvalue.task.FactorialCalculator.factorial; +import static java.util.concurrent.CompletableFuture.allOf; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.math.BigInteger; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; + +import org.junit.jupiter.api.Test; + +public class CompletableFutureUnitTest { + + @Test + void givenCompletableFuture_whenSupplyAsyncFactorial_thenResultOk() throws ExecutionException, InterruptedException { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> factorial(BigInteger.valueOf(10))); + assertEquals(BigInteger.valueOf(3628800), completableFuture.get()); + } + + @Test + void givenCompletableFuture_whenComposeTasks_thenResultOk() throws ExecutionException, InterruptedException { + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> factorial(BigInteger.valueOf(3))) + .thenCompose(inputFromFirstTask -> CompletableFuture.supplyAsync(() -> factorial(inputFromFirstTask))); + assertEquals(BigInteger.valueOf(720), completableFuture.get()); + } + + @Test + void givenCompletableFuture_whenAllOfTasks_thenResultOk() { + CompletableFuture asyncTask1 = CompletableFuture.supplyAsync(() -> BigInteger.valueOf(5)); + CompletableFuture asyncTask2 = CompletableFuture.supplyAsync(() -> "3"); + + BigInteger result = allOf(asyncTask1, asyncTask2).thenApplyAsync(fn -> factorial(asyncTask1.join()).add(factorial(new BigInteger(asyncTask2.join()))), Executors.newFixedThreadPool(1)) + .join(); + + assertEquals(BigInteger.valueOf(126), result); + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/threadreturnvalue/fork/ForkUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/threadreturnvalue/fork/ForkUnitTest.java new file mode 100644 index 0000000000..5012fc3745 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/threadreturnvalue/fork/ForkUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.concurrent.threadreturnvalue.fork; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.math.BigInteger; +import java.util.Arrays; + +import org.junit.jupiter.api.Test; + +import com.baeldung.concurrent.threadreturnvalue.task.callable.CallableFactorialTask; +import com.baeldung.concurrent.threadreturnvalue.task.fork.ForkExecutor; +import com.baeldung.concurrent.threadreturnvalue.task.fork.ForkFactorialTask; + +public class ForkUnitTest { + + private final ForkExecutor forkExecutor = new ForkExecutor(); + + @Test + void givenForkExecutor_whenExecuteRecursiveTask_thenResultOk() { + assertEquals(BigInteger.valueOf(3628800), forkExecutor.execute(new ForkFactorialTask(10, 5))); + } + + @Test + void givenForkExecutor_whenExecuteCallable_thenResultOk() { + assertEquals(BigInteger.valueOf(126), forkExecutor.execute(Arrays.asList(new CallableFactorialTask(5), new CallableFactorialTask(3)))); + } +} diff --git a/core-java-modules/core-java-concurrency-basic/README.md b/core-java-modules/core-java-concurrency-basic/README.md index f1aa748c6b..137251b46a 100644 --- a/core-java-modules/core-java-concurrency-basic/README.md +++ b/core-java-modules/core-java-concurrency-basic/README.md @@ -9,5 +9,5 @@ This module contains articles about basic Java concurrency - [How to Kill a Java Thread](https://www.baeldung.com/java-thread-stop) - [ExecutorService – Waiting for Threads to Finish](https://www.baeldung.com/java-executor-wait-for-threads) - [Runnable vs. Callable in Java](https://www.baeldung.com/java-runnable-callable) -- [What is Thread-Safety and How to Achieve it?](https://www.baeldung.com/java-thread-safety) +- [What Is Thread-Safety and How to Achieve It?](https://www.baeldung.com/java-thread-safety) - [[Next -->]](/core-java-modules/core-java-concurrency-basic-2) diff --git a/core-java-modules/core-java-concurrency-collections/README.md b/core-java-modules/core-java-concurrency-collections/README.md index 94f93d1bfd..1ae50531f0 100644 --- a/core-java-modules/core-java-concurrency-collections/README.md +++ b/core-java-modules/core-java-concurrency-collections/README.md @@ -7,7 +7,7 @@ This module contains articles about concurrent Java collections - [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map) - [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue) - [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception) -- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool) +- [Custom Thread Pools in Java 8 Parallel Streams](https://www.baeldung.com/java-8-parallel-streams-custom-threadpool) - [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue) - [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue) - [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map) diff --git a/core-java-modules/core-java-date-operations-1/README.md b/core-java-modules/core-java-date-operations-1/README.md index b63fab63db..8c171177ee 100644 --- a/core-java-modules/core-java-date-operations-1/README.md +++ b/core-java-modules/core-java-date-operations-1/README.md @@ -10,6 +10,6 @@ This module contains articles about date operations in Java. - [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) - [Calculate Age in Java](http://www.baeldung.com/java-get-age) - [Increment Date in Java](http://www.baeldung.com/java-increment-date) -- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date) +- [Add Hours to a Date in Java](https://www.baeldung.com/java-add-hours-date) - [Introduction to Joda-Time](http://www.baeldung.com/joda-time) -- [[Next -->]](/core-java-modules/core-java-date-operations-2) \ No newline at end of file +- [[Next -->]](/core-java-modules/core-java-date-operations-2) diff --git a/core-java-modules/core-java-date-operations-2/README.md b/core-java-modules/core-java-date-operations-2/README.md index 1555492bf6..da516b4641 100644 --- a/core-java-modules/core-java-date-operations-2/README.md +++ b/core-java-modules/core-java-date-operations-2/README.md @@ -5,10 +5,10 @@ This module contains articles about date operations in Java. - [Get the Current Date Prior to Java 8](https://www.baeldung.com/java-get-the-current-date-legacy) - [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends) -- [Checking if Two Java Dates are On the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day) +- [Checking if Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day) - [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime) - [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone) -- [How to determine day of week by passing specific date in Java?](https://www.baeldung.com/java-get-day-of-week) +- [How to Determine Day of Week by Passing Specific Date in Java?](https://www.baeldung.com/java-get-day-of-week) - [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year) - [Getting the Week Number From Any Date](https://www.baeldung.com/java-get-week-number) - [Subtract Days from a Date in Java](https://www.baeldung.com/java-subtract-days-from-date) diff --git a/core-java-modules/core-java-datetime-string-2/src/test/java/com/baeldung/sortdatestrings/SortDateStringsUnitTest.java b/core-java-modules/core-java-datetime-string-2/src/test/java/com/baeldung/sortdatestrings/SortDateStringsUnitTest.java new file mode 100644 index 0000000000..89342e8197 --- /dev/null +++ b/core-java-modules/core-java-datetime-string-2/src/test/java/com/baeldung/sortdatestrings/SortDateStringsUnitTest.java @@ -0,0 +1,98 @@ +package com.baeldung.sortdatestrings; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.google.common.collect.Lists; + +public class SortDateStringsUnitTest { + private List dtStrings = null; + // @formatter:off + private static final List EXPECTED = Lists.newArrayList( + "01/20/2013 06:16", + "01/20/2013 10:48", + "01/21/2013 10:41", + "01/21/2013 16:37", + "01/21/2013 17:16", + "01/21/2013 17:19", + "01/22/2013 06:19", + "01/22/2013 15:13" + ); + // @formatter:on + + @BeforeEach + void resetInput() { + // @formatter:off + dtStrings = Lists.newArrayList( + "01/21/2013 10:41", + "01/20/2013 10:48", + "01/22/2013 15:13", + "01/21/2013 16:37", + "01/21/2013 17:16", + "01/21/2013 17:19", + "01/20/2013 06:16", + "01/22/2013 06:19" + ); + // @formatter:on + + } + + @Test + void whenUsingCustomComparator_thenGetExpectedResult() { + DateFormat dfm = new SimpleDateFormat("MM/dd/yyyy HH:mm"); + Collections.sort(dtStrings, new Comparator() { + @Override + public int compare(String o1, String o2) { + try { + return dfm.parse(o1) + .compareTo(dfm.parse(o2)); + } catch (ParseException e) { + throw new IllegalArgumentException(e); + } + } + }); + assertEquals(EXPECTED, dtStrings); + } + + @Test + void whenUsingListSort_thenGetExpectedResult() { + DateTimeFormatter dfm = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm"); + dtStrings.sort(Comparator.comparing(s -> LocalDateTime.parse(s, dfm))); + assertEquals(EXPECTED, dtStrings); + } + + @Test + void whenUsingStreamToNewList_thenGetExpectedResult() { + DateTimeFormatter dfm = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm"); + List sortedList = dtStrings.stream() + .map(s -> LocalDateTime.parse(s, dfm)) + .sorted() + .map(dfm::format) + .collect(Collectors.toList()); + assertEquals(EXPECTED, sortedList); + } + + @Test + void whenUsingTreeMap_thenGetExpectedResult() { + DateTimeFormatter dfm = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm"); + Map dateFormatMap = new TreeMap<>(); + dtStrings.forEach(s -> dateFormatMap.put(LocalDateTime.parse(s, dfm), s)); + List result = new ArrayList<>(dateFormatMap.values()); + assertEquals(EXPECTED, result); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-datetime-string/README.md b/core-java-modules/core-java-datetime-string/README.md index e22e807591..bd1a844654 100644 --- a/core-java-modules/core-java-datetime-string/README.md +++ b/core-java-modules/core-java-datetime-string/README.md @@ -4,12 +4,12 @@ This module contains articles about parsing and formatting Java date and time ob ### Relevant Articles: - [Check If a String Is a Valid Date in Java](https://www.baeldung.com/java-string-valid-date) -- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions) +- [Regex for Matching Date Pattern in Java](https://www.baeldung.com/java-date-regular-expressions) - [Guide to DateTimeFormatter](https://www.baeldung.com/java-datetimeformatter) - [Format ZonedDateTime to String](https://www.baeldung.com/java-format-zoned-datetime-string) - [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format) -- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) -- [Convert between String and Timestamp](https://www.baeldung.com/java-string-to-timestamp) +- [Display All Time Zones With GMT and UTC in Java](https://www.baeldung.com/java-time-zones) +- [Convert Between String and Timestamp](https://www.baeldung.com/java-string-to-timestamp) - [Convert String to Date in Java](http://www.baeldung.com/java-string-to-date) - [Format a Milliseconds Duration to HH:MM:SS](https://www.baeldung.com/java-ms-to-hhmmss) - [Format Instant to String in Java](https://www.baeldung.com/java-instant-to-string) diff --git a/core-java-modules/core-java-io-2/src/test/java/com/baeldung/readlargefile/ReadLargeFileUnitTest.java b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/readlargefile/ReadLargeFileUnitTest.java index b2923d9c01..772d97d287 100644 --- a/core-java-modules/core-java-io-2/src/test/java/com/baeldung/readlargefile/ReadLargeFileUnitTest.java +++ b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/readlargefile/ReadLargeFileUnitTest.java @@ -1,9 +1,16 @@ package com.baeldung.readlargefile; +import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; +import java.io.FileReader; import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; import java.util.Scanner; +import java.util.stream.Stream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; @@ -93,6 +100,61 @@ public class ReadLargeFileUnitTest { logMemory(); } + @Test + public void givenUsingBufferedReader_whenIteratingAFile_thenCorrect() throws IOException { + String fileName = "src/test/resources/myFile"; + + logMemory(); + try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { + while (br.readLine() != null) { + // do something with each line + } + } + logMemory(); + } + + @Test + public void givenUsingNewBufferedReader_whenIteratingAFile_thenCorrect() throws IOException { + String fileName = "src/test/resources/myFile"; + + logMemory(); + try (BufferedReader br = java.nio.file.Files.newBufferedReader(Paths.get(fileName))) { + while (br.readLine() != null) { + // do something with each line + } + } + logMemory(); + } + + @Test + public void givenUsingSeekableByteChannel_whenIteratingAFile_thenCorrect() throws IOException { + String fileName = "src/test/resources/myFile"; + + logMemory(); + try (SeekableByteChannel ch = java.nio.file.Files.newByteChannel(Paths.get(fileName), StandardOpenOption.READ)) { + ByteBuffer bf = ByteBuffer.allocate(1000); + while (ch.read(bf) > 0) { + bf.flip(); + // System.out.println(new String(bf.array())); + bf.clear(); + } + } + logMemory(); + } + + @Test + public void givenUsingStreamApi_whenIteratingAFile_thenCorrect() throws IOException { + String fileName = "src/test/resources/myFile"; + + logMemory(); + try (Stream lines = java.nio.file.Files.lines(Paths.get(fileName))) { + lines.forEach(line -> { + // do something with each line + }); + } + logMemory(); + } + // utils private final void logMemory() { 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 9bd55abac4..d62fd3dbd1 100644 --- a/core-java-modules/core-java-io-apis-2/README.md +++ b/core-java-modules/core-java-io-apis-2/README.md @@ -12,3 +12,5 @@ This module contains articles about core Java input/output(IO) APIs. - [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) diff --git a/core-java-modules/core-java-lang-2/README.md b/core-java-modules/core-java-lang-2/README.md index c043d29811..8548ad8ca2 100644 --- a/core-java-modules/core-java-lang-2/README.md +++ b/core-java-modules/core-java-lang-2/README.md @@ -3,9 +3,9 @@ This module contains articles about core features in the Java language ### Relevant Articles: -- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects) +- [Java Primitives Versus Objects](https://www.baeldung.com/java-primitives-vs-objects) - [Command-Line Arguments in Java](https://www.baeldung.com/java-command-line-arguments) -- [What is a POJO Class?](https://www.baeldung.com/java-pojo-class) +- [What Is a Pojo Class?](https://www.baeldung.com/java-pojo-class) - [Java Default Parameters Using Method Overloading](https://www.baeldung.com/java-default-parameters-method-overloading) - [How to Return Multiple Values From a Java Method](https://www.baeldung.com/java-method-return-multiple-values) - [Guide to the Java finally Keyword](https://www.baeldung.com/java-finally-keyword) diff --git a/core-java-modules/core-java-lang-3/README.md b/core-java-modules/core-java-lang-3/README.md index d0505dfee1..f0e7c8b7b4 100644 --- a/core-java-modules/core-java-lang-3/README.md +++ b/core-java-modules/core-java-lang-3/README.md @@ -4,7 +4,7 @@ This module contains articles about core features in the Java language - [Class.isInstance vs Class.isAssignableFrom and instanceof](https://www.baeldung.com/java-isinstance-isassignablefrom) - [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean) -- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization) +- [When Are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization) - [Checking if a Class Exists in Java](https://www.baeldung.com/java-check-class-exists) - [The Difference Between a.getClass() and A.class in Java](https://www.baeldung.com/java-getclass-vs-class) - [Constants in Java: Patterns and Anti-Patterns](https://www.baeldung.com/java-constants-good-practices) diff --git a/core-java-modules/core-java-lang-math-2/README.md b/core-java-modules/core-java-lang-math-2/README.md index 5e1dc5af0e..9567ea6fb6 100644 --- a/core-java-modules/core-java-lang-math-2/README.md +++ b/core-java-modules/core-java-lang-math-2/README.md @@ -6,7 +6,7 @@ - [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial) - [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm) -- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap) +- [Check if Two Rectangles Overlap in Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap) - [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points) - [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines) - [Round Up to the Nearest Hundred in Java](https://www.baeldung.com/java-round-up-nearest-hundred) diff --git a/core-java-modules/core-java-lang-oop-types/README.md b/core-java-modules/core-java-lang-oop-types/README.md index 7978cb7730..ec2230f06a 100644 --- a/core-java-modules/core-java-lang-oop-types/README.md +++ b/core-java-modules/core-java-lang-oop-types/README.md @@ -8,7 +8,7 @@ This module contains articles about types in Java - [Guide to the this Java Keyword](https://www.baeldung.com/java-this) - [Nested Classes in Java](https://www.baeldung.com/java-nested-classes) - [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces) -- [Iterating over Enum Values in Java](https://www.baeldung.com/java-enum-iteration) +- [Iterating Over Enum Values in Java](https://www.baeldung.com/java-enum-iteration) - [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values) - [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums) - [Determine if an Object Is of Primitive Type](https://www.baeldung.com/java-object-primitive-type) diff --git a/core-java-modules/core-java-lang-operators/README.md b/core-java-modules/core-java-lang-operators/README.md index 3e2afd1489..52906f292e 100644 --- a/core-java-modules/core-java-lang-operators/README.md +++ b/core-java-modules/core-java-lang-operators/README.md @@ -4,7 +4,7 @@ This module contains articles about Java operators ## Relevant Articles: - [Guide to the Diamond Operator in Java](https://www.baeldung.com/java-diamond-operator) -- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator) +- [Ternary Operator in Java](https://www.baeldung.com/java-ternary-operator) - [The Modulo Operator in Java](https://www.baeldung.com/modulo-java) - [Java instanceof Operator](https://www.baeldung.com/java-instanceof) - [A Guide to Increment and Decrement Unary Operators in Java](https://www.baeldung.com/java-unary-operators) diff --git a/core-java-modules/core-java-lang/README.md b/core-java-modules/core-java-lang/README.md index 963a1e623e..93b4c25fd9 100644 --- a/core-java-modules/core-java-lang/README.md +++ b/core-java-modules/core-java-lang/README.md @@ -5,7 +5,7 @@ This module contains articles about core features in the Java language ### Relevant Articles: - [Generate equals() and hashCode() with Eclipse](https://www.baeldung.com/java-eclipse-equals-and-hashcode) - [Comparator and Comparable in Java](https://www.baeldung.com/java-comparator-comparable) -- [Recursion In Java](https://www.baeldung.com/java-recursion) +- [Recursion in Java](https://www.baeldung.com/java-recursion) - [A Guide to the finalize Method in Java](https://www.baeldung.com/java-finalize) - [Quick Guide to java.lang.System](https://www.baeldung.com/java-lang-system) - [Using Java Assertions](https://www.baeldung.com/java-assert) diff --git a/core-java-modules/core-java-networking-2/README.md b/core-java-modules/core-java-networking-2/README.md index c223e20a84..220ff8ad3d 100644 --- a/core-java-modules/core-java-networking-2/README.md +++ b/core-java-modules/core-java-networking-2/README.md @@ -12,6 +12,6 @@ This module contains articles about networking in Java - [Authentication with HttpUrlConnection](https://www.baeldung.com/java-http-url-connection) - [Download a File From an URL in Java](https://www.baeldung.com/java-download-file) - [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception) -- [Getting MAC addresses in Java](https://www.baeldung.com/java-mac-address) +- [Getting MAC Addresses in Java](https://www.baeldung.com/java-mac-address) - [Sending Emails with Attachments in Java](https://www.baeldung.com/java-send-emails-attachments) - [[<-- Prev]](/core-java-modules/core-java-networking) diff --git a/core-java-modules/core-java-networking/README.md b/core-java-modules/core-java-networking/README.md index 4038e9803a..893efa4c55 100644 --- a/core-java-modules/core-java-networking/README.md +++ b/core-java-modules/core-java-networking/README.md @@ -6,12 +6,12 @@ This module contains articles about networking in Java - [Connecting Through Proxy Servers in Core Java](https://www.baeldung.com/java-connect-via-proxy-server) - [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast) -- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java) -- [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java) +- [A Guide to UDP In Java](https://www.baeldung.com/udp-in-java) +- [A Guide to HTTP Cookies in Java](https://www.baeldung.com/cookies-java) - [A Guide to the Java URL](http://www.baeldung.com/java-url) - [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces) - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) - [Guide to Java URL Encoding/Decoding](http://www.baeldung.com/java-url-encoding-decoding) -- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri) +- [Difference Between URL and URI](https://www.baeldung.com/java-url-vs-uri) - [Read an InputStream using the Java Server Socket](https://www.baeldung.com/java-inputstream-server-socket) - [[More -->]](/core-java-modules/core-java-networking-2) diff --git a/core-java-modules/core-java-perf-2/README.md b/core-java-modules/core-java-perf-2/README.md index 8911c687a0..8718060645 100644 --- a/core-java-modules/core-java-perf-2/README.md +++ b/core-java-modules/core-java-perf-2/README.md @@ -3,6 +3,5 @@ This module contains articles about performance of Java applications ### Relevant Articles: -- [Possible Root Causes for High CPU Usage in Java](https://www.baeldung.com/java-high-cpu-usage-causes) - [External Debugging With JMXTerm](https://www.baeldung.com/java-jmxterm-external-debugging) - [Create and Detect Memory Leaks in Java](https://www.baeldung.com/java-create-detect-memory-leaks) diff --git a/core-java-modules/core-java-perf/README.md b/core-java-modules/core-java-perf/README.md index c400f1d196..c018ec9927 100644 --- a/core-java-modules/core-java-perf/README.md +++ b/core-java-modules/core-java-perf/README.md @@ -13,5 +13,3 @@ This module contains articles about performance of Java applications - [Capturing a Java Thread Dump](https://www.baeldung.com/java-thread-dump) - [JMX Ports](https://www.baeldung.com/jmx-ports) - [Calling JMX MBean Method From a Shell Script](https://www.baeldung.com/jmx-mbean-shell-access) -- [External Debugging With JMXTerm](https://www.baeldung.com/java-jmxterm-external-debugging) -- [Create and Detect Memory Leaks in Java](https://www.baeldung.com/java-create-detect-memory-leaks) diff --git a/core-java-modules/core-java-records/README.md b/core-java-modules/core-java-records/README.md index 2e7ad00cd3..86d3579c76 100644 --- a/core-java-modules/core-java-records/README.md +++ b/core-java-modules/core-java-records/README.md @@ -1,2 +1,2 @@ ## Relevant Articles -- [Overridding hashCode() And equals() For Records](https://www.baeldung.com/java-override-hashcode-equals-records) +- [Overriding hashCode() And equals() For Records](https://www.baeldung.com/java-override-hashcode-equals-records) diff --git a/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Movie.java b/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Movie.java index e94638e8b5..9ee0f1ac95 100644 --- a/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Movie.java +++ b/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Movie.java @@ -4,20 +4,24 @@ import java.util.Objects; record Movie(String name, Integer yearOfRelease, String distributor) { -@Override -public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null) { + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (other == null) { + return false; + } + if (!(other instanceof Movie)) { + return false; + } + + Movie movie = (Movie) other; + if (movie.name.equals(this.name) && movie.yearOfRelease.equals(this.yearOfRelease)) { + return true; + } return false; } - Movie movie = (Movie) other; - if (movie.name.equals(this.name) && movie.yearOfRelease.equals(this.yearOfRelease)) { - return true; - } - return false; -} @Override public int hashCode() { diff --git a/core-java-modules/core-java-reflection-private-constructor/README.md b/core-java-modules/core-java-reflection-private-constructor/README.md deleted file mode 100644 index a3c9d00b0a..0000000000 --- a/core-java-modules/core-java-reflection-private-constructor/README.md +++ /dev/null @@ -1,10 +0,0 @@ -### Relevant Articles: - -- [Reading the Value of ‘private’ Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value) -- [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value) -- [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static) -- [Checking if a Java Class is ‘abstract’ Using Reflection](https://www.baeldung.com/java-reflection-is-class-abstract) -- [Invoking a Private Method in Java](https://www.baeldung.com/java-call-private-method) -- [Finding All Classes in a Java Package](https://www.baeldung.com/java-find-all-classes-in-package) -- [Invoke a Static Method Using Java Reflection API](https://www.baeldung.com/java-invoke-static-method-reflection) -- [What Is the JDK com.sun.proxy.$Proxy Class?](https://www.baeldung.com/jdk-com-sun-proxy) diff --git a/core-java-modules/core-java-reflection-private-constructor/pom.xml b/core-java-modules/core-java-reflection-private-constructor/pom.xml deleted file mode 100644 index aee7815e23..0000000000 --- a/core-java-modules/core-java-reflection-private-constructor/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - 4.0.0 - core-java-reflection-private-constructor - core-java-reflection-private-constructor - jar - - - com.baeldung.core-java-modules - core-java-modules - 0.0.1-SNAPSHOT - - - - - org.springframework - spring-test - ${spring.version} - test - - - org.reflections - reflections - ${reflections.version} - - - - - core-java-reflection-private-constructor - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${source.version} - ${target.version} - -parameters - - - - - - - 0.9.12 - 1.8 - 1.8 - 5.3.4 - - - \ No newline at end of file diff --git a/core-java-modules/core-java-reflection-private-constructor/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java b/core-java-modules/core-java-reflection-private-constructor/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java deleted file mode 100644 index 24e7d435c7..0000000000 --- a/core-java-modules/core-java-reflection-private-constructor/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.reflection; - -public class PrivateConstructorClass { - - private PrivateConstructorClass() { - System.out.println("Used the private constructor!"); - } -} \ No newline at end of file diff --git a/core-java-modules/core-java-reflection-private-constructor/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java b/core-java-modules/core-java-reflection-private-constructor/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java deleted file mode 100644 index cd1f48d720..0000000000 --- a/core-java-modules/core-java-reflection-private-constructor/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.reflection; - -import java.lang.reflect.Constructor; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class PrivateConstructorUnitTest { - - @Test - public void whenConstructorIsPrivate_thenInstanceSuccess() throws Exception { - Constructor pcc = PrivateConstructorClass.class.getDeclaredConstructor(); - pcc.setAccessible(true); - PrivateConstructorClass privateConstructorInstance = pcc.newInstance(); - Assertions.assertTrue(privateConstructorInstance instanceof PrivateConstructorClass); - } -} \ No newline at end of file diff --git a/core-java-modules/core-java-reflection/README.md b/core-java-modules/core-java-reflection/README.md index b823f43606..e7c931575a 100644 --- a/core-java-modules/core-java-reflection/README.md +++ b/core-java-modules/core-java-reflection/README.md @@ -3,7 +3,7 @@ - [Void Type in Java](https://www.baeldung.com/java-void-type) - [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields) - [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) -- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params) +- [Changing Annotation Parameters at Runtime](https://www.baeldung.com/java-reflection-change-annotation-params) - [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) - [What Causes java.lang.reflect.InvocationTargetException?](https://www.baeldung.com/java-lang-reflect-invocationtargetexception) - [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method) diff --git a/core-java-modules/core-java-security-2/README.md b/core-java-modules/core-java-security-2/README.md index 7128c39713..1c6313b9dd 100644 --- a/core-java-modules/core-java-security-2/README.md +++ b/core-java-modules/core-java-security-2/README.md @@ -4,7 +4,7 @@ This module contains articles about core Java Security ### Relevant Articles: -- [Guide To The Java Authentication And Authorization Service (JAAS)](https://www.baeldung.com/java-authentication-authorization-service) +- [Guide to the Java Authentication And Authorization Service (JAAS)](https://www.baeldung.com/java-authentication-authorization-service) - [MD5 Hashing in Java](http://www.baeldung.com/java-md5) - [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) - [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) diff --git a/core-java-modules/core-java-serialization/README.md b/core-java-modules/core-java-serialization/README.md index fc6cfcf134..ed8f8dc1c6 100644 --- a/core-java-modules/core-java-serialization/README.md +++ b/core-java-modules/core-java-serialization/README.md @@ -6,4 +6,5 @@ - [Introduction to Java Serialization](http://www.baeldung.com/java-serialization) - [Deserialization Vulnerabilities in Java](https://www.baeldung.com/java-deserialization-vulnerabilities) - [Serialization Validation in Java](https://www.baeldung.com/java-validate-serializable) -- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid) +- [What Is the serialVersionUID?](https://www.baeldung.com/java-serial-version-uid) +- [Java Serialization: readObject() vs. readResolve()](https://www.baeldung.com/java-serialization-readobject-vs-readresolve) diff --git a/core-java-modules/core-java-streams/README.md b/core-java-modules/core-java-streams/README.md index b950325e40..360f7190ea 100644 --- a/core-java-modules/core-java-streams/README.md +++ b/core-java-modules/core-java-streams/README.md @@ -12,5 +12,5 @@ This module contains articles about the Stream API in Java. - [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda) - [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count) - [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum) -- [How to Find all Getters Returning Null](https://www.baeldung.com/java-getters-returning-null) +- [How to Find All Getters Returning Null](https://www.baeldung.com/java-getters-returning-null) - More articles: [[next -->]](/../core-java-streams-2) diff --git a/core-java-modules/core-java-string-algorithms-2/README.md b/core-java-modules/core-java-string-algorithms-2/README.md index 5d39291cfb..dbfbb3ef3c 100644 --- a/core-java-modules/core-java-string-algorithms-2/README.md +++ b/core-java-modules/core-java-string-algorithms-2/README.md @@ -6,7 +6,7 @@ This module contains articles about string-related algorithms. - [How to Remove the Last Character of a String?](https://www.baeldung.com/java-remove-last-character-of-string) - [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) - [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex) -- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part) +- [Remove or Replace Part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part) - [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index) - [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) - [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) diff --git a/core-java-modules/core-java-string-algorithms-3/README.md b/core-java-modules/core-java-string-algorithms-3/README.md index bc6b6f2167..6af818b52d 100644 --- a/core-java-modules/core-java-string-algorithms-3/README.md +++ b/core-java-modules/core-java-string-algorithms-3/README.md @@ -5,7 +5,7 @@ This module contains articles about string-related algorithms. ### Relevant Articles: - [Generating a Java String of N Repeated Characters](https://www.baeldung.com/java-string-of-repeated-characters) -- [Check if Two Strings are Anagrams in Java](https://www.baeldung.com/java-strings-anagrams) +- [Check if Two Strings Are Anagrams in Java](https://www.baeldung.com/java-strings-anagrams) - [Email Validation in Java](https://www.baeldung.com/java-email-validation-regex) - [Check if the First Letter of a String Is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase) - [Find the First Non Repeating Character in a String in Java](https://www.baeldung.com/java-find-the-first-non-repeating-character) diff --git a/core-java-modules/core-java-string-algorithms/README.md b/core-java-modules/core-java-string-algorithms/README.md index e8c8e32da8..5a7abf074a 100644 --- a/core-java-modules/core-java-string-algorithms/README.md +++ b/core-java-modules/core-java-string-algorithms/README.md @@ -3,13 +3,13 @@ This module contains articles about string-related algorithms. ### Relevant Articles: -- [Check if a String is a Palindrome in Java](https://www.baeldung.com/java-palindrome) +- [Check if a String Is a Palindrome in Java](https://www.baeldung.com/java-palindrome) - [Count Occurrences of a Char in a String](https://www.baeldung.com/java-count-chars) - [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexof-find-string-occurrences) - [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) - [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) - [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string) -- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) +- [Check if a String Is a Pangram in Java](https://www.baeldung.com/java-string-pangram) - [Check If a String Contains Multiple Keywords in Java](https://www.baeldung.com/string-contains-multiple-words) - [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring) - [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) diff --git a/core-java-modules/core-java-string-operations-2/README.md b/core-java-modules/core-java-string-operations-2/README.md index f95b002906..871b5525cd 100644 --- a/core-java-modules/core-java-string-operations-2/README.md +++ b/core-java-modules/core-java-string-operations-2/README.md @@ -3,7 +3,7 @@ This module contains articles about string operations. ### Relevant Articles: -- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) +- [Concatenating Strings in Java](https://www.baeldung.com/java-strings-concatenation) - [Checking for Empty or Blank Strings in Java](https://www.baeldung.com/java-blank-empty-strings) - [String Initialization in Java](https://www.baeldung.com/java-string-initialization) - [String toLowerCase and toUpperCase Methods in Java](https://www.baeldung.com/java-string-convert-case) diff --git a/core-java-modules/core-java-string-operations-5/README.md b/core-java-modules/core-java-string-operations-5/README.md index 3a09c8a585..21ba1bf985 100644 --- a/core-java-modules/core-java-string-operations-5/README.md +++ b/core-java-modules/core-java-string-operations-5/README.md @@ -10,5 +10,4 @@ - [Guide to Splitting a String by Whitespace in Java](https://www.baeldung.com/java-splitting-a-string-by-whitespace) - [Check if the First Letter of a String Is a Number](https://www.baeldung.com/java-check-if-string-starts-with-number) - [Print “” Quotes Around a String in Java](https://www.baeldung.com/java-string-print-quotes) -- [Remove Punctuation From a String in Java](https://www.baeldung.com/java-remove-punctuation-from-string) -- [Find the Longest Word in a Given String in Java](https://www.baeldung.com/java-longest-word-string) +- [Remove Punctuation From a String in Java](https://www.baeldung.com/java-remove-punctuation-from-string) \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-6/README.md b/core-java-modules/core-java-string-operations-6/README.md new file mode 100644 index 0000000000..190880a5dd --- /dev/null +++ b/core-java-modules/core-java-string-operations-6/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Find the Longest Word in a Given String in Java](https://www.baeldung.com/java-longest-word-string) diff --git a/core-java-modules/core-java-string-operations-6/pom.xml b/core-java-modules/core-java-string-operations-6/pom.xml new file mode 100644 index 0000000000..8b9eabbc63 --- /dev/null +++ b/core-java-modules/core-java-string-operations-6/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + core-java-string-operations-6 + core-java-string-operations-6 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 11 + 11 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/longestword/LongestWordFinder.java b/core-java-modules/core-java-string-operations-6/src/main/java/com/baeldung/longestword/LongestWordFinder.java similarity index 100% rename from core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/longestword/LongestWordFinder.java rename to core-java-modules/core-java-string-operations-6/src/main/java/com/baeldung/longestword/LongestWordFinder.java diff --git a/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/longestword/LongestWordFinderUnitTest.java b/core-java-modules/core-java-string-operations-6/src/test/java/com/baeldung/longestword/LongestWordFinderUnitTest.java similarity index 100% rename from core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/longestword/LongestWordFinderUnitTest.java rename to core-java-modules/core-java-string-operations-6/src/test/java/com/baeldung/longestword/LongestWordFinderUnitTest.java diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index b872eef491..806882a84f 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -137,6 +137,7 @@ core-java-string-conversions-3 core-java-string-operations core-java-string-operations-2 + core-java-string-operations-6 core-java-regex core-java-regex-2 core-java-uuid diff --git a/gradle-modules/gradle-7/gradle-wsdl-stubs/.gitignore b/gradle-modules/gradle-7/gradle-wsdl-stubs/.gitignore new file mode 100644 index 0000000000..b63da4551b --- /dev/null +++ b/gradle-modules/gradle-7/gradle-wsdl-stubs/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/gradle-modules/gradle-7/gradle-wsdl-stubs/build.gradle b/gradle-modules/gradle-7/gradle-wsdl-stubs/build.gradle new file mode 100644 index 0000000000..e368dc5c06 --- /dev/null +++ b/gradle-modules/gradle-7/gradle-wsdl-stubs/build.gradle @@ -0,0 +1,23 @@ +plugins { + id 'java' + id("com.github.bjornvester.wsdl2java") version "1.2" +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'com.sun.xml.ws:jaxws-ri:4.0.1' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' +} + +test { + useJUnitPlatform() +} + + +wsdl2java { + cxfVersion.set("3.4.4") +} diff --git a/gradle-modules/gradle-7/gradle-wsdl-stubs/gradle/wrapper/gradle-wrapper.jar b/gradle-modules/gradle-7/gradle-wsdl-stubs/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..ccebba7710 Binary files /dev/null and b/gradle-modules/gradle-7/gradle-wsdl-stubs/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle-modules/gradle-7/gradle-wsdl-stubs/gradle/wrapper/gradle-wrapper.properties b/gradle-modules/gradle-7/gradle-wsdl-stubs/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..42defcc94b --- /dev/null +++ b/gradle-modules/gradle-7/gradle-wsdl-stubs/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradle-modules/gradle-7/gradle-wsdl-stubs/gradlew b/gradle-modules/gradle-7/gradle-wsdl-stubs/gradlew new file mode 100755 index 0000000000..79a61d421c --- /dev/null +++ b/gradle-modules/gradle-7/gradle-wsdl-stubs/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradle-modules/gradle-7/gradle-wsdl-stubs/gradlew.bat b/gradle-modules/gradle-7/gradle-wsdl-stubs/gradlew.bat new file mode 100644 index 0000000000..6689b85bee --- /dev/null +++ b/gradle-modules/gradle-7/gradle-wsdl-stubs/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/gradle-wsdl-stubs/settings.gradle b/gradle-modules/gradle-7/gradle-wsdl-stubs/settings.gradle new file mode 100644 index 0000000000..3a648ffa2f --- /dev/null +++ b/gradle-modules/gradle-7/gradle-wsdl-stubs/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'gradle-javadoc' + diff --git a/gradle-modules/gradle-7/gradle-wsdl-stubs/src/main/resources/wsdl/NumberConversion.wsdl b/gradle-modules/gradle-7/gradle-wsdl-stubs/src/main/resources/wsdl/NumberConversion.wsdl new file mode 100644 index 0000000000..31826e82cb --- /dev/null +++ b/gradle-modules/gradle-7/gradle-wsdl-stubs/src/main/resources/wsdl/NumberConversion.wsdl @@ -0,0 +1,110 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Returns the word corresponding to the positive number passed as parameter. Limited to quadrillions. + + + + + Returns the non-zero dollar amount of the passed number. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The Number Conversion Web Service, implemented with Visual DataFlex, provides functions that convert numbers into words or dollar amounts. + + + + + + + + diff --git a/gradle-modules/gradle-7/gradle-wsdl-stubs/src/test/java/com/baeldung/wsdlestubs/NumberConversionUnitTest.java b/gradle-modules/gradle-7/gradle-wsdl-stubs/src/test/java/com/baeldung/wsdlestubs/NumberConversionUnitTest.java new file mode 100644 index 0000000000..8a76a68d57 --- /dev/null +++ b/gradle-modules/gradle-7/gradle-wsdl-stubs/src/test/java/com/baeldung/wsdlestubs/NumberConversionUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.wsdlestubs; + +import com.dataaccess.webservicesserver.NumberConversion; +import com.dataaccess.webservicesserver.NumberConversionSoapType; +import org.junit.jupiter.api.Test; +import java.math.BigInteger; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class NumberConversionUnitTest { + + @Test + public void givenNumberConversionService_whenConvertingNumberToWords_thenReturnCorrectWords() { + NumberConversion service = new NumberConversion(); + NumberConversionSoapType port = service.getNumberConversionSoap(); + + String numberInWords = port.numberToWords(BigInteger.valueOf(10000000)); + assertEquals("ten million", numberInWords); + } +} diff --git a/gradle-modules/gradle-customization/protobuf/README.md b/gradle-modules/gradle-customization/gradle-protobuf/README.md similarity index 100% rename from gradle-modules/gradle-customization/protobuf/README.md rename to gradle-modules/gradle-customization/gradle-protobuf/README.md diff --git a/gradle-modules/gradle-customization/protobuf/build.gradle b/gradle-modules/gradle-customization/gradle-protobuf/build.gradle similarity index 100% rename from gradle-modules/gradle-customization/protobuf/build.gradle rename to gradle-modules/gradle-customization/gradle-protobuf/build.gradle diff --git a/gradle-modules/gradle-customization/protobuf/gradle/wrapper/gradle-wrapper.properties b/gradle-modules/gradle-customization/gradle-protobuf/gradle/wrapper/gradle-wrapper.properties similarity index 100% rename from gradle-modules/gradle-customization/protobuf/gradle/wrapper/gradle-wrapper.properties rename to gradle-modules/gradle-customization/gradle-protobuf/gradle/wrapper/gradle-wrapper.properties diff --git a/gradle-modules/gradle-customization/protobuf/gradlew b/gradle-modules/gradle-customization/gradle-protobuf/gradlew similarity index 100% rename from gradle-modules/gradle-customization/protobuf/gradlew rename to gradle-modules/gradle-customization/gradle-protobuf/gradlew diff --git a/gradle-modules/gradle-customization/protobuf/gradlew.bat b/gradle-modules/gradle-customization/gradle-protobuf/gradlew.bat similarity index 100% rename from gradle-modules/gradle-customization/protobuf/gradlew.bat rename to gradle-modules/gradle-customization/gradle-protobuf/gradlew.bat diff --git a/gradle-modules/gradle-customization/gradle-protobuf/settings.gradle b/gradle-modules/gradle-customization/gradle-protobuf/settings.gradle new file mode 100644 index 0000000000..8f8b559eb6 --- /dev/null +++ b/gradle-modules/gradle-customization/gradle-protobuf/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'gradle-protobuf' diff --git a/gradle-modules/gradle-customization/protobuf/src/main/resources/application.properties b/gradle-modules/gradle-customization/gradle-protobuf/src/main/resources/application.properties similarity index 100% rename from gradle-modules/gradle-customization/protobuf/src/main/resources/application.properties rename to gradle-modules/gradle-customization/gradle-protobuf/src/main/resources/application.properties diff --git a/gradle-modules/gradle-customization/protobuf/src/sample_protofiles/user_message.proto b/gradle-modules/gradle-customization/gradle-protobuf/src/sample_protofiles/user_message.proto similarity index 100% rename from gradle-modules/gradle-customization/protobuf/src/sample_protofiles/user_message.proto rename to gradle-modules/gradle-customization/gradle-protobuf/src/sample_protofiles/user_message.proto diff --git a/gradle-modules/gradle-customization/protobuf/src/test/java/com/baeldung/protobuf/ProtobufCodeGenerationUnitTest.java b/gradle-modules/gradle-customization/gradle-protobuf/src/test/java/com/baeldung/protobuf/ProtobufCodeGenerationUnitTest.java similarity index 100% rename from gradle-modules/gradle-customization/protobuf/src/test/java/com/baeldung/protobuf/ProtobufCodeGenerationUnitTest.java rename to gradle-modules/gradle-customization/gradle-protobuf/src/test/java/com/baeldung/protobuf/ProtobufCodeGenerationUnitTest.java diff --git a/gradle-modules/gradle-customization/protobuf/settings.gradle b/gradle-modules/gradle-customization/protobuf/settings.gradle deleted file mode 100644 index 63483bae11..0000000000 --- a/gradle-modules/gradle-customization/protobuf/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'protobuf' diff --git a/image-compressing/README.md b/image-compressing/README.md new file mode 100644 index 0000000000..b2556062b8 --- /dev/null +++ b/image-compressing/README.md @@ -0,0 +1 @@ +This module contains tutorials related to the image compression in Java. \ No newline at end of file diff --git a/image-compressing/pom.xml b/image-compressing/pom.xml new file mode 100644 index 0000000000..99cdd65647 --- /dev/null +++ b/image-compressing/pom.xml @@ -0,0 +1,36 @@ + + + 4.0.0 + image-compressing + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + net.coobird + thumbnailator + ${thumbnailator.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.0 + + + + + + 0.4.19 + + + \ No newline at end of file diff --git a/image-compressing/src/main/java/com/baeldung/image/compression/ImageCompressor.java b/image-compressing/src/main/java/com/baeldung/image/compression/ImageCompressor.java new file mode 100644 index 0000000000..13b1b9560c --- /dev/null +++ b/image-compressing/src/main/java/com/baeldung/image/compression/ImageCompressor.java @@ -0,0 +1,36 @@ +package com.baeldung.image.compression; + + +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.Iterator; + + +public class ImageCompressor { + + public static void compressImage(String inputPath, String outputPath) throws IOException { + File inputFile = new File(inputPath); + BufferedImage inputImage = ImageIO.read(inputFile); + + Iterator writers = ImageIO.getImageWritersByFormatName("jpg"); + ImageWriter writer = writers.next(); + + File outputFile = new File(outputPath); + ImageOutputStream outputStream = ImageIO.createImageOutputStream(outputFile); + writer.setOutput(outputStream); + + ImageWriteParam params = writer.getDefaultWriteParam(); + params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + params.setCompressionQuality(0.5f); + + writer.write(null, new javax.imageio.IIOImage(inputImage, null, null), params); + + outputStream.close(); + writer.dispose(); + } +} \ No newline at end of file diff --git a/image-compressing/src/main/java/com/baeldung/image/compression/ThumbnailsCompressor.java b/image-compressing/src/main/java/com/baeldung/image/compression/ThumbnailsCompressor.java new file mode 100644 index 0000000000..63e81b5d70 --- /dev/null +++ b/image-compressing/src/main/java/com/baeldung/image/compression/ThumbnailsCompressor.java @@ -0,0 +1,19 @@ +package com.baeldung.image.compression; + + +import net.coobird.thumbnailator.Thumbnails; + +import java.io.File; +import java.io.IOException; + +public class ThumbnailsCompressor { + + public static void compressImage(String inputPath, String outputPath) throws IOException { + File input = new File(inputPath); + File output = new File(outputPath); + Thumbnails.of(input) + .scale(1) + .outputQuality(0.5) + .toFile(output); + } +} \ No newline at end of file diff --git a/image-compressing/src/test/java/com/baeldung/image/compression/ImageCompressorUnitTest.java b/image-compressing/src/test/java/com/baeldung/image/compression/ImageCompressorUnitTest.java new file mode 100644 index 0000000000..374de8a83a --- /dev/null +++ b/image-compressing/src/test/java/com/baeldung/image/compression/ImageCompressorUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.image.compression; + +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class ImageCompressorUnitTest { + @Test + void testSecondFileIsSmaller() throws IOException { + String inputImagePath = ImageCompressorUnitTest.class.getClassLoader() + .getResource("input.jpg").getPath(); + File inputImage = new File(inputImagePath); + long inputImageSize = inputImage.length(); + String outputPath = inputImagePath + "compressed.jpg"; + ImageCompressor.compressImage(inputImagePath, outputPath); + File compressedImage = new File(outputPath); + long compressedImageSize = compressedImage.length(); + + assertTrue(compressedImageSize < inputImageSize, "The compressed image is smaller in size"); + } +} \ No newline at end of file diff --git a/image-compressing/src/test/java/com/baeldung/image/compression/ThumbnailsCompressorUnitTest.java b/image-compressing/src/test/java/com/baeldung/image/compression/ThumbnailsCompressorUnitTest.java new file mode 100644 index 0000000000..cb89b56cc7 --- /dev/null +++ b/image-compressing/src/test/java/com/baeldung/image/compression/ThumbnailsCompressorUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.image.compression; + +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.*; + +class ThumbnailsCompressorUnitTest { + @Test + void testCompressedImageIsSmaller() throws IOException { + String inputImagePath = ThumbnailsCompressor.class.getClassLoader() + .getResource("input.jpg").getPath(); + File inputImage = new File(inputImagePath); + long inputImageSize = inputImage.length(); + String outputPath = inputImagePath + "compressed.jpg"; + ThumbnailsCompressor.compressImage(inputImagePath, outputPath); + File compressedImage = new File(outputPath); + long compressedImageSize = compressedImage.length(); + + assertTrue(compressedImageSize < inputImageSize, "The compressed image is smaller in size"); + } +} \ No newline at end of file diff --git a/image-compressing/src/test/resources/input.jpg b/image-compressing/src/test/resources/input.jpg new file mode 100644 index 0000000000..985b089840 Binary files /dev/null and b/image-compressing/src/test/resources/input.jpg differ diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonmerge/Keyboard.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonmerge/Keyboard.java new file mode 100644 index 0000000000..818b93bc36 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonmerge/Keyboard.java @@ -0,0 +1,37 @@ +package com.baeldung.jackson.jsonmerge; + +public class Keyboard { + + private String style; + private String layout; + + public Keyboard(){ + super(); + } + + public Keyboard(String style, String layout) { + this.style = style; + this.layout = layout; + } + + public String getStyle() { + return style; + } + + public void setStyle(String style) { + this.style = style; + } + + public String getLayout() { + return layout; + } + + public void setLayout(String layout) { + this.layout = layout; + } + + @Override + public String toString() { + return "Keyboard{" + "style='" + style + '\'' + ", layout='" + layout + '\'' + '}'; + } +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonmerge/ObjectWithMap.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonmerge/ObjectWithMap.java new file mode 100644 index 0000000000..322229a241 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonmerge/ObjectWithMap.java @@ -0,0 +1,38 @@ +package com.baeldung.jackson.jsonmerge; + +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonMerge; + +public class ObjectWithMap { + + private String name; + @JsonMerge + private Map stringPairs; + + public ObjectWithMap(String name, Map stringPairs) { + this.name = name; + this.stringPairs = stringPairs; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map getStringPairs() { + return stringPairs; + } + + public void setStringPairs(Map stringPairs) { + this.stringPairs = stringPairs; + } + + @Override + public String toString() { + return "ObjectWithMap{" + "name='" + name + '\'' + ", something=" + stringPairs + '}'; + } +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonmerge/ProgrammerAnnotated.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonmerge/ProgrammerAnnotated.java new file mode 100644 index 0000000000..56fba37a25 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonmerge/ProgrammerAnnotated.java @@ -0,0 +1,38 @@ +package com.baeldung.jackson.jsonmerge; + +import com.fasterxml.jackson.annotation.JsonMerge; + +public class ProgrammerAnnotated { + + private String name; + private String favouriteLanguage; + @JsonMerge + private Keyboard keyboard; + + public ProgrammerAnnotated(String name, String favouriteLanguage, Keyboard keyboard) { + this.name = name; + this.favouriteLanguage = favouriteLanguage; + this.keyboard = keyboard; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getFavouriteLanguage() { + return favouriteLanguage; + } + + public Keyboard getKeyboard() { + return keyboard; + } + + @Override + public String toString() { + return "Programmer{" + "name='" + name + '\'' + ", favouriteLanguage='" + favouriteLanguage + '\'' + ", keyboard=" + keyboard + '}'; + } +} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonmerge/ProgrammerNotAnnotated.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonmerge/ProgrammerNotAnnotated.java new file mode 100644 index 0000000000..fae090c870 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/jsonmerge/ProgrammerNotAnnotated.java @@ -0,0 +1,43 @@ +package com.baeldung.jackson.jsonmerge; + +public class ProgrammerNotAnnotated { + + private String name; + private String favouriteLanguage; + private Keyboard keyboard; + + public ProgrammerNotAnnotated(String name, String favouriteLanguage, Keyboard keyboard) { + this.name = name; + this.favouriteLanguage = favouriteLanguage; + this.keyboard = keyboard; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getFavouriteLanguage() { + return favouriteLanguage; + } + + public void setFavouriteLanguage(String favouriteLanguage) { + this.favouriteLanguage = favouriteLanguage; + } + + public Keyboard getKeyboard() { + return keyboard; + } + + public void setKeyboard(Keyboard keyboard) { + this.keyboard = keyboard; + } + + @Override + public String toString() { + return "Programmer{" + "name='" + name + '\'' + ", favouriteLanguage='" + favouriteLanguage + '\'' + ", keyboard=" + keyboard + '}'; + } +} diff --git a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/jsonmerge/JsonMergeUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/jsonmerge/JsonMergeUnitTest.java new file mode 100644 index 0000000000..e15d3a0690 --- /dev/null +++ b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/jsonmerge/JsonMergeUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.jackson.jsonmerge; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; + +public class JsonMergeUnitTest { + + @Test + public void givenAnObjectAndJson_whenUsingJsonMerge_thenExpectUpdateInPOJO() throws JsonProcessingException { + String newData = "{\"favouriteLanguage\":\"Java\",\"keyboard\":{\"style\":\"Mechanical\"}}"; + ProgrammerAnnotated programmerToUpdate = new ProgrammerAnnotated("John", "C++", new Keyboard("Membrane", "US")); + + ObjectMapper objectMapper = new ObjectMapper(); + ProgrammerAnnotated update = objectMapper.readerForUpdating(programmerToUpdate) + .readValue(newData); + + assert (update.getFavouriteLanguage()).equals("Java"); + // Only works with annotation + assert (update.getKeyboard() + .getLayout()).equals("US"); + } + + @Test + public void givenAnObjectAndJson_whenNotUsingJsonMerge_thenExpectNoUpdateInPOJO() throws JsonProcessingException { + String newData = "{\"favouriteLanguage\":\"Java\",\"keyboard\":{\"style\":\"Mechanical\"}}"; + ProgrammerNotAnnotated programmerToUpdate = new ProgrammerNotAnnotated("John", "C++", new Keyboard("Membrane", "US")); + + ObjectMapper objectMapper = new ObjectMapper(); + ObjectReader objectReader = objectMapper.readerForUpdating(programmerToUpdate); + ProgrammerNotAnnotated update = objectReader.readValue(newData); + + assert (update.getFavouriteLanguage()).equals("Java"); + assertNull(update.getKeyboard() + .getLayout()); + } + + @Test + public void givenAnObjectWithAMap_whenUsingJsonMerge_thenExpectAllFieldsInMap() throws JsonProcessingException { + String newData = "{\"stringPairs\":{\"field1\":\"value1\",\"field2\":\"value2\"}}"; + Map map = new HashMap<>(); + map.put("field3", "value3"); + ObjectWithMap objectToUpdateWith = new ObjectWithMap("James", map); + + ObjectMapper objectMapper = new ObjectMapper(); + ObjectWithMap update = objectMapper.readerForUpdating(objectToUpdateWith) + .readValue(newData); + + assertTrue(update.getStringPairs() + .containsKey("field1")); + assertTrue(update.getStringPairs() + .containsKey("field2")); + assertTrue(update.getStringPairs() + .containsKey("field3")); + } +} diff --git a/jackson-modules/jackson-conversions/README.md b/jackson-modules/jackson-conversions/README.md index 5984ad399a..55dcb60c29 100644 --- a/jackson-modules/jackson-conversions/README.md +++ b/jackson-modules/jackson-conversions/README.md @@ -5,7 +5,7 @@ This module contains articles about Jackson conversions. ### Relevant Articles: - [Jackson – Unmarshall to Collection/Array](https://www.baeldung.com/jackson-collection-array) - [Jackson Date](https://www.baeldung.com/jackson-serialize-dates) -- [Jackson – Working with Maps and nulls](https://www.baeldung.com/jackson-map-null-values-or-null-key) +- [Jackson – Working With Maps and Nulls](https://www.baeldung.com/jackson-map-null-values-or-null-key) - [Jackson – Decide What Fields Get Serialized/Deserialized](https://www.baeldung.com/jackson-field-serializable-deserializable-or-not) - [XML Serialization and Deserialization with Jackson](https://www.baeldung.com/jackson-xml-serialization-and-deserialization) - [Map Serialization and Deserialization with Jackson](https://www.baeldung.com/jackson-map) diff --git a/jackson-modules/jackson-custom-conversions/README.md b/jackson-modules/jackson-custom-conversions/README.md index 2f45a2f43b..68a48511d9 100644 --- a/jackson-modules/jackson-custom-conversions/README.md +++ b/jackson-modules/jackson-custom-conversions/README.md @@ -5,6 +5,6 @@ This module contains articles about Jackson custom conversions. ### Relevant Articles: - [Jackson – Custom Serializer](https://www.baeldung.com/jackson-custom-serialization) - [Getting Started with Custom Deserialization in Jackson](https://www.baeldung.com/jackson-deserialization) -- [Serialize Only Fields that meet a Custom Criteria with Jackson](https://www.baeldung.com/jackson-serialize-field-custom-criteria) +- [Serialize Only Fields That Meet a Custom Criteria With Jackson](https://www.baeldung.com/jackson-serialize-field-custom-criteria) - [Calling Default Serializer from Custom Serializer in Jackson](https://www.baeldung.com/jackson-call-default-serializer-from-custom-serializer) - [OffsetDateTime Serialization With Jackson](https://www.baeldung.com/java-jackson-offsetdatetime) diff --git a/javaxval/README.md b/javaxval/README.md index b7e19d5794..7420580f8e 100644 --- a/javaxval/README.md +++ b/javaxval/README.md @@ -4,11 +4,11 @@ This module contains articles about Bean Validation. ### Relevant Articles: - [Java Bean Validation Basics](https://www.baeldung.com/javax-validation) -- [Validating Container Elements with Bean Validation 2.0](https://www.baeldung.com/bean-validation-container-elements) +- [Validating Container Elements with Jakarta Bean Validation 3.0](https://www.baeldung.com/bean-validation-container-elements) - [Validations for Enum Types](https://www.baeldung.com/javax-validations-enums) - [Javax BigDecimal Validation](https://www.baeldung.com/javax-bigdecimal-validation) - [Grouping Javax Validation Constraints](https://www.baeldung.com/javax-validation-groups) - [Constraint Composition with Bean Validation](https://www.baeldung.com/java-bean-validation-constraint-composition) - [Using @NotNull on a Method Parameter](https://www.baeldung.com/java-notnull-method-parameter) - [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank) -- More articles: [[next -->]](../javaxval-2) \ No newline at end of file +- More articles: [[next -->]](../javaxval-2) diff --git a/jmeter/src/main/resources/summary-report/Summary-Report.jmx b/jmeter/src/main/resources/summary-report/Summary-Report.jmx new file mode 100644 index 0000000000..f7270344a4 --- /dev/null +++ b/jmeter/src/main/resources/summary-report/Summary-Report.jmx @@ -0,0 +1,88 @@ + + + + + + false + true + false + + + + + + + + continue + + false + 10 + + 5 + 1 + false + + + true + + + + + + + postman-echo.com + + https + + get?foo1=bar1&foo2=bar2 + GET + true + false + true + false + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + true + false + false + false + true + 0 + true + true + true + true + true + true + + + + + + + + + diff --git a/jmeter/src/main/resources/summary-report/Summary-Report.jtl b/jmeter/src/main/resources/summary-report/Summary-Report.jtl new file mode 100644 index 0000000000..67325e6c68 --- /dev/null +++ b/jmeter/src/main/resources/summary-report/Summary-Report.jtl @@ -0,0 +1,51 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect +1685956723691,969,HTTP Request,200,OK,Thread Group 1-1,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,964,0,765 +1685956723848,819,HTTP Request,200,OK,Thread Group 1-2,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,819,0,616 +1685956724660,194,HTTP Request,200,OK,Thread Group 1-1,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,193,0,0 +1685956724667,202,HTTP Request,200,OK,Thread Group 1-2,text,true,,685,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,202,0,0 +1685956724047,827,HTTP Request,200,OK,Thread Group 1-3,text,true,,681,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,827,0,620 +1685956724854,198,HTTP Request,200,OK,Thread Group 1-1,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,197,0,0 +1685956724247,827,HTTP Request,200,OK,Thread Group 1-4,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,825,0,604 +1685956724870,207,HTTP Request,200,OK,Thread Group 1-2,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,207,0,0 +1685956724874,214,HTTP Request,200,OK,Thread Group 1-3,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,211,0,0 +1685956725055,193,HTTP Request,200,OK,Thread Group 1-1,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,193,0,0 +1685956724448,819,HTTP Request,200,OK,Thread Group 1-5,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,808,0,607 +1685956725075,198,HTTP Request,200,OK,Thread Group 1-4,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,198,0,0 +1685956725089,208,HTTP Request,200,OK,Thread Group 1-3,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,208,0,0 +1685956725077,263,HTTP Request,200,OK,Thread Group 1-2,text,true,,687,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,252,0,0 +1685956725249,206,HTTP Request,200,OK,Thread Group 1-1,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,206,0,0 +1685956725268,199,HTTP Request,200,OK,Thread Group 1-5,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,199,0,0 +1685956725274,197,HTTP Request,200,OK,Thread Group 1-4,text,true,,683,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,197,0,0 +1685956725298,207,HTTP Request,200,OK,Thread Group 1-3,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,207,0,0 +1685956725341,204,HTTP Request,200,OK,Thread Group 1-2,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,203,0,0 +1685956725457,196,HTTP Request,200,OK,Thread Group 1-1,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,195,0,0 +1685956725468,200,HTTP Request,200,OK,Thread Group 1-5,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,199,0,0 +1685956725471,200,HTTP Request,200,OK,Thread Group 1-4,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,200,0,0 +1685956725507,208,HTTP Request,200,OK,Thread Group 1-3,text,true,,681,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,207,0,0 +1685956725546,204,HTTP Request,200,OK,Thread Group 1-2,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,203,0,0 +1685956725654,194,HTTP Request,200,OK,Thread Group 1-1,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,194,0,0 +1685956725669,199,HTTP Request,200,OK,Thread Group 1-5,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,199,0,0 +1685956725671,201,HTTP Request,200,OK,Thread Group 1-4,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,200,0,0 +1685956725716,207,HTTP Request,200,OK,Thread Group 1-3,text,true,,681,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,206,0,0 +1685956725752,202,HTTP Request,200,OK,Thread Group 1-2,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,202,0,0 +1685956725849,198,HTTP Request,200,OK,Thread Group 1-1,text,true,,681,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,198,0,0 +1685956725872,200,HTTP Request,200,OK,Thread Group 1-4,text,true,,681,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,200,0,0 +1685956725870,202,HTTP Request,200,OK,Thread Group 1-5,text,true,,683,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,202,0,0 +1685956725923,209,HTTP Request,200,OK,Thread Group 1-3,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,208,0,0 +1685956725955,215,HTTP Request,200,OK,Thread Group 1-2,text,true,,687,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,215,0,0 +1685956726049,197,HTTP Request,200,OK,Thread Group 1-1,text,true,,683,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,196,0,0 +1685956726073,198,HTTP Request,200,OK,Thread Group 1-5,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,197,0,0 +1685956726073,198,HTTP Request,200,OK,Thread Group 1-4,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,198,0,0 +1685956726132,210,HTTP Request,200,OK,Thread Group 1-3,text,true,,677,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,210,0,0 +1685956726171,202,HTTP Request,200,OK,Thread Group 1-2,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,202,0,0 +1685956726247,197,HTTP Request,200,OK,Thread Group 1-1,text,true,,679,143,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,197,0,0 +1685956726271,199,HTTP Request,200,OK,Thread Group 1-4,text,true,,677,143,4,4,https://postman-echo.com/get?foo1=bar1&foo2=bar2,199,0,0 +1685956726271,201,HTTP Request,200,OK,Thread Group 1-5,text,true,,679,143,4,4,https://postman-echo.com/get?foo1=bar1&foo2=bar2,200,0,0 +1685956726343,209,HTTP Request,200,OK,Thread Group 1-3,text,true,,677,143,4,4,https://postman-echo.com/get?foo1=bar1&foo2=bar2,209,0,0 +1685956726374,205,HTTP Request,200,OK,Thread Group 1-2,text,true,,677,143,4,4,https://postman-echo.com/get?foo1=bar1&foo2=bar2,205,0,0 +1685956726472,200,HTTP Request,200,OK,Thread Group 1-5,text,true,,681,143,3,3,https://postman-echo.com/get?foo1=bar1&foo2=bar2,200,0,0 +1685956726471,204,HTTP Request,200,OK,Thread Group 1-4,text,true,,681,143,3,3,https://postman-echo.com/get?foo1=bar1&foo2=bar2,200,0,0 +1685956726554,211,HTTP Request,200,OK,Thread Group 1-3,text,true,,679,143,3,3,https://postman-echo.com/get?foo1=bar1&foo2=bar2,210,0,0 +1685956726673,201,HTTP Request,200,OK,Thread Group 1-5,text,true,,677,143,2,2,https://postman-echo.com/get?foo1=bar1&foo2=bar2,200,0,0 +1685956726675,199,HTTP Request,200,OK,Thread Group 1-4,text,true,,683,143,2,2,https://postman-echo.com/get?foo1=bar1&foo2=bar2,199,0,0 +1685956726875,201,HTTP Request,200,OK,Thread Group 1-5,text,true,,679,143,1,1,https://postman-echo.com/get?foo1=bar1&foo2=bar2,201,0,0 diff --git a/json-modules/gson-2/README.md b/json-modules/gson-2/README.md index 40d5515567..5580479753 100644 --- a/json-modules/gson-2/README.md +++ b/json-modules/gson-2/README.md @@ -3,5 +3,5 @@ This module contains articles about Gson ### Relevant Articles: - +- [Solving Gson Parsing Errors](https://www.baeldung.com/gson-parsing-errors) diff --git a/jsoup/README.md b/jsoup/README.md index 42b30d4d83..3a8a7f0ebb 100644 --- a/jsoup/README.md +++ b/jsoup/README.md @@ -4,7 +4,7 @@ This module contains articles about jsoup. ### Relevant Articles: - [Parsing HTML in Java with Jsoup](https://www.baeldung.com/java-with-jsoup) -- [How to add proxy support to Jsoup?](https://www.baeldung.com/java-jsoup-proxy) +- [How to Add Proxy Support to Jsoup?](https://www.baeldung.com/java-jsoup-proxy) - [Preserving Line Breaks When Using Jsoup](https://www.baeldung.com/jsoup-line-breaks) ### Build the Project diff --git a/kubernetes-modules/Deployment_Vs_StatefulSet/Deployment/Deployment.yaml b/kubernetes-modules/deployment-and-statefulset-configs/Deployment/Deployment.yaml similarity index 100% rename from kubernetes-modules/Deployment_Vs_StatefulSet/Deployment/Deployment.yaml rename to kubernetes-modules/deployment-and-statefulset-configs/Deployment/Deployment.yaml diff --git a/kubernetes-modules/Deployment_Vs_StatefulSet/Deployment/PersitantVoulumeClaim.yaml b/kubernetes-modules/deployment-and-statefulset-configs/Deployment/PersitantVoulumeClaim.yaml similarity index 100% rename from kubernetes-modules/Deployment_Vs_StatefulSet/Deployment/PersitantVoulumeClaim.yaml rename to kubernetes-modules/deployment-and-statefulset-configs/Deployment/PersitantVoulumeClaim.yaml diff --git a/kubernetes-modules/Deployment_Vs_StatefulSet/Deployment/Service.yaml b/kubernetes-modules/deployment-and-statefulset-configs/Deployment/Service.yaml similarity index 100% rename from kubernetes-modules/Deployment_Vs_StatefulSet/Deployment/Service.yaml rename to kubernetes-modules/deployment-and-statefulset-configs/Deployment/Service.yaml diff --git a/kubernetes-modules/Deployment_Vs_StatefulSet/StatefulSets/PersistantVolumeClaim.yaml b/kubernetes-modules/deployment-and-statefulset-configs/StatefulSets/PersistantVolumeClaim.yaml similarity index 100% rename from kubernetes-modules/Deployment_Vs_StatefulSet/StatefulSets/PersistantVolumeClaim.yaml rename to kubernetes-modules/deployment-and-statefulset-configs/StatefulSets/PersistantVolumeClaim.yaml diff --git a/kubernetes-modules/Deployment_Vs_StatefulSet/StatefulSets/Service.yaml b/kubernetes-modules/deployment-and-statefulset-configs/StatefulSets/Service.yaml similarity index 100% rename from kubernetes-modules/Deployment_Vs_StatefulSet/StatefulSets/Service.yaml rename to kubernetes-modules/deployment-and-statefulset-configs/StatefulSets/Service.yaml diff --git a/kubernetes-modules/Deployment_Vs_StatefulSet/StatefulSets/StatefulSet.yaml b/kubernetes-modules/deployment-and-statefulset-configs/StatefulSets/StatefulSet.yaml similarity index 100% rename from kubernetes-modules/Deployment_Vs_StatefulSet/StatefulSets/StatefulSet.yaml rename to kubernetes-modules/deployment-and-statefulset-configs/StatefulSets/StatefulSet.yaml diff --git a/libraries-data-db/README.md b/libraries-data-db/README.md index 1062449693..a3a126c7a5 100644 --- a/libraries-data-db/README.md +++ b/libraries-data-db/README.md @@ -7,7 +7,7 @@ This module contains articles about database-related data processing libraries. - [Introduction to Reladomo](https://www.baeldung.com/reladomo) - [Introduction to ORMLite](https://www.baeldung.com/ormlite) - [Guide to Java Data Objects](https://www.baeldung.com/jdo) -- [Intro to JDO Queries 2/2](https://www.baeldung.com/jdo-queries) +- [Intro to JDO Queries](https://www.baeldung.com/jdo-queries) - [Introduction to HikariCP](https://www.baeldung.com/hikaricp) - [Guide to Ebean ORM](https://www.baeldung.com/ebean-orm) - [Introduction to Debezium](https://www.baeldung.com/debezium-intro) diff --git a/libraries-http-2/pom.xml b/libraries-http-2/pom.xml index d8479def3c..77498dd248 100644 --- a/libraries-http-2/pom.xml +++ b/libraries-http-2/pom.xml @@ -82,7 +82,31 @@ converter-gson ${retrofit.version} + + org.mockito + mockito-inline + ${mockito.version} + test + + + org.jmockit + jmockit + ${jmockit.version} + + + + + + maven-surefire-plugin + + + -javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar + + + + + 4.9.1 @@ -95,6 +119,7 @@ 5.1.9.RELEASE 1.0.3 3.2.12.RELEASE + 1.49 \ No newline at end of file diff --git a/libraries-http-2/src/main/java/com/baeldung/mock/url/UrlFetcher.java b/libraries-http-2/src/main/java/com/baeldung/mock/url/UrlFetcher.java new file mode 100644 index 0000000000..bb9ba4a5f9 --- /dev/null +++ b/libraries-http-2/src/main/java/com/baeldung/mock/url/UrlFetcher.java @@ -0,0 +1,23 @@ +package com.baeldung.mock.url; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +public class UrlFetcher { + + private URL url; + + public UrlFetcher(URL url) throws IOException { + this.url = url; + } + + public boolean isUrlAvailable() throws IOException { + return getResponseCode() == HttpURLConnection.HTTP_OK; + } + + private int getResponseCode() throws IOException { + HttpURLConnection con = (HttpURLConnection) this.url.openConnection(); + return con.getResponseCode(); + } +} diff --git a/libraries-http-2/src/test/java/com/baeldung/mock/url/MockHttpURLConnection.java b/libraries-http-2/src/test/java/com/baeldung/mock/url/MockHttpURLConnection.java new file mode 100644 index 0000000000..9df05fe0d0 --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/mock/url/MockHttpURLConnection.java @@ -0,0 +1,35 @@ +package com.baeldung.mock.url; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +public class MockHttpURLConnection extends HttpURLConnection { + + protected MockHttpURLConnection(URL url) { + super(url); + } + + @Override + public int getResponseCode() { + return responseCode; + } + + public void setResponseCode(int responseCode) { + this.responseCode = responseCode; + } + + @Override + public void disconnect() { + } + + @Override + public boolean usingProxy() { + return false; + } + + @Override + public void connect() throws IOException { + } + +} diff --git a/libraries-http-2/src/test/java/com/baeldung/mock/url/MockURLStreamHandler.java b/libraries-http-2/src/test/java/com/baeldung/mock/url/MockURLStreamHandler.java new file mode 100644 index 0000000000..1cc09dc2e9 --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/mock/url/MockURLStreamHandler.java @@ -0,0 +1,21 @@ +package com.baeldung.mock.url; + +import java.io.IOException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; + +public class MockURLStreamHandler extends URLStreamHandler { + + private MockHttpURLConnection mockHttpURLConnection; + + public MockURLStreamHandler(MockHttpURLConnection mockHttpURLConnection) { + this.mockHttpURLConnection = mockHttpURLConnection; + } + + @Override + protected URLConnection openConnection(URL url) throws IOException { + return this.mockHttpURLConnection; + } + +} diff --git a/libraries-http-2/src/test/java/com/baeldung/mock/url/MockURLStreamHandlerFactory.java b/libraries-http-2/src/test/java/com/baeldung/mock/url/MockURLStreamHandlerFactory.java new file mode 100644 index 0000000000..855c761b65 --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/mock/url/MockURLStreamHandlerFactory.java @@ -0,0 +1,19 @@ +package com.baeldung.mock.url; + +import java.net.URLStreamHandler; +import java.net.URLStreamHandlerFactory; + +public class MockURLStreamHandlerFactory implements URLStreamHandlerFactory { + + private MockHttpURLConnection mockHttpURLConnection; + + public MockURLStreamHandlerFactory(MockHttpURLConnection mockHttpURLConnection) { + this.mockHttpURLConnection = mockHttpURLConnection; + } + + @Override + public URLStreamHandler createURLStreamHandler(String protocol) { + return new MockURLStreamHandler(this.mockHttpURLConnection); + } + +} diff --git a/libraries-http-2/src/test/java/com/baeldung/mock/url/UrlFetcherJMockitUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/mock/url/UrlFetcherJMockitUnitTest.java new file mode 100644 index 0000000000..b99dcd282d --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/mock/url/UrlFetcherJMockitUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.mock.url; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.HttpURLConnection; +import java.net.URL; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import mockit.Expectations; +import mockit.Mocked; +import mockit.integration.junit5.JMockitExtension; + + +@ExtendWith(JMockitExtension.class) +class UrlFetcherJMockitUnitTest { + + @Test + void givenMockedUrl_whenRequestSent_thenIsUrlAvailableTrue(@Mocked URL anyURL, @Mocked HttpURLConnection mockConn) throws Exception { + new Expectations() {{ + mockConn.getResponseCode(); + result = HttpURLConnection.HTTP_OK; + }}; + + UrlFetcher fetcher = new UrlFetcher(new URL("https://www.baeldung.com/")); + assertTrue(fetcher.isUrlAvailable(), "Url should be available: "); + } + + @Test + void givenMockedUrl_whenRequestSent_thenIsUrlAvailableFalse(@Mocked URL anyURL, @Mocked HttpURLConnection mockConn) throws Exception { + new Expectations() {{ + mockConn.getResponseCode(); + result = HttpURLConnection.HTTP_INTERNAL_ERROR; + }}; + + UrlFetcher fetcher = new UrlFetcher(new URL("https://www.baeldung.com/")); + assertFalse(fetcher.isUrlAvailable(), "Url should NOT be available: "); + } + +} diff --git a/libraries-http-2/src/test/java/com/baeldung/mock/url/UrlFetcherMockitoUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/mock/url/UrlFetcherMockitoUnitTest.java new file mode 100644 index 0000000000..bd998e83b4 --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/mock/url/UrlFetcherMockitoUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.mock.url; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.HttpURLConnection; +import java.net.URL; + +import org.junit.jupiter.api.Test; + +class UrlFetcherMockitoUnitTest { + + @Test + void givenMockedUrl_whenRequestSent_thenIsUrlAvailableTrue() throws Exception { + HttpURLConnection mockHttpURLConnection = mock(HttpURLConnection.class); + when(mockHttpURLConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + + URL mockURL = mock(URL.class); + when(mockURL.openConnection()).thenReturn(mockHttpURLConnection); + + UrlFetcher fetcher = new UrlFetcher(mockURL); + assertTrue(fetcher.isUrlAvailable(), "Url should be available: "); + } + + @Test + void givenMockedUrl_whenRequestSent_thenIsUrlAvailableFalse() throws Exception { + HttpURLConnection mockHttpURLConnection = mock(HttpURLConnection.class); + when(mockHttpURLConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); + + URL mockURL = mock(URL.class); + when(mockURL.openConnection()).thenReturn(mockHttpURLConnection); + + UrlFetcher fetcher = new UrlFetcher(mockURL); + assertFalse(fetcher.isUrlAvailable(), "Url should NOT be available: "); + } + +} diff --git a/libraries-http-2/src/test/java/com/baeldung/mock/url/UrlFetcherUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/mock/url/UrlFetcherUnitTest.java new file mode 100644 index 0000000000..be3a784a99 --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/mock/url/UrlFetcherUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.mock.url; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.HttpURLConnection; +import java.net.URL; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class UrlFetcherUnitTest { + + private static MockHttpURLConnection mockHttpURLConnection; + + @BeforeAll + public static void setUp() { + mockHttpURLConnection = new MockHttpURLConnection(null); + URL.setURLStreamHandlerFactory(new MockURLStreamHandlerFactory(mockHttpURLConnection)); + } + + @Test + void givenMockedUrl_whenRequestSent_thenIsUrlAvailableTrue() throws Exception { + mockHttpURLConnection.setResponseCode(HttpURLConnection.HTTP_OK); + URL url = new URL("https://www.baeldung.com/"); + + UrlFetcher fetcher = new UrlFetcher(url); + assertTrue(fetcher.isUrlAvailable(), "Url should be available: "); + } + + @Test + void givenMockedUrl_whenRequestSent_thenIsUrlAvailableFalse() throws Exception { + mockHttpURLConnection.setResponseCode(HttpURLConnection.HTTP_FORBIDDEN); + URL url = new URL("https://www.baeldung.com/"); + + UrlFetcher fetcher = new UrlFetcher(url); + assertFalse(fetcher.isUrlAvailable(), "Url should NOT be available: "); + } + +} diff --git a/linux-bash-modules/json/README.md b/linux-bash-modules/linux-bash-json/README.md similarity index 100% rename from linux-bash-modules/json/README.md rename to linux-bash-modules/linux-bash-json/README.md diff --git a/linux-bash-modules/json/src/main/bash/fruit.json b/linux-bash-modules/linux-bash-json/src/main/bash/fruit.json similarity index 100% rename from linux-bash-modules/json/src/main/bash/fruit.json rename to linux-bash-modules/linux-bash-json/src/main/bash/fruit.json diff --git a/linux-bash-modules/json/src/main/bash/fruits.json b/linux-bash-modules/linux-bash-json/src/main/bash/fruits.json similarity index 100% rename from linux-bash-modules/json/src/main/bash/fruits.json rename to linux-bash-modules/linux-bash-json/src/main/bash/fruits.json diff --git a/linux-bash-modules/json/src/main/bash/jq.sh b/linux-bash-modules/linux-bash-json/src/main/bash/jq.sh similarity index 100% rename from linux-bash-modules/json/src/main/bash/jq.sh rename to linux-bash-modules/linux-bash-json/src/main/bash/jq.sh diff --git a/linux-bash-modules/json/src/main/bash/wikipedia.json b/linux-bash-modules/linux-bash-json/src/main/bash/wikipedia.json similarity index 100% rename from linux-bash-modules/json/src/main/bash/wikipedia.json rename to linux-bash-modules/linux-bash-json/src/main/bash/wikipedia.json diff --git a/linux-bash-modules/loops/README.md b/linux-bash-modules/linux-bash-loops/README.md similarity index 100% rename from linux-bash-modules/loops/README.md rename to linux-bash-modules/linux-bash-loops/README.md diff --git a/linux-bash-modules/loops/src/main/bash/find_directories.sh b/linux-bash-modules/linux-bash-loops/src/main/bash/find_directories.sh similarity index 100% rename from linux-bash-modules/loops/src/main/bash/find_directories.sh rename to linux-bash-modules/linux-bash-loops/src/main/bash/find_directories.sh diff --git a/linux-bash-modules/loops/src/main/bash/loop_directories.sh b/linux-bash-modules/linux-bash-loops/src/main/bash/loop_directories.sh similarity index 100% rename from linux-bash-modules/loops/src/main/bash/loop_directories.sh rename to linux-bash-modules/linux-bash-loops/src/main/bash/loop_directories.sh diff --git a/linux-bash-modules/read/README.md b/linux-bash-modules/linux-bash-read/README.md similarity index 100% rename from linux-bash-modules/read/README.md rename to linux-bash-modules/linux-bash-read/README.md diff --git a/linux-bash-modules/read/src/main/bash/file.csv b/linux-bash-modules/linux-bash-read/src/main/bash/file.csv similarity index 100% rename from linux-bash-modules/read/src/main/bash/file.csv rename to linux-bash-modules/linux-bash-read/src/main/bash/file.csv diff --git a/linux-bash-modules/read/src/main/bash/read_inputs.sh b/linux-bash-modules/linux-bash-read/src/main/bash/read_inputs.sh similarity index 100% rename from linux-bash-modules/read/src/main/bash/read_inputs.sh rename to linux-bash-modules/linux-bash-read/src/main/bash/read_inputs.sh diff --git a/linux-bash-modules/text/README.md b/linux-bash-modules/linux-bash-text/README.md similarity index 100% rename from linux-bash-modules/text/README.md rename to linux-bash-modules/linux-bash-text/README.md diff --git a/linux-bash-modules/text/src/main/bash/append_multiple_lines.sh b/linux-bash-modules/linux-bash-text/src/main/bash/append_multiple_lines.sh similarity index 100% rename from linux-bash-modules/text/src/main/bash/append_multiple_lines.sh rename to linux-bash-modules/linux-bash-text/src/main/bash/append_multiple_lines.sh diff --git a/linux-bash-modules/text/src/main/bash/remove_characters.sh b/linux-bash-modules/linux-bash-text/src/main/bash/remove_characters.sh similarity index 100% rename from linux-bash-modules/text/src/main/bash/remove_characters.sh rename to linux-bash-modules/linux-bash-text/src/main/bash/remove_characters.sh diff --git a/maven-modules/spring-bom/pom.xml b/maven-modules/spring-bom/pom.xml index 93d0bdc458..1bedbf75ab 100644 --- a/maven-modules/spring-bom/pom.xml +++ b/maven-modules/spring-bom/pom.xml @@ -37,7 +37,7 @@ - 4.3.8.RELEASE + 5.3.27 \ No newline at end of file diff --git a/messaging-modules/pom.xml b/messaging-modules/pom.xml index 71ff25d71b..6fd14f7c64 100644 --- a/messaging-modules/pom.xml +++ b/messaging-modules/pom.xml @@ -22,6 +22,7 @@ spring-amqp spring-apache-camel spring-jms + postgres-notify \ No newline at end of file diff --git a/messaging-modules/postgres-notify/.gitignore b/messaging-modules/postgres-notify/.gitignore new file mode 100644 index 0000000000..0776e6f133 --- /dev/null +++ b/messaging-modules/postgres-notify/.gitignore @@ -0,0 +1 @@ +/application-local.properties diff --git a/messaging-modules/postgres-notify/README.md b/messaging-modules/postgres-notify/README.md new file mode 100644 index 0000000000..32c1f6bf3e --- /dev/null +++ b/messaging-modules/postgres-notify/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Using PostgreSQL as a Message Broker](https://www.baeldung.com/spring-postgresql-message-broker) diff --git a/messaging-modules/postgres-notify/pom.xml b/messaging-modules/postgres-notify/pom.xml new file mode 100644 index 0000000000..174d66b7f5 --- /dev/null +++ b/messaging-modules/postgres-notify/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + postgres-notify + postgres-notify + PostgreSQL as a Message Broker + + + com.baeldung + messaging-modules + 0.0.1-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jdbc + + + org.postgresql + postgresql + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.projectlombok + lombok + true + + + + + + + 1.8 + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + instance1 + + + + org.springframework.boot + spring-boot-maven-plugin + + -Dserver.port=8081 + + + + + + + + \ No newline at end of file diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/Application.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/Application.java new file mode 100644 index 0000000000..b3b1f83d2f --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.messaging.postgresql; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/config/CacheConfiguration.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/config/CacheConfiguration.java new file mode 100644 index 0000000000..73763316c3 --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/config/CacheConfiguration.java @@ -0,0 +1,34 @@ +package com.baeldung.messaging.postgresql.config; + +import java.util.Arrays; +import java.util.Collection; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.concurrent.ConcurrentMapCache; +import org.springframework.cache.support.SimpleCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.ConcurrentLruCache; + +import com.baeldung.messaging.postgresql.domain.Order; + +@Configuration +public class CacheConfiguration { + + @Bean + Cache ordersCache(CacheManager cm) { + return cm.getCache("orders"); + } + + @Bean + @ConditionalOnMissingBean + CacheManager defaultCacheManager() { + SimpleCacheManager cm = new SimpleCacheManager(); + Cache cache = new ConcurrentMapCache("orders",false); + cm.setCaches(Arrays.asList(cache)); + + return cm; + } +} diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/config/ListenerConfiguration.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/config/ListenerConfiguration.java new file mode 100644 index 0000000000..b053ba8bc2 --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/config/ListenerConfiguration.java @@ -0,0 +1,25 @@ +package com.baeldung.messaging.postgresql.config; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.messaging.postgresql.service.NotifierService; +import com.baeldung.messaging.postgresql.service.NotificationHandler; + +import lombok.extern.slf4j.Slf4j; + +@Configuration +@Slf4j +public class ListenerConfiguration { + + @Bean + CommandLineRunner startListener(NotifierService notifier, NotificationHandler handler) { + return (args) -> { + log.info("Starting order listener thread..."); + Runnable listener = notifier.createNotificationHandler(handler); + Thread t = new Thread(listener, "order-listener"); + t.start(); + }; + } +} diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/config/NotifierConfiguration.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/config/NotifierConfiguration.java new file mode 100644 index 0000000000..51d6016c57 --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/config/NotifierConfiguration.java @@ -0,0 +1,30 @@ +package com.baeldung.messaging.postgresql.config; + +import java.util.Properties; + +import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; + +import com.baeldung.messaging.postgresql.service.NotifierService; +import com.zaxxer.hikari.util.DriverDataSource; + +@Configuration +public class NotifierConfiguration { + + @Bean + NotifierService notifier(DataSourceProperties props) { + + DriverDataSource ds = new DriverDataSource( + props.determineUrl(), + props.determineDriverClassName(), + new Properties(), + props.determineUsername(), + props.determinePassword()); + + JdbcTemplate tpl = new JdbcTemplate(ds); + + return new NotifierService(tpl); + } +} diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/controller/OrdersController.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/controller/OrdersController.java new file mode 100644 index 0000000000..70daa14abd --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/controller/OrdersController.java @@ -0,0 +1,53 @@ +package com.baeldung.messaging.postgresql.controller; + +import java.math.BigDecimal; +import java.util.Optional; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.messaging.postgresql.domain.Order; +import com.baeldung.messaging.postgresql.domain.OrderType; +import com.baeldung.messaging.postgresql.service.OrdersService; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@RestController +@RequiredArgsConstructor +@Slf4j +public class OrdersController { + + private final OrdersService orders; + + @PostMapping("/orders/sell") + public ResponseEntity postSellOrder(String symbol, BigDecimal quantity, BigDecimal price) { + log.info("postSellOrder: symbol={},quantity={},price={}", symbol,quantity,price); + Order order = orders.createOrder(OrderType.SELL, symbol, quantity, price); + return ResponseEntity.status(HttpStatus.CREATED).body(order); + } + + @PostMapping("/orders/buy") + public ResponseEntity postBuyOrder(String symbol, BigDecimal quantity, BigDecimal price) { + log.info("postBuyOrder: symbol={},quantity={},price={}", symbol,quantity,price); + Order order = orders.createOrder(OrderType.BUY, symbol, quantity, price); + return ResponseEntity.status(HttpStatus.CREATED).body(order); + } + + @GetMapping("/orders/{id}") + public ResponseEntity getOrderById(@PathVariable Long id) { + + Optional o = orders.findById(id); + if (o.isEmpty()) { + return ResponseEntity.notFound().build(); + } + + return ResponseEntity.ok(o.get()); + + } + +} diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/domain/Order.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/domain/Order.java new file mode 100644 index 0000000000..d7b19aa10d --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/domain/Order.java @@ -0,0 +1,21 @@ +package com.baeldung.messaging.postgresql.domain; + +import java.math.BigDecimal; + +import org.springframework.data.annotation.Id; +import org.springframework.data.relational.core.mapping.Table; + +import lombok.Data; +import lombok.ToString; + +@Data +@ToString +@Table(name = "orders") +public class Order { + @Id + private Long id; + private String symbol; + private OrderType orderType; + private BigDecimal price; + private BigDecimal quantity; +} diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/domain/OrderType.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/domain/OrderType.java new file mode 100644 index 0000000000..6c053bc25c --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/domain/OrderType.java @@ -0,0 +1,12 @@ +package com.baeldung.messaging.postgresql.domain; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +@Getter +public enum OrderType { + BUY('B'), + SELL('S'); + private final char c; +} diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/repository/OrdersRepository.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/repository/OrdersRepository.java new file mode 100644 index 0000000000..d131017930 --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/repository/OrdersRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.messaging.postgresql.repository; + +import org.springframework.data.repository.CrudRepository; + +import com.baeldung.messaging.postgresql.domain.Order; + +public interface OrdersRepository extends CrudRepository{ + +} diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotificationHandler.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotificationHandler.java new file mode 100644 index 0000000000..61b970f3a2 --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotificationHandler.java @@ -0,0 +1,31 @@ +package com.baeldung.messaging.postgresql.service; + +import java.util.Optional; +import java.util.function.Consumer; + +import org.postgresql.PGNotification; +import org.springframework.cache.Cache; +import org.springframework.stereotype.Component; + +import com.baeldung.messaging.postgresql.domain.Order; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Component +@Slf4j +@RequiredArgsConstructor +public class NotificationHandler implements Consumer{ + + private final OrdersService orders; + + @Override + public void accept(PGNotification t) { + log.info("Notification received: pid={}, name={}, param={}",t.getPID(),t.getName(),t.getParameter()); + Optional order = orders.findById(Long.valueOf(t.getParameter())); + if ( !order.isEmpty()) { + log.info("order details: {}", order.get()); + } + } + +} diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotifierService.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotifierService.java new file mode 100644 index 0000000000..bc8215c7b3 --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotifierService.java @@ -0,0 +1,55 @@ +package com.baeldung.messaging.postgresql.service; + +import java.sql.Connection; +import java.util.function.Consumer; + +import org.postgresql.PGConnection; +import org.postgresql.PGNotification; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.messaging.postgresql.domain.Order; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@RequiredArgsConstructor +public class NotifierService { + private static final String ORDERS_CHANNEL = "orders"; + private final JdbcTemplate tpl; + + + @Transactional + public void notifyOrderCreated(Order order) { + tpl.execute("NOTIFY " + ORDERS_CHANNEL + ", '" + order.getId() + "'"); + } + + public Runnable createNotificationHandler(Consumer consumer) { + + return () -> { + tpl.execute((Connection c) -> { + log.info("notificationHandler: sending LISTEN command..."); + c.createStatement().execute("LISTEN " + ORDERS_CHANNEL); + + PGConnection pgconn = c.unwrap(PGConnection.class); + + while(!Thread.currentThread().isInterrupted()) { + PGNotification[] nts = pgconn.getNotifications(10000); + if ( nts == null || nts.length == 0 ) { + continue; + } + + for( PGNotification nt : nts) { + consumer.accept(nt); + } + } + + return 0; + }); + + }; + } +} diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/OrdersService.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/OrdersService.java new file mode 100644 index 0000000000..cc369c1f3e --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/OrdersService.java @@ -0,0 +1,61 @@ +package com.baeldung.messaging.postgresql.service; + +import java.math.BigDecimal; +import java.util.Optional; + +import javax.sql.DataSource; + +import org.springframework.cache.Cache; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.messaging.postgresql.domain.Order; +import com.baeldung.messaging.postgresql.domain.OrderType; +import com.baeldung.messaging.postgresql.repository.OrdersRepository; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Service +@RequiredArgsConstructor +@Slf4j +public class OrdersService { + private final OrdersRepository repo; + private final NotifierService notifier; + private final Cache ordersCache; + + @Transactional + public Order createOrder(OrderType orderType, String symbol, BigDecimal quantity, BigDecimal price) { + + Order order = new Order(); + order.setOrderType(orderType); + order.setSymbol(symbol); + order.setQuantity(quantity); + order.setPrice(price); + order = repo.save(order); + + notifier.notifyOrderCreated(order); + + return order; + + } + + @Transactional(readOnly = true) + public Optional findById(Long id) { + Optional o = Optional.ofNullable(ordersCache.get(id, Order.class)); + if ( !o.isEmpty() ) { + log.info("findById: cache hit, id={}",id); + return o; + } + + log.info("findById: cache miss, id={}",id); + o = repo.findById(id); + if ( o.isEmpty()) { + return o; + } + + ordersCache.put(id, o.get()); + return o; + } + +} diff --git a/messaging-modules/postgres-notify/src/main/resources/application.properties b/messaging-modules/postgres-notify/src/main/resources/application.properties new file mode 100644 index 0000000000..836e01cdca --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/resources/application.properties @@ -0,0 +1,5 @@ +# Replace the properties below with proper values for your environment +spring.sql.init.mode=ALWAYS +#spring.datasource.url=jdbc:postgresql://some-postgresql-host/some-postgresql-database +#spring.datasource.username=your-postgresql-username +#spring.datasource.password=your-postgresql-password diff --git a/messaging-modules/postgres-notify/src/main/resources/schema.sql b/messaging-modules/postgres-notify/src/main/resources/schema.sql new file mode 100644 index 0000000000..fad33509bd --- /dev/null +++ b/messaging-modules/postgres-notify/src/main/resources/schema.sql @@ -0,0 +1,7 @@ +create table if not exists orders ( + id serial primary key, + symbol varchar(16) not null, + order_type varchar(8) not null, + price NUMERIC(10,2) not null, + quantity NUMERIC(10,2) not null +); diff --git a/messaging-modules/postgres-notify/src/test/java/com/baeldung/messaging/postgresql/ApplicationLiveTest.java b/messaging-modules/postgres-notify/src/test/java/com/baeldung/messaging/postgresql/ApplicationLiveTest.java new file mode 100644 index 0000000000..5311793fe7 --- /dev/null +++ b/messaging-modules/postgres-notify/src/test/java/com/baeldung/messaging/postgresql/ApplicationLiveTest.java @@ -0,0 +1,47 @@ +package com.baeldung.messaging.postgresql; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import com.baeldung.messaging.postgresql.domain.Order; + +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@Sql("/schema.sql") +class ApplicationLiveTest { + + + @LocalServerPort + int localPort; + + @Autowired + TestRestTemplate client; + + @Test + void whenCreateBuyOrder_thenSuccess() { + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + MultiValueMap data= new LinkedMultiValueMap<>(); + data.add("symbol", "BAEL"); + data.add("price", "14.56"); + data.add("quantity", "100"); + HttpEntity> request = new HttpEntity>(data, headers); + + client.postForEntity("http://localhost:" + localPort + "/orders/buy", data, Order.class); + + } + +} diff --git a/messaging-modules/postgres-notify/src/test/resources/application.properties b/messaging-modules/postgres-notify/src/test/resources/application.properties new file mode 100644 index 0000000000..ebc3ef54e1 --- /dev/null +++ b/messaging-modules/postgres-notify/src/test/resources/application.properties @@ -0,0 +1,3 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/baeldung +spring.datasource.username=baeldung +spring.datasource.password=SqD64PtsGhDXjn9f \ No newline at end of file diff --git a/messaging-modules/spring-jms/src/test/java/com/baeldung/spring/jms/testing/EmbeddedActiveMqIntegrationTest.java b/messaging-modules/spring-jms/src/test/java/com/baeldung/spring/jms/testing/EmbeddedActiveMqManualTest.java similarity index 95% rename from messaging-modules/spring-jms/src/test/java/com/baeldung/spring/jms/testing/EmbeddedActiveMqIntegrationTest.java rename to messaging-modules/spring-jms/src/test/java/com/baeldung/spring/jms/testing/EmbeddedActiveMqManualTest.java index 6644ee50ac..676dcb1dd8 100644 --- a/messaging-modules/spring-jms/src/test/java/com/baeldung/spring/jms/testing/EmbeddedActiveMqIntegrationTest.java +++ b/messaging-modules/spring-jms/src/test/java/com/baeldung/spring/jms/testing/EmbeddedActiveMqManualTest.java @@ -23,11 +23,11 @@ import org.springframework.jms.core.JmsTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.spring.jms.testing.EmbeddedActiveMqIntegrationTest.TestConfiguration; +import com.baeldung.spring.jms.testing.EmbeddedActiveMqManualTest.TestConfiguration; @RunWith(SpringRunner.class) @ContextConfiguration(classes = { TestConfiguration.class }) -public class EmbeddedActiveMqIntegrationTest { +public class EmbeddedActiveMqManualTest { @ClassRule public static EmbeddedActiveMQBroker embeddedBroker = new EmbeddedActiveMQBroker(); diff --git a/patterns-modules/design-patterns-structural/README.md b/patterns-modules/design-patterns-structural/README.md index 996b500842..7a9c7acf4d 100644 --- a/patterns-modules/design-patterns-structural/README.md +++ b/patterns-modules/design-patterns-structural/README.md @@ -1,7 +1,7 @@ ### Relevant Articles: - [Facade Design Pattern in Java](https://www.baeldung.com/java-facade-pattern) - [Proxy, Decorator, Adapter and Bridge Patterns](https://www.baeldung.com/java-structural-design-patterns) -- [Composite Design pattern in Java](https://www.baeldung.com/java-composite-pattern) +- [Composite Design Pattern in Java](https://www.baeldung.com/java-composite-pattern) - [The Decorator Pattern in Java](https://www.baeldung.com/java-decorator-pattern) - [The Adapter Pattern in Java](https://www.baeldung.com/java-adapter-pattern) - [The Proxy Pattern in Java](https://www.baeldung.com/java-proxy-pattern) diff --git a/persistence-modules/blaze-persistence/pom.xml b/persistence-modules/blaze-persistence/pom.xml index 1162de67fc..55b9831c26 100644 --- a/persistence-modules/blaze-persistence/pom.xml +++ b/persistence-modules/blaze-persistence/pom.xml @@ -8,10 +8,10 @@ blaze-persistence - org.springframework.boot - spring-boot-starter-parent - 2.4.0 - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 @@ -42,7 +42,7 @@ com.blazebit - blaze-persistence-integration-hibernate-5.4 + blaze-persistence-integration-hibernate-5.6 @@ -64,7 +64,7 @@ com.blazebit - blaze-persistence-integration-spring-data-2.4 + blaze-persistence-integration-spring-data-2.7 @@ -81,8 +81,8 @@ - org.springframework - spring-test + org.springframework.boot + spring-boot-starter-test test diff --git a/persistence-modules/blaze-persistence/src/main/resources/application.properties b/persistence-modules/blaze-persistence/src/main/resources/application.properties index de4a62720a..4d0dbc94df 100644 --- a/persistence-modules/blaze-persistence/src/main/resources/application.properties +++ b/persistence-modules/blaze-persistence/src/main/resources/application.properties @@ -6,4 +6,5 @@ spring.datasource.url=jdbc:h2:mem:test spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=sa -spring.jpa.database-platform=org.hibernate.dialect.H2Dialect \ No newline at end of file +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.defer-datasource-initialization=true \ No newline at end of file diff --git a/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PersonUnitTest.java b/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PersonUnitTest.java index 16434d52d0..13e9b5afd3 100644 --- a/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PersonUnitTest.java +++ b/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PersonUnitTest.java @@ -1,21 +1,19 @@ package com.baeldung; -import com.baeldung.model.Person; -import com.baeldung.model.Post; -import com.baeldung.repository.PersonRepository; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; -@ContextConfiguration(classes = TestContextConfig.class) -@ExtendWith(SpringExtension.class) +import com.baeldung.model.Person; +import com.baeldung.model.Post; +import com.baeldung.repository.PersonRepository; + +@SpringBootTest public class PersonUnitTest { @Autowired diff --git a/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PostUnitTest.java b/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PostUnitTest.java index 0af01de088..395c106356 100644 --- a/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PostUnitTest.java +++ b/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PostUnitTest.java @@ -1,23 +1,21 @@ package com.baeldung; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + import com.baeldung.model.Post; import com.baeldung.repository.PostRepository; import com.baeldung.repository.PostViewRepository; import com.baeldung.view.PostView; import com.baeldung.view.PostWithAuthorView; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -@ContextConfiguration(classes = TestContextConfig.class) -@ExtendWith(SpringExtension.class) +@SpringBootTest public class PostUnitTest { @Autowired @@ -36,8 +34,7 @@ public class PostUnitTest { @Test public void givenPostIdAndAuthorName_whenFind_thenReturnCorrectResult() { - final Iterable listIterable = - postRepository.findBy("Spring", "Peter"); + final Iterable listIterable = postRepository.findBy("Spring", "Peter"); final List list = new ArrayList<>(); listIterable.forEach(list::add); assertEquals(4, list.size()); @@ -50,5 +47,4 @@ public class PostUnitTest { listIterable.forEach(list::add); assertEquals(7, list.size()); } - } diff --git a/persistence-modules/blaze-persistence/src/test/java/com/baeldung/TestContextConfig.java b/persistence-modules/blaze-persistence/src/test/java/com/baeldung/TestContextConfig.java deleted file mode 100644 index 1df1fb21d9..0000000000 --- a/persistence-modules/blaze-persistence/src/test/java/com/baeldung/TestContextConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung; - -import com.blazebit.persistence.integration.view.spring.EnableEntityViews; -import com.blazebit.persistence.spring.data.repository.config.EnableBlazeRepositories; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("com.baeldung") -@EnableEntityViews(basePackages = {"com.baeldung.view"}) -@EnableBlazeRepositories(basePackages = "com.baeldung.repository") -public class TestContextConfig { - - -} diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java index d559e5a6c2..b326363c60 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java @@ -10,6 +10,16 @@ public class Address { private String country; private int zipCode; + public Address(String addressLine1, String addressLine2, String city, String country, int zipCode) { + this.addressLine1 = addressLine1; + this.addressLine2 = addressLine2; + this.city = city; + this.country = country; + this.zipCode = zipCode; + } + + public Address() {} + public String getAddressLine1() { return addressLine1; } diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java index f50d8fd7cc..ea92d516ae 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java @@ -2,19 +2,13 @@ package com.baeldung.hibernate.customtypes; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.metamodel.spi.ValueAccess; import org.hibernate.usertype.CompositeUserType; -import org.hibernate.usertype.UserType; import java.io.Serializable; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; import java.util.Objects; -public class AddressType implements CompositeUserType
, UserType
{ +public class AddressType implements CompositeUserType
{ @Override public Object getPropertyValue(Address component, int property) throws HibernateException { @@ -39,7 +33,8 @@ public class AddressType implements CompositeUserType
, UserType
, UserType
returnedClass() { return Address.class; @@ -73,36 +63,6 @@ public class AddressType implements CompositeUserType
, UserType
{ +public class PhoneNumberType implements CompositeUserType { @Override - public int getSqlType() { - return Types.INTEGER; + public Object getPropertyValue(PhoneNumber component, int property) throws HibernateException { + switch (property) { + case 0: + return component.getCountryCode(); + case 1: + return component.getCityCode(); + case 2: + return component.getNumber(); + default: + throw new IllegalArgumentException(property + " is an invalid property index for class type " + component.getClass().getName()); + } + } + + @Override + public PhoneNumber instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) { + return new PhoneNumber(values.getValue(0, Integer.class), values.getValue(1, Integer.class), values.getValue(2,Integer.class)); + } + + @Override + public Class embeddable() { + return PhoneNumber.class; } @Override @@ -37,32 +54,6 @@ public class PhoneNumberType implements UserType { return x.hashCode(); } - @Override - public PhoneNumber nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { - int countryCode = rs.getInt(position); - - if (rs.wasNull()) - return null; - - int cityCode = rs.getInt(position); - int number = rs.getInt(position); - - return new PhoneNumber(countryCode, cityCode, number); - } - - @Override - public void nullSafeSet(PreparedStatement st, PhoneNumber value, int index, SharedSessionContractImplementor session) throws SQLException { - if (Objects.isNull(value)) { - st.setNull(index, Types.INTEGER); - st.setNull(index+1, Types.INTEGER); - st.setNull(index+2, Types.INTEGER); - } else { - st.setInt(index, value.getCountryCode()); - st.setInt(index+1, value.getCityCode()); - st.setInt(index+2, value.getNumber()); - } - } - @Override public PhoneNumber deepCopy(PhoneNumber value) { if (Objects.isNull(value)) diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java index f9a7ac5902..2402531869 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java @@ -1,8 +1,9 @@ package com.baeldung.hibernate.customtypes; +import java.io.Serializable; import java.util.Objects; -public class Salary { +public class Salary implements Serializable { private Long amount; private String currency; diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java index 69e34c1363..49294abe89 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java @@ -1,10 +1,6 @@ package com.baeldung.hibernate.customtypes; -import org.hibernate.HibernateException; -import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.metamodel.spi.ValueAccess; -import org.hibernate.usertype.CompositeUserType; import org.hibernate.usertype.DynamicParameterizedType; import org.hibernate.usertype.UserType; @@ -16,38 +12,13 @@ import java.sql.Types; import java.util.Objects; import java.util.Properties; -public class SalaryType implements UserType, CompositeUserType, DynamicParameterizedType { +public class SalaryType implements UserType, DynamicParameterizedType { private String localCurrency; - @Override - public Object getPropertyValue(Salary component, int property) throws HibernateException { - - switch (property) { - case 0: - return component.getAmount(); - case 1: - return component.getCurrency(); - default: - throw new IllegalArgumentException(property + - " is an invalid property index for class type " + - component.getClass().getName()); - } - } - - @Override - public Salary instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) { - return null; - } - - @Override - public Class embeddable() { - return Salary.class; - } - @Override public int getSqlType() { - return Types.BIGINT; + return Types.VARCHAR; } @Override @@ -74,12 +45,12 @@ public class SalaryType implements UserType, CompositeUserType, @Override public Salary nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { Salary salary = new Salary(); - salary.setAmount(rs.getLong(position)); - if (rs.wasNull()) - return null; + String salaryValue = rs.getString(position); - salary.setCurrency(rs.getString(position)); + salary.setAmount(Long.parseLong(salaryValue.split(" ")[1])); + + salary.setCurrency(salaryValue.split(" ")[0]); return salary; } @@ -87,13 +58,11 @@ public class SalaryType implements UserType, CompositeUserType, @Override public void nullSafeSet(PreparedStatement st, Salary value, int index, SharedSessionContractImplementor session) throws SQLException { if (Objects.isNull(value)) - st.setNull(index, Types.BIGINT); + st.setNull(index, Types.VARCHAR); else { - - st.setLong(index, SalaryCurrencyConvertor.convert( - value.getAmount(), - value.getCurrency(), localCurrency)); - st.setString(index + 1, value.getCurrency()); + Long salaryValue = SalaryCurrencyConvertor.convert(value.getAmount(), + value.getCurrency(), localCurrency); + st.setString(index, value.getCurrency() + " " + salaryValue); } } @@ -117,7 +86,7 @@ public class SalaryType implements UserType, CompositeUserType, @Override public Serializable disassemble(Salary value) { - return (Serializable) deepCopy(value); + return deepCopy(value); } @Override diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java index 9da3a90034..8e7a71c49b 100644 --- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java +++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java @@ -11,10 +11,12 @@ import org.junit.Test; import jakarta.persistence.TypedQuery; import java.time.LocalDate; import java.util.HashMap; +import java.util.List; import java.util.Map; import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class HibernateCustomTypesIntegrationTest { @@ -74,12 +76,18 @@ public class HibernateCustomTypesIntegrationTest { doInHibernate(this::sessionFactory, session -> { session.save(e); + session.flush(); + session.refresh(e); TypedQuery query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipCode = :pinCode", OfficeEmployee.class); query.setParameter("pinCode",100); - int size = query.getResultList().size(); + final List resultList = query.getResultList(); + int size = resultList.size(); assertEquals(1, size); + assertNotNull(resultList.get(0).getEmployeeNumber()); + assertNotNull(resultList.get(0).getEmpAddress()); + assertNotNull(resultList.get(0).getSalary()); }); } diff --git a/persistence-modules/hibernate-enterprise/README.md b/persistence-modules/hibernate-enterprise/README.md index 1a86c32afa..81707c6015 100644 --- a/persistence-modules/hibernate-enterprise/README.md +++ b/persistence-modules/hibernate-enterprise/README.md @@ -5,9 +5,9 @@ This module contains articles about enterprise concerns such as Multitenancy, Er ### Relevant articles: - [Introduction to Hibernate Spatial](https://www.baeldung.com/hibernate-spatial) -- [A Guide to Multitenancy in Hibernate 5](https://www.baeldung.com/hibernate-5-multitenancy) +- [A Guide to Multitenancy in Hibernate 6](https://www.baeldung.com/hibernate-6-multitenancy) - [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) - [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) - [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set) - [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels) -- [Hibernate: save, persist, update, merge, saveOrUpdate](https://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) \ No newline at end of file +- [Hibernate: save, persist, update, merge, saveOrUpdate](https://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) diff --git a/persistence-modules/hibernate-mapping-2/README.md b/persistence-modules/hibernate-mapping-2/README.md index 36c9f8c304..9994640f1a 100644 --- a/persistence-modules/hibernate-mapping-2/README.md +++ b/persistence-modules/hibernate-mapping-2/README.md @@ -7,3 +7,4 @@ This module contains articles about Hibernate Mappings. - [Hibernate Many to Many Annotation Tutorial](https://www.baeldung.com/hibernate-many-to-many) - [Boolean Converters in Hibernate 6](https://www.baeldung.com/java-hibernate-6-boolean-converters) - [Generate UUIDs as Primary Keys With Hibernate](https://www.baeldung.com/java-hibernate-uuid-primary-key) +- [Understanding JPA/Hibernate Associations](https://www.baeldung.com/jpa-hibernate-associations) diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml index b70fd0daec..b96b24582e 100644 --- a/persistence-modules/java-jpa/pom.xml +++ b/persistence-modules/java-jpa/pom.xml @@ -69,6 +69,11 @@ javax.annotation-api ${javax.annotation.version} + + mysql + mysql-connector-java + ${mysql.version} + @@ -130,6 +135,7 @@ 2.1.214 4.0.0 1.3.2 + 8.0.33 \ No newline at end of file diff --git a/persistence-modules/querydsl/src/test/java/com/baeldung/dao/PersonDaoIntegrationTest.java b/persistence-modules/querydsl/src/test/java/com/baeldung/dao/PersonDaoIntegrationTest.java index e9cf679c43..879b4238db 100644 --- a/persistence-modules/querydsl/src/test/java/com/baeldung/dao/PersonDaoIntegrationTest.java +++ b/persistence-modules/querydsl/src/test/java/com/baeldung/dao/PersonDaoIntegrationTest.java @@ -25,7 +25,7 @@ public class PersonDaoIntegrationTest { // @Test - public void testCreation() { + public void givenExistingPersons_whenFindingPersonByFirstName_thenFound() { personDao.save(new Person("Erich", "Gamma")); final Person person = new Person("Kent", "Beck"); personDao.save(person); @@ -36,7 +36,7 @@ public class PersonDaoIntegrationTest { } @Test - public void testMultipleFilter() { + public void givenExistingPersons_whenFindingPersonByFirstNameAndSurName_thenFound() { personDao.save(new Person("Erich", "Gamma")); final Person person = personDao.save(new Person("Ralph", "Beck")); final Person person2 = personDao.save(new Person("Ralph", "Johnson")); @@ -47,7 +47,7 @@ public class PersonDaoIntegrationTest { } @Test - public void testOrdering() { + public void givenExistingPersons_whenFindingPersonByFirstNameInDescendingOrder_thenFound() { final Person person = personDao.save(new Person("Kent", "Gamma")); personDao.save(new Person("Ralph", "Johnson")); final Person person2 = personDao.save(new Person("Kent", "Zivago")); @@ -58,7 +58,7 @@ public class PersonDaoIntegrationTest { } @Test - public void testMaxAge() { + public void givenExistingPersons_whenFindingMaxAge_thenFound() { personDao.save(new Person("Kent", "Gamma", 20)); personDao.save(new Person("Ralph", "Johnson", 35)); personDao.save(new Person("Kent", "Zivago", 30)); @@ -68,7 +68,7 @@ public class PersonDaoIntegrationTest { } @Test - public void testMaxAgeByName() { + public void givenExistingPersons_whenFindingMaxAgeByName_thenFound() { personDao.save(new Person("Kent", "Gamma", 20)); personDao.save(new Person("Ralph", "Johnson", 35)); personDao.save(new Person("Kent", "Zivago", 30)); diff --git a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java index 664ed1d0c3..63f9f1c9e7 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java @@ -38,7 +38,7 @@ public class JedisIntegrationTest { redisServer = RedisServer.builder() .port(port) - .setting("maxheap 128M") + .setting("maxmemory 128M") .build(); redisServer.start(); diff --git a/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java index b80cae98d8..c4a24f5d05 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java @@ -34,7 +34,7 @@ public class RedissonConfigurationIntegrationTest { redisServer = RedisServer.builder() .port(port) - .setting("maxheap 128M") + .setting("maxmemory 128M") .build(); redisServer.start(); } diff --git a/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java index 79581df989..aeda20435b 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java @@ -32,7 +32,7 @@ public class RedissonIntegrationTest { public static void setUp() { redisServer = RedisServer.builder() .port(6379) - .setting("maxheap 128M") + .setting("maxmemory 128M") .build(); redisServer.start(); client = Redisson.create(); diff --git a/persistence-modules/redis/src/test/java/com/baeldung/redis/deleteeverything/DeleteEverythingInRedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/redis/deleteeverything/DeleteEverythingInRedisIntegrationTest.java index 54123afdea..84fc060e2f 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/redis/deleteeverything/DeleteEverythingInRedisIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/redis/deleteeverything/DeleteEverythingInRedisIntegrationTest.java @@ -25,7 +25,7 @@ public class DeleteEverythingInRedisIntegrationTest { redisServer = RedisServer.builder() .port(port) - .setting("maxheap 128M") + .setting("maxmemory 128M") .build(); redisServer.start(); diff --git a/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java index 5c325e8ea0..7ba7ff4310 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/NaiveApproachIntegrationTest.java @@ -27,7 +27,7 @@ public class NaiveApproachIntegrationTest { redisServer = RedisServer.builder() .port(port) - .setting("maxheap 128M") + .setting("maxmemory 128M") .build(); } diff --git a/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java index 838d0144dc..ff00b6ddc6 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/redis_scan/ScanStrategyIntegrationTest.java @@ -33,7 +33,7 @@ public class ScanStrategyIntegrationTest { redisServer = RedisServer.builder() .port(port) - .setting("maxheap 128M") + .setting("maxmemory 128M") .build(); } diff --git a/persistence-modules/spring-data-jpa-annotations/README.md b/persistence-modules/spring-data-jpa-annotations/README.md index d7e6189ae5..2b2805b92b 100644 --- a/persistence-modules/spring-data-jpa-annotations/README.md +++ b/persistence-modules/spring-data-jpa-annotations/README.md @@ -5,7 +5,7 @@ This module contains articles about annotations used in Spring Data JPA ### Relevant articles - [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) -- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) +- [Jpa @Embedded and @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) - [Spring JPA @Embedded and @EmbeddedId](https://www.baeldung.com/spring-jpa-embedded-method-parameters) - [Programmatic Transaction Management in Spring](https://www.baeldung.com/spring-programmatic-transaction-management) - [JPA Entity Lifecycle Events](https://www.baeldung.com/jpa-entity-lifecycle-events) diff --git a/persistence-modules/spring-data-jpa-enterprise/README.md b/persistence-modules/spring-data-jpa-enterprise/README.md index 08fa55c14e..d1039dcc50 100644 --- a/persistence-modules/spring-data-jpa-enterprise/README.md +++ b/persistence-modules/spring-data-jpa-enterprise/README.md @@ -6,7 +6,7 @@ This module contains articles about Spring Data JPA used in enterprise applicati - [Spring Data Java 8 Support](https://www.baeldung.com/spring-data-java-8) - [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test) -- [A Guide to Spring’s Open Session In View](https://www.baeldung.com/spring-open-session-in-view) +- [A Guide to Spring’s Open Session in View](https://www.baeldung.com/spring-open-session-in-view) - [Working with Lazy Element Collections in JPA](https://www.baeldung.com/java-jpa-lazy-collections) - [Custom Naming Convention with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-custom-naming) - [Partial Data Update With Spring Data](https://www.baeldung.com/spring-data-partial-update) diff --git a/persistence-modules/spring-data-jpa-query-2/README.md b/persistence-modules/spring-data-jpa-query-2/README.md index 8005bc0e19..e091bc1d99 100644 --- a/persistence-modules/spring-data-jpa-query-2/README.md +++ b/persistence-modules/spring-data-jpa-query-2/README.md @@ -9,7 +9,7 @@ This module contains articles about querying data using Spring Data JPA . - [Hibernate Pagination](https://www.baeldung.com/hibernate-pagination) - [Sorting with Hibernate](https://www.baeldung.com/hibernate-sort) - [Stored Procedures with Hibernate](https://www.baeldung.com/stored-procedures-with-hibernate-tutorial) -- [Eager/Lazy Loading In Hibernate](https://www.baeldung.com/hibernate-lazy-eager-loading) +- [Eager/Lazy Loading in Hibernate](https://www.baeldung.com/hibernate-lazy-eager-loading) - [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) - More articles: [[<-- prev]](../spring-data-jpa-query)[[more -->]](../spring-data-jpa-query-3) diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md index dc94ba41d0..12eeddae7f 100644 --- a/persistence-modules/spring-data-jpa-repo-2/README.md +++ b/persistence-modules/spring-data-jpa-repo-2/README.md @@ -10,4 +10,5 @@ - [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-3/README.md b/persistence-modules/spring-data-jpa-repo-3/README.md index 2ed2dc8896..93cc9379f7 100644 --- a/persistence-modules/spring-data-jpa-repo-3/README.md +++ b/persistence-modules/spring-data-jpa-repo-3/README.md @@ -6,4 +6,5 @@ This module contains articles about Spring Data JPA. - [New CRUD Repository Interfaces in Spring Data 3](https://www.baeldung.com/spring-data-3-crud-repository-interfaces) - [How to Persist a List of String in JPA?](https://www.baeldung.com/java-jpa-persist-string-list) - [Hibernate Natural IDs in Spring Boot](https://www.baeldung.com/spring-boot-hibernate-natural-ids) +- [Correct Use of flush() in JPA](https://www.baeldung.com/spring-jpa-flush) - More articles: [[<-- prev]](../spring-data-jpa-repo-2) diff --git a/persistence-modules/spring-data-jpa-repo/README.md b/persistence-modules/spring-data-jpa-repo/README.md index 6ffb402477..43097a8c1e 100644 --- a/persistence-modules/spring-data-jpa-repo/README.md +++ b/persistence-modules/spring-data-jpa-repo/README.md @@ -10,7 +10,6 @@ This module contains articles about repositories in Spring Data JPA - [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) - [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) - [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) -- [TRUNCATE TABLE in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-truncate-table) - More articles: [[--> next]](../spring-data-jpa-repo-2) ### Eclipse Config diff --git a/pom.xml b/pom.xml index 8a494719a8..7c726c1015 100644 --- a/pom.xml +++ b/pom.xml @@ -334,7 +334,6 @@ parent-spring-6 parent-java - checker-framework core-java-modules/core-java-8 @@ -366,10 +365,10 @@ muleesb web-modules/java-lite web-modules/restx - web-modules/jee-7 persistence-modules/deltaspike persistence-modules/hibernate-ogm persistence-modules/java-cassandra + persistence-modules/spring-data-cassandra-reactive @@ -428,9 +427,7 @@ spring-security-modules/spring-security-ldap spring-soap - spring-static-resources spring-swagger-codegen - testing-modules video-tutorials @@ -516,7 +513,6 @@ parent-spring-6 parent-java - checker-framework core-java-modules/core-java-8 @@ -547,10 +543,10 @@ muleesb web-modules/java-lite web-modules/restx - web-modules/jee-7 persistence-modules/deltaspike persistence-modules/hibernate-ogm persistence-modules/java-cassandra + persistence-modules/spring-data-cassandra-reactive @@ -601,9 +597,7 @@ spring-security-modules/spring-security-ldap spring-soap - spring-static-resources spring-swagger-codegen - testing-modules video-tutorials @@ -770,6 +764,7 @@ asciidoctor aws-modules + checker-framework couchbase core-groovy-modules @@ -801,7 +796,7 @@ quarkus-modules spring-reactive-modules spring-swagger-codegen/custom-validations-opeanpi-codegen - testing-modules/testing-assertions + testing-modules testing-modules/mockito-simple rule-engines-modules @@ -811,6 +806,7 @@ lightrun tablesaw + image-compressing geotools jws @@ -922,6 +918,7 @@ spring-state-machine spring-shell spring-spel + spring-static-resources spring-threads spring-vault spring-websockets @@ -1028,6 +1025,7 @@ asciidoctor aws-modules + checker-framework couchbase core-groovy-modules @@ -1063,7 +1061,7 @@ quarkus-modules spring-reactive-modules spring-swagger-codegen/custom-validations-opeanpi-codegen - testing-modules/testing-assertions + testing-modules testing-modules/mockito-simple rule-engines-modules @@ -1073,6 +1071,7 @@ lightrun tablesaw + image-compressing geotools jws @@ -1185,6 +1184,7 @@ spring-state-machine spring-shell spring-spel + spring-static-resources spring-threads spring-vault spring-websockets diff --git a/security-modules/oauth2-framework-impl/README.md b/security-modules/oauth2-framework-impl/README.md index ae28c1b511..e3d9f0c4ee 100644 --- a/security-modules/oauth2-framework-impl/README.md +++ b/security-modules/oauth2-framework-impl/README.md @@ -4,4 +4,4 @@ This module contains articles about the implementation of OAuth2 with Java EE. ### Relevant Articles -- [Implementing The OAuth 2.0 Authorization Framework Using Jakarta EE](https://www.baeldung.com/java-ee-oauth2-implementation) +- [Implementing the Oauth 2.0 Authorization Framework Using Jakarta EE](https://www.baeldung.com/java-ee-oauth2-implementation) diff --git a/security-modules/pom.xml b/security-modules/pom.xml index d0edced4e0..b779c0d46d 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 + java-ee-8-security-api jee-7-security jjwt jwt @@ -29,4 +29,4 @@ 3.3.2 - \ No newline at end of file + diff --git a/server-modules/undertow/pom.xml b/server-modules/undertow/pom.xml index 7d446c29d2..42a46d9508 100644 --- a/server-modules/undertow/pom.xml +++ b/server-modules/undertow/pom.xml @@ -32,7 +32,6 @@ org.apache.maven.plugins maven-jar-plugin - ${maven-jar-plugin.version} diff --git a/server-modules/wildfly/pom.xml b/server-modules/wildfly/pom.xml index af742c7bd3..fece3c9866 100644 --- a/server-modules/wildfly/pom.xml +++ b/server-modules/wildfly/pom.xml @@ -63,7 +63,6 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} @@ -75,8 +74,4 @@ - - 3.3.2 - - \ No newline at end of file diff --git a/spf4j/pom.xml b/spf4j/pom.xml index 6d325947cf..9d747f11dc 100644 --- a/spf4j/pom.xml +++ b/spf4j/pom.xml @@ -19,4 +19,9 @@ spf4j-aspects-app + + 1.10.2 + 8.9.0 + 3.1.1 + \ No newline at end of file diff --git a/spf4j/spf4j-aspects-app/pom.xml b/spf4j/spf4j-aspects-app/pom.xml index 3eccdd879a..9769ff77f3 100644 --- a/spf4j/spf4j-aspects-app/pom.xml +++ b/spf4j/spf4j-aspects-app/pom.xml @@ -45,7 +45,7 @@ org.apache.avro avro - 1.10.2 + ${avro.version} @@ -59,7 +59,6 @@ org.apache.maven.plugins maven-dependency-plugin - ${dependency.plugin.version} copy-dependencies @@ -91,9 +90,4 @@ - - 8.9.0 - 3.1.1 - - \ No newline at end of file diff --git a/spf4j/spf4j-core-app/pom.xml b/spf4j/spf4j-core-app/pom.xml index 20251860aa..ee82ea869a 100644 --- a/spf4j/spf4j-core-app/pom.xml +++ b/spf4j/spf4j-core-app/pom.xml @@ -51,7 +51,7 @@ org.apache.avro avro - 1.10.2 + ${avro.version} @@ -65,7 +65,6 @@ org.apache.maven.plugins maven-dependency-plugin - ${dependency.plugin.version} copy-dependencies @@ -97,9 +96,4 @@ - - 8.9.0 - 3.1.1 - - \ No newline at end of file diff --git a/spring-actuator/pom.xml b/spring-actuator/pom.xml index 48dae45940..20b80d9924 100644 --- a/spring-actuator/pom.xml +++ b/spring-actuator/pom.xml @@ -19,7 +19,7 @@ jakarta.servlet jakarta.servlet-api - 5.0.0 + ${jakarta.servlet-api.version} provided @@ -49,7 +49,6 @@ org.apache.maven.plugins maven-war-plugin - 3.3.2 @@ -68,6 +67,7 @@ + 5.0.0 3.0.6 11.0.15 diff --git a/spring-aop-2/pom.xml b/spring-aop-2/pom.xml index cb84ed4ca2..e4748cdcbf 100644 --- a/spring-aop-2/pom.xml +++ b/spring-aop-2/pom.xml @@ -44,7 +44,6 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} false @@ -54,7 +53,6 @@ 1.14.0 - 3.3.2 \ No newline at end of file diff --git a/spring-aop/pom.xml b/spring-aop/pom.xml index ae5ab5fce1..2b84e2a432 100644 --- a/spring-aop/pom.xml +++ b/spring-aop/pom.xml @@ -72,7 +72,6 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} false @@ -82,7 +81,6 @@ 1.14.0 - 3.3.2 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-actuator/README.md b/spring-boot-modules/spring-boot-actuator/README.md index ea43377ed2..3af4634e44 100644 --- a/spring-boot-modules/spring-boot-actuator/README.md +++ b/spring-boot-modules/spring-boot-actuator/README.md @@ -12,4 +12,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Health Indicators in Spring Boot](https://www.baeldung.com/spring-boot-health-indicators) - [How to Enable All Endpoints in Spring Boot Actuator](https://www.baeldung.com/spring-boot-actuator-enable-endpoints) - [Spring Boot Startup Actuator Endpoint](https://www.baeldung.com/spring-boot-actuator-startup) -- [Metrics for your Spring REST API](https://www.baeldung.com/spring-rest-api-metrics) +- [Metrics for Your Spring REST API](https://www.baeldung.com/spring-rest-api-metrics) diff --git a/spring-boot-modules/spring-boot-gradle-2/README.md b/spring-boot-modules/spring-boot-gradle-2/README.md new file mode 100644 index 0000000000..ba6f30c000 --- /dev/null +++ b/spring-boot-modules/spring-boot-gradle-2/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Configuring Gradle Tasks in Spring Boot 3](https://www.baeldung.com/spring-boot-3-gradle-configure-tasks) diff --git a/spring-boot-modules/spring-boot-libraries-2/pom.xml b/spring-boot-modules/spring-boot-libraries-2/pom.xml index 6d9401f4bc..3cc228d838 100644 --- a/spring-boot-modules/spring-boot-libraries-2/pom.xml +++ b/spring-boot-modules/spring-boot-libraries-2/pom.xml @@ -62,9 +62,9 @@ ${jackson-databind.version} - io.springfox - springfox-swagger2 - ${springfox.version} + org.springdoc + springdoc-openapi-ui + ${springdoc.version} org.springframework.boot @@ -165,10 +165,10 @@ 3.1.1 4.0.3 - 5.1.0 + 5.3.0 2.4.5 0.2.1 - 2.9.2 + 1.7.0 com.baeldung.openapi.OpenApiApplication diff --git a/spring-boot-modules/spring-boot-mvc-4/pom.xml b/spring-boot-modules/spring-boot-mvc-4/pom.xml index b1c079b715..800ca8e31e 100644 --- a/spring-boot-modules/spring-boot-mvc-4/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-4/pom.xml @@ -32,11 +32,11 @@ spring-boot-devtools true - - io.springfox - springfox-boot-starter - ${spring.fox.version} - + + org.springdoc + springdoc-openapi-ui + ${springdoc.version} + com.fasterxml.jackson.core jackson-databind @@ -70,7 +70,7 @@ - 3.0.0 + 1.7.0 com.baeldung.springboot.swagger.ArticleApplication diff --git a/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/ArticleApplication.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/ArticleApplication.java index 8be380baa0..2b8388f914 100644 --- a/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/ArticleApplication.java +++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/ArticleApplication.java @@ -5,14 +5,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; @SpringBootApplication -@EnableSwagger2 @EnableWebMvc public class ArticleApplication { @@ -21,12 +17,10 @@ public class ArticleApplication { } @Bean - public Docket api() { - return new Docket(DocumentationType.SWAGGER_2) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build(); + public OpenAPI openAPI() { + return new OpenAPI().info(new Info().title("SpringDoc example") + .description("SpringDoc application") + .version("v0.0.1")); } } diff --git a/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/controller/ArticlesController.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/controller/ArticlesController.java index c4336a7cfe..96812e367a 100644 --- a/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/controller/ArticlesController.java +++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/controller/ArticlesController.java @@ -21,7 +21,7 @@ public class ArticlesController { } @PostMapping("") - public void addArticle(@ModelAttribute Article article) { + public void addArticle(@RequestBody Article article) { articleService.addArticle(article); } diff --git a/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/model/Article.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/model/Article.java index f6318c04b3..8a54e54427 100644 --- a/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/model/Article.java +++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/springboot/swagger/model/Article.java @@ -1,21 +1,16 @@ package com.baeldung.springboot.swagger.model; import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonView; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.annotations.ApiParam; - +import io.swagger.v3.oas.annotations.Hidden; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.Schema.AccessMode; public class Article { - //@JsonIgnore - //@JsonProperty(access = JsonProperty.Access.READ_ONLY) - //@ApiModelProperty(hidden = true) - //@ApiParam(hidden = true) - //@ApiModelProperty(readOnly = true) - @ApiParam(hidden = true) + // @JsonIgnore + // @JsonProperty(access = JsonProperty.Access.READ_ONLY) + // @Schema(accessMode = AccessMode.READ_ONLY) + @Hidden private int id; private String title; private int numOfWords; diff --git a/spring-boot-modules/spring-boot-mvc-legacy/README.md b/spring-boot-modules/spring-boot-mvc-legacy/README.md new file mode 100644 index 0000000000..a4e075b7fa --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-legacy/README.md @@ -0,0 +1,8 @@ +## Spring Boot MVC Legacy + +This module contains legacy Spring MVC articles in Spring Boot projects. + +### Relevant Articles: + +- [Setting Up Swagger 2 with a Spring REST API Using Springfox](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) + diff --git a/spring-boot-modules/spring-boot-mvc-legacy/pom.xml b/spring-boot-modules/spring-boot-mvc-legacy/pom.xml new file mode 100644 index 0000000000..b5422b12bd --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-legacy/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + spring-boot-mvc-legacy + spring-boot-mvc-legacy + jar + Module For Spring Boot MVC Legacy + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-data-rest + + + org.hsqldb + hsqldb + runtime + + + javax.validation + validation-api + + + + io.springfox + springfox-boot-starter + ${spring.fox.version} + + + + + 3.0.0 + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/Application.java b/spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/Application.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/Application.java rename to spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/Application.java diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java b/spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java similarity index 92% rename from spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java rename to spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java index 5998ffeb2a..69316d6b28 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java +++ b/spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java @@ -1,16 +1,17 @@ package com.baeldung.swagger2boot.configuration; -import com.baeldung.swagger2boot.plugin.EmailAnnotationPlugin; +import java.util.Collections; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; + +import com.baeldung.swagger2boot.plugin.EmailAnnotationPlugin; + import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger.web.DocExpansion; import springfox.documentation.swagger.web.ModelRendering; @@ -19,8 +20,6 @@ import springfox.documentation.swagger.web.TagsSorter; import springfox.documentation.swagger.web.UiConfiguration; import springfox.documentation.swagger.web.UiConfigurationBuilder; -import java.util.Collections; - @Configuration public class SpringFoxConfig { diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java b/spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java rename to spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/model/User.java b/spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/model/User.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/model/User.java rename to spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/model/User.java diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/plugin/EmailAnnotationPlugin.java b/spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/plugin/EmailAnnotationPlugin.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/plugin/EmailAnnotationPlugin.java rename to spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/plugin/EmailAnnotationPlugin.java diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/repository/UserRepository.java b/spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/repository/UserRepository.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/repository/UserRepository.java rename to spring-boot-modules/spring-boot-mvc-legacy/src/main/java/com/baeldung/swagger2boot/repository/UserRepository.java diff --git a/spring-boot-modules/spring-boot-mvc-legacy/src/main/resources/application.properties b/spring-boot-modules/spring-boot-mvc-legacy/src/main/resources/application.properties new file mode 100644 index 0000000000..d52a63b19c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-legacy/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER diff --git a/spring-boot-modules/spring-boot-mvc/README.md b/spring-boot-modules/spring-boot-mvc/README.md index 852990bd73..f45feb6169 100644 --- a/spring-boot-modules/spring-boot-mvc/README.md +++ b/spring-boot-modules/spring-boot-mvc/README.md @@ -7,7 +7,6 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Custom Validation MessageSource in Spring Boot](https://www.baeldung.com/spring-custom-validation-message-source) - [Display RSS Feed with Spring MVC](https://www.baeldung.com/spring-mvc-rss-feed) - [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) -- [Setting Up Swagger 2 with a Spring REST API Using Springfox](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Using Spring ResponseEntity to Manipulate the HTTP Response](https://www.baeldung.com/spring-response-entity) - [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) - [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) diff --git a/spring-boot-modules/spring-boot-mvc/pom.xml b/spring-boot-modules/spring-boot-mvc/pom.xml index d5ec7742c9..369bcf799b 100644 --- a/spring-boot-modules/spring-boot-mvc/pom.xml +++ b/spring-boot-modules/spring-boot-mvc/pom.xml @@ -80,12 +80,6 @@ org.springframework.boot spring-boot-starter-validation - - - io.springfox - springfox-boot-starter - ${spring.fox.version} - org.aspectj @@ -113,7 +107,6 @@ - 3.0.0 1.10.0 2.3.7 diff --git a/spring-boot-modules/spring-boot-properties-2/pom.xml b/spring-boot-modules/spring-boot-properties-2/pom.xml index 4b1daca34d..2c74f7f186 100644 --- a/spring-boot-modules/spring-boot-properties-2/pom.xml +++ b/spring-boot-modules/spring-boot-properties-2/pom.xml @@ -20,10 +20,12 @@ org.springframework.boot spring-boot-starter + ${spring-boot.version} org.springframework.boot spring-boot-starter-web + ${spring-boot.version} commons-lang @@ -34,6 +36,7 @@ com.baeldung.properties.yaml.YamlApplication + 3.1.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/PriorityRecord.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/PriorityRecord.java new file mode 100644 index 0000000000..2d88da2f37 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/PriorityRecord.java @@ -0,0 +1,10 @@ +package com.baeldung.properties.value; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +@Component +@PropertySource("classpath:values.properties") +public record PriorityRecord(@Value("${priority:normal}") String priority) { +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/PriorityProviderIntegrationTest.java b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/PriorityProviderIntegrationTest.java index d7d1e7d78b..5d1ef825fc 100644 --- a/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/PriorityProviderIntegrationTest.java +++ b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/PriorityProviderIntegrationTest.java @@ -1,13 +1,13 @@ package com.baeldung.properties.value; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import static org.assertj.core.api.Assertions.assertThat; - @RunWith(SpringRunner.class) @SpringBootTest(classes = PriorityProvider.class) public class PriorityProviderIntegrationTest { diff --git a/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/PriorityRecordIntegrationTest.java b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/PriorityRecordIntegrationTest.java new file mode 100644 index 0000000000..571e927bd5 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/PriorityRecordIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung.properties.value; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PriorityRecord.class) +public class PriorityRecordIntegrationTest { + + @Autowired + private PriorityRecord priorityRecord; + + @Test + public void givenPropertyFile_WhenConstructorInjectionUsedInRecord_ThenValueInjected() { + assertThat(priorityRecord.priority()).isEqualTo("high"); + } + +} diff --git a/spring-boot-modules/spring-boot-properties-3/README.md b/spring-boot-modules/spring-boot-properties-3/README.md index cb09a0ab81..476797965a 100644 --- a/spring-boot-modules/spring-boot-properties-3/README.md +++ b/spring-boot-modules/spring-boot-properties-3/README.md @@ -13,4 +13,5 @@ - [Using Environment Variables in Spring Boot’s application.properties](https://www.baeldung.com/spring-boot-properties-env-variables) - [Loading Multiple YAML Configuration Files in Spring Boot](https://www.baeldung.com/spring-boot-load-multiple-yaml-configuration-files) - [Using Environment Variables in Spring Boot’s Properties Files](https://www.baeldung.com/spring-boot-properties-env-variables) +- [Spring Boot Properties Prefix Must Be in Canonical Form](https://www.baeldung.com/spring-boot-properties-canonical-form) - More articles: [[<-- prev]](../spring-boot-properties-2) diff --git a/spring-boot-modules/spring-boot-swagger-jwt/src/main/java/com/baeldung/swaggerjwt/configuration/SwaggerConfiguration.java b/spring-boot-modules/spring-boot-swagger-jwt/src/main/java/com/baeldung/swaggerjwt/configuration/SwaggerConfiguration.java index 240a21cd21..e5e87de3ec 100644 --- a/spring-boot-modules/spring-boot-swagger-jwt/src/main/java/com/baeldung/swaggerjwt/configuration/SwaggerConfiguration.java +++ b/spring-boot-modules/spring-boot-swagger-jwt/src/main/java/com/baeldung/swaggerjwt/configuration/SwaggerConfiguration.java @@ -2,6 +2,7 @@ package com.baeldung.swaggerjwt.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; + import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; @@ -16,47 +17,40 @@ import java.util.List; @Configuration public class SwaggerConfiguration { - public static final String AUTHORIZATION_HEADER = "Authorization"; + public static final String AUTHORIZATION_HEADER = "Authorization"; - private ApiInfo apiInfo() { - return new ApiInfo("My REST API", - "Some custom description of API.", - "1.0", - "Terms of service", - new Contact("Sallo Szrajbman", "www.baeldung.com", "salloszraj@gmail.com"), - "License of API", - "API license URL", - Collections.emptyList()); - } + private ApiInfo apiInfo() { + return new ApiInfo("My REST API", "Some custom description of API.", "1.0", "Terms of service", new Contact("Sallo Szrajbman", "www.baeldung.com", "salloszraj@gmail.com"), "License of API", "API license URL", Collections.emptyList()); + } - @Bean - public Docket api() { - return new Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .securityContexts(Arrays.asList(securityContext())) - .securitySchemes(Arrays.asList(apiKey())) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build(); - } + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) + .securityContexts(Arrays.asList(securityContext())) + .securitySchemes(Arrays.asList(apiKey())) + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); + } - private ApiKey apiKey() { - return new ApiKey("JWT", AUTHORIZATION_HEADER, "header"); - } + private ApiKey apiKey() { + return new ApiKey("JWT", AUTHORIZATION_HEADER, "header"); + } - private SecurityContext securityContext() { - return SecurityContext.builder() - .securityReferences(defaultAuth()) - .build(); - } + private SecurityContext securityContext() { + return SecurityContext.builder() + .securityReferences(List.of(defaultAuth())) + .operationSelector(o -> o.requestMappingPattern() + .matches("/.*")) + .build(); + } - List defaultAuth() { - AuthorizationScope authorizationScope - = new AuthorizationScope("global", "accessEverything"); - AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; - authorizationScopes[0] = authorizationScope; - return Arrays.asList(new SecurityReference("JWT", authorizationScopes)); - } + private SecurityReference defaultAuth() { + return SecurityReference.builder() + .scopes(new AuthorizationScope[0]) + .reference("JWT") + .build(); + } } diff --git a/spring-boot-modules/spring-boot-testing-2/README.md b/spring-boot-modules/spring-boot-testing-2/README.md index bb504aeee0..e6bc4c4590 100644 --- a/spring-boot-modules/spring-boot-testing-2/README.md +++ b/spring-boot-modules/spring-boot-testing-2/README.md @@ -8,7 +8,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level) +- [Setting the Log Level in Spring Boot When Testing](https://www.baeldung.com/spring-boot-testing-log-level) - [Failed to Load ApplicationContext for JUnit Test of Spring Controller](https://www.baeldung.com/spring-junit-failed-to-load-applicationcontext) - [Spring Web Service Integration Tests with @WebServiceServerTest](https://www.baeldung.com/spring-webserviceservertest) - [Spring Boot – Testing Redis With Testcontainers](https://www.baeldung.com/spring-boot-redis-testcontainers) diff --git a/spring-core-3/README.md b/spring-core-3/README.md index ed88561e10..dcdbbd3a67 100644 --- a/spring-core-3/README.md +++ b/spring-core-3/README.md @@ -6,7 +6,7 @@ This module contains articles about core Spring functionality - [Understanding getBean() in Spring](https://www.baeldung.com/spring-getbean) - [Guide to the Spring BeanFactory](https://www.baeldung.com/spring-beanfactory) -- [How to use the Spring FactoryBean?](https://www.baeldung.com/spring-factorybean) +- [How to Use the Spring FactoryBean?](https://www.baeldung.com/spring-factorybean) - [Design Patterns in the Spring Framework](https://www.baeldung.com/spring-framework-design-patterns) - [Difference Between BeanFactory and ApplicationContext](https://www.baeldung.com/spring-beanfactory-vs-applicationcontext) - [Custom Scope in Spring](http://www.baeldung.com/spring-custom-scope) diff --git a/spring-core/README.md b/spring-core/README.md index ffcbf4757b..8e85ae44f3 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -8,7 +8,7 @@ This module contains articles about core Spring functionality. - [BeanNameAware and BeanFactoryAware Interfaces in Spring](https://www.baeldung.com/spring-bean-name-factory-aware) - [Access a File from the Classpath in a Spring Application](https://www.baeldung.com/spring-classpath-file-access) - [Spring Application Context Events](https://www.baeldung.com/spring-context-events) -- [What is a Spring Bean?](https://www.baeldung.com/spring-bean) +- [What Is a Spring Bean?](https://www.baeldung.com/spring-bean) - [Spring PostConstruct and PreDestroy Annotations](https://www.baeldung.com/spring-postconstruct-predestroy) - [Intro to the Spring ClassPathXmlApplicationContext](http://www.baeldung.com/spring-classpathxmlapplicationcontext) - More articles: [[next -->]](../spring-core-2) diff --git a/spring-di-3/README.md b/spring-di-3/README.md index ffb81fbe7d..64cf11eb6b 100644 --- a/spring-di-3/README.md +++ b/spring-di-3/README.md @@ -9,6 +9,6 @@ This module contains articles about dependency injection with Spring - [Finding All Beans with a Custom Annotation](https://www.baeldung.com/spring-injecting-all-annotated-beans) - [Guide to Spring @Autowired](http://www.baeldung.com/spring-autowire) - [@Order in Spring](http://www.baeldung.com/spring-order) -- [How to dynamically Autowire a Bean in Spring](https://www.baeldung.com/spring-dynamic-autowire) +- [How to Dynamically Autowire a Bean in Spring](https://www.baeldung.com/spring-dynamic-autowire) - [Spring @Import Annotation](https://www.baeldung.com/spring-import-annotation) - More articles: [[<-- prev]](../spring-di-2)[[more -->]](../spring-di-4) diff --git a/spring-di-4/README.md b/spring-di-4/README.md index d4b0d94385..8e73aff437 100644 --- a/spring-di-4/README.md +++ b/spring-di-4/README.md @@ -6,4 +6,5 @@ This module contains articles about dependency injection with Spring - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) - [Spring @Component Annotation](https://www.baeldung.com/spring-component-annotation) +- [Why Is Field Injection Not Recommended?](https://www.baeldung.com/java-spring-field-injection-cons) - More articles: [[<-- prev]](../spring-di-3) diff --git a/spring-di-4/src/main/java/com/baeldung/fieldinjection/EmailService.java b/spring-di-4/src/main/java/com/baeldung/fieldinjection/EmailService.java new file mode 100644 index 0000000000..2c28b5baf4 --- /dev/null +++ b/spring-di-4/src/main/java/com/baeldung/fieldinjection/EmailService.java @@ -0,0 +1,21 @@ +package com.baeldung.fieldinjection; + +import org.springframework.stereotype.Service; + +@Service +public class EmailService { + + public static final String INVALID_EMAIL = "Invalid email"; + private final EmailValidator emailValidator; + + public EmailService(final EmailValidator emailValidator) { + this.emailValidator = emailValidator; + } + + public void process(String email) { + if (!emailValidator.isValid(email)) { + throw new IllegalArgumentException(INVALID_EMAIL); + } + // ... + } +} \ No newline at end of file diff --git a/spring-di-4/src/main/java/com/baeldung/fieldinjection/EmailValidator.java b/spring-di-4/src/main/java/com/baeldung/fieldinjection/EmailValidator.java new file mode 100644 index 0000000000..884a139781 --- /dev/null +++ b/spring-di-4/src/main/java/com/baeldung/fieldinjection/EmailValidator.java @@ -0,0 +1,17 @@ +package com.baeldung.fieldinjection; + +import org.springframework.stereotype.Component; + +import java.util.regex.Pattern; + +@Component +public class EmailValidator { + + private static final String REGEX_PATTERN = "^(.+)@(\\S+)$"; + + public boolean isValid(final String email) { + return Pattern.compile(REGEX_PATTERN) + .matcher(email) + .matches(); + } +} diff --git a/spring-di-4/src/test/java/com/baeldung/fieldinjection/EmailServiceUnitTest.java b/spring-di-4/src/test/java/com/baeldung/fieldinjection/EmailServiceUnitTest.java new file mode 100644 index 0000000000..b2bcbad811 --- /dev/null +++ b/spring-di-4/src/test/java/com/baeldung/fieldinjection/EmailServiceUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.fieldinjection; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class EmailServiceUnitTest { + + private EmailValidator emailValidator; + + private EmailService emailService; + + @BeforeEach + public void setup() { + this.emailValidator = Mockito.mock(EmailValidator.class); + this.emailService = new EmailService(emailValidator); + } + + @Test + void givenInvalidEmail_whenProcess_thenThrowException() { + String email = "testbaeldung.com"; + + when(emailValidator.isValid(email)).thenReturn(false); + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> emailService.process(email)); + + assertNotNull(exception); + assertEquals(EmailService.INVALID_EMAIL, exception.getMessage()); + } +} diff --git a/spring-integration/README.md b/spring-integration/README.md index ad46082a04..710af2a8c7 100644 --- a/spring-integration/README.md +++ b/spring-integration/README.md @@ -4,7 +4,7 @@ This module contains articles about Spring Integration ### Relevant Articles: - [Introduction to Spring Integration](https://www.baeldung.com/spring-integration) -- [Security In Spring Integration](https://www.baeldung.com/spring-integration-security) +- [Security in Spring Integration](https://www.baeldung.com/spring-integration-security) - [Spring Integration Java DSL](https://www.baeldung.com/spring-integration-java-dsl) - [Using Subflows in Spring Integration](https://www.baeldung.com/spring-integration-subflows) - [Transaction Support in Spring Integration](https://www.baeldung.com/spring-integration-transaction) diff --git a/spring-native/README.md b/spring-native/README.md index 72308cb9d5..0f193252d0 100644 --- a/spring-native/README.md +++ b/spring-native/README.md @@ -1,4 +1,3 @@ ## Relevant Articles: - [Introduction to Spring Native](https://www.baeldung.com/spring-native-intro) -- [Ahead of Time Optimizations in Spring 6](https://www.baeldung.com/aot-optimization-spring) \ No newline at end of file diff --git a/spring-reactive-modules/spring-5-reactive/README.md b/spring-reactive-modules/spring-5-reactive/README.md index aa8d2800e2..f3148fe696 100644 --- a/spring-reactive-modules/spring-5-reactive/README.md +++ b/spring-reactive-modules/spring-5-reactive/README.md @@ -9,7 +9,6 @@ The "REST With Spring" Classes: https://bit.ly/restwithspring - [Exploring the Spring 5 WebFlux URL Matching](https://www.baeldung.com/spring-5-mvc-url-matching) - [Reactive WebSockets with Spring 5](https://www.baeldung.com/spring-5-reactive-websockets) -- [Spring WebFlux Filters](https://www.baeldung.com/spring-webflux-filters) - [How to Set a Header on a Response with Spring 5](https://www.baeldung.com/spring-response-header) - [A Guide to Spring Session Reactive Support: WebSession](https://www.baeldung.com/spring-session-reactive) - More articles: [[next -->]](../spring-5-reactive-2) diff --git a/spring-security-modules/spring-security-saml/README.md b/spring-security-modules/spring-security-saml/README.md index 213b56fb8c..7362f1016b 100644 --- a/spring-security-modules/spring-security-saml/README.md +++ b/spring-security-modules/spring-security-saml/README.md @@ -1,4 +1,3 @@ ### Relevant Articles: - [A Guide to SAML with Spring Security](https://www.baeldung.com/spring-security-saml-legacy) -- [SAML with Spring Boot and Spring Security](https://www.baeldung.com/spring-security-saml) diff --git a/spring-security-modules/spring-security-saml2/README.md b/spring-security-modules/spring-security-saml2/README.md new file mode 100644 index 0000000000..6078ac2215 --- /dev/null +++ b/spring-security-modules/spring-security-saml2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [SAML with Spring Boot and Spring Security](https://www.baeldung.com/spring-security-saml) diff --git a/spring-security-modules/spring-security-web-boot-4/README.md b/spring-security-modules/spring-security-web-boot-4/README.md index af8ed4e76a..8a7dbf3029 100644 --- a/spring-security-modules/spring-security-web-boot-4/README.md +++ b/spring-security-modules/spring-security-web-boot-4/README.md @@ -9,5 +9,5 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [Spring Security: Upgrading the Deprecated WebSecurityConfigurerAdapter](https://www.baeldung.com/spring-deprecated-websecurityconfigureradapter) - [Spring @EnableMethodSecurity Annotation](https://www.baeldung.com/spring-enablemethodsecurity) - +- [Securing Spring Boot API With API Key and Secret](https://www.baeldung.com/spring-boot-api-key-secret) More articles: [[<-- prev]](/spring-security-modules/spring-security-web-boot-3) diff --git a/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/ApiControllerIntegrationTest.java b/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/ApiControllerIntegrationTest.java index f04dcc30d4..3645ff253e 100644 --- a/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/ApiControllerIntegrationTest.java +++ b/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/ApiControllerIntegrationTest.java @@ -5,6 +5,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.*; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -14,20 +15,23 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest(classes = SpringSecurityApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ExtendWith(SpringExtension.class) class ApiControllerIntegrationTest { private final TestRestTemplate restTemplate = new TestRestTemplate(); - private static final String API_ENDPOINT = "http://localhost:8080/app/api/hello"; + private static final String API_ENDPOINT = "http://localhost:%s/app/api/hello"; + + @LocalServerPort + private int serverPort; @Test void givenAuthHeaderSecretIsValid_whenApiControllerCalled_thenReturnOk() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.add("x-auth-secret-key", "test-secret"); - ResponseEntity response = restTemplate.exchange(new URI(API_ENDPOINT), HttpMethod.GET, + ResponseEntity response = restTemplate.exchange(new URI(String.format(API_ENDPOINT, serverPort)), HttpMethod.GET, new HttpEntity<>(headers), String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); @@ -39,7 +43,7 @@ class ApiControllerIntegrationTest { HttpHeaders headers = new HttpHeaders(); headers.add("x-auth-secret-key", "invalid"); - ResponseEntity response = restTemplate.exchange(new URI(API_ENDPOINT), HttpMethod.GET, + ResponseEntity response = restTemplate.exchange(new URI(String.format(API_ENDPOINT, serverPort)), HttpMethod.GET, new HttpEntity<>(headers), String.class); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); @@ -50,7 +54,7 @@ class ApiControllerIntegrationTest { HttpHeaders headers = new HttpHeaders(); headers.add("x-auth-secret", "test-secret"); - ResponseEntity response = restTemplate.exchange(new URI(API_ENDPOINT), HttpMethod.GET, + ResponseEntity response = restTemplate.exchange(new URI(String.format(API_ENDPOINT, serverPort)), HttpMethod.GET, new HttpEntity<>(headers), String.class); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); @@ -60,7 +64,7 @@ class ApiControllerIntegrationTest { void givenAuthHeaderIsMissing_whenApiControllerCalled_thenReturnUnAuthorised() throws Exception { HttpHeaders headers = new HttpHeaders(); - ResponseEntity response = restTemplate.exchange(new URI(API_ENDPOINT), HttpMethod.GET, + ResponseEntity response = restTemplate.exchange(new URI(String.format(API_ENDPOINT, serverPort)), HttpMethod.GET, new HttpEntity<>(headers), String.class); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); diff --git a/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/HealthCheckControllerIntegrationTest.java b/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/HealthCheckControllerIntegrationTest.java index ea6fdcf292..2022ef0339 100644 --- a/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/HealthCheckControllerIntegrationTest.java +++ b/spring-security-modules/spring-security-web-boot-5/src/test/java/com/baeldung/customauth/controller/HealthCheckControllerIntegrationTest.java @@ -5,6 +5,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.*; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -13,19 +14,22 @@ import java.net.URI; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest(classes = SpringSecurityApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ExtendWith(SpringExtension.class) class HealthCheckControllerIntegrationTest { private final TestRestTemplate restTemplate = new TestRestTemplate(); - private static final String HEALTH_CHECK_ENDPOINT = "http://localhost:8080/app/health"; + private static final String HEALTH_CHECK_ENDPOINT = "http://localhost:%s/app/health"; + + @LocalServerPort + private int serverPort; @Test void givenApplicationIsRunning_whenHealthCheckControllerCalled_thenReturnOk() throws Exception { HttpHeaders headers = new HttpHeaders(); - ResponseEntity response = restTemplate.exchange(new URI(HEALTH_CHECK_ENDPOINT), HttpMethod.GET, + ResponseEntity response = restTemplate.exchange(new URI(String.format(HEALTH_CHECK_ENDPOINT, serverPort)), HttpMethod.GET, new HttpEntity<>(headers), String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); diff --git a/spring-security-modules/spring-security-web-mvc-custom/README.md b/spring-security-modules/spring-security-web-mvc-custom/README.md index d8bd4cb3e0..6a38460b28 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/README.md +++ b/spring-security-modules/spring-security-web-mvc-custom/README.md @@ -9,7 +9,7 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Remember Me](https://www.baeldung.com/spring-security-remember-me) -- [Redirect to Different Pages after Login with Spring Security](https://www.baeldung.com/spring-redirect-after-login) +- [Redirect to Different Pages After Login With Spring Security](https://www.baeldung.com/spring-redirect-after-login) - [Changing Spring Model Parameters with Handler Interceptor](https://www.baeldung.com/spring-model-parameters-with-handler-interceptor) - [Introduction to Spring MVC HandlerInterceptor](https://www.baeldung.com/spring-mvc-handlerinterceptor) - [Using a Custom Spring MVC’s Handler Interceptor to Manage Sessions](https://www.baeldung.com/spring-mvc-custom-handler-interceptor) diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/README.md b/spring-security-modules/spring-security-web-rest-basic-auth/README.md index 097e89b138..9070179676 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/README.md +++ b/spring-security-modules/spring-security-web-rest-basic-auth/README.md @@ -11,7 +11,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Basic Authentication with the RestTemplate](https://www.baeldung.com/how-to-use-resttemplate-with-basic-authentication-in-spring) - [A Custom Filter in the Spring Security Filter Chain](https://www.baeldung.com/spring-security-custom-filter) - [Spring Security Basic Authentication](https://www.baeldung.com/spring-security-basic-authentication) -- [New Password Storage In Spring Security 5](https://www.baeldung.com/spring-security-5-password-storage) +- [New Password Storage in Spring Security 5](https://www.baeldung.com/spring-security-5-password-storage) - [Default Password Encoder in Spring Security 5](https://www.baeldung.com/spring-security-5-default-password-encoder) - [Basic Authentication With Postman](https://www.baeldung.com/java-postman-authentication) diff --git a/spring-static-resources/pom.xml b/spring-static-resources/pom.xml index ca7f944d23..f682eafdbe 100644 --- a/spring-static-resources/pom.xml +++ b/spring-static-resources/pom.xml @@ -180,7 +180,6 @@ org.apache.maven.plugins maven-war-plugin - 3.2.2 diff --git a/spring-web-modules/spring-rest-http-2/pom.xml b/spring-web-modules/spring-rest-http-2/pom.xml index 10d904e302..d83a83c690 100644 --- a/spring-web-modules/spring-rest-http-2/pom.xml +++ b/spring-web-modules/spring-rest-http-2/pom.xml @@ -24,16 +24,6 @@ org.springframework.boot spring-boot-starter-webflux - - io.springfox - springfox-swagger2 - ${swagger2.version} - - - io.springfox - springfox-swagger-ui - ${swagger2.version} - com.h2database h2 @@ -47,11 +37,23 @@ resilience4j-timelimiter ${resilience4j.version} + + org.springdoc + springdoc-openapi-ui + ${springdoc.version} + + + com.google.guava + guava + ${guava.version} + 2.9.2 1.6.1 + 1.7.0 + 31.0.1-jre \ No newline at end of file diff --git a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/swagger/SpringDocConfig.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/swagger/SpringDocConfig.java new file mode 100644 index 0000000000..2df6cd118c --- /dev/null +++ b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/swagger/SpringDocConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.endpoint.swagger; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; + +@Configuration +public class SpringDocConfig { + + @Bean + public OpenAPI openAPI() { + return new OpenAPI().info(new Info().title("SpringDoc example") + .description("SpringDoc application") + .version("v0.0.1")); + } +} diff --git a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/swagger/SpringFoxConfig.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/swagger/SpringFoxConfig.java deleted file mode 100644 index bd258122cd..0000000000 --- a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/endpoint/swagger/SpringFoxConfig.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.endpoint.swagger; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; - -@Configuration -public class SpringFoxConfig { - - @Bean - public Docket api() { - return new Docket(DocumentationType.SWAGGER_2) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build(); - } -} diff --git a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/SwaggerUIDisableApplication.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/SwaggerUIDisableApplication.java new file mode 100644 index 0000000000..5aa4f219f0 --- /dev/null +++ b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/SwaggerUIDisableApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.swaggerui.disable; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SwaggerUIDisableApplication { + + public static void main(String[] args) { + SpringApplication.run(SwaggerUIDisableApplication.class, args); + } +} diff --git a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java index e3c0237b06..d9981b7097 100644 --- a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java +++ b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java @@ -6,33 +6,21 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; @Profile("!prod && swagger") //@Profile("!prod") // @Profile("swagger") // @ConditionalOnExpression(value = "${useSwagger:false}") @Configuration -@EnableSwagger2 -public class SwaggerConfig implements WebMvcConfigurer { +public class SwaggerConfig { @Bean - public Docket api() { - return new Docket(DocumentationType.SWAGGER_2).select() - .apis(RequestHandlerSelectors.basePackage("com.baeldung")) - .paths(PathSelectors.regex("/.*")) - .build(); - } - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("swagger-ui.html") - .addResourceLocations("classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**") - .addResourceLocations("classpath:/META-INF/resources/webjars/"); + public OpenAPI openAPI() { + return new OpenAPI().info(new Info().title("SpringDoc Disable SwaggerUI example") + .description("SpringDoc Disable SwaggerUI application") + .version("v0.0.1")); } } diff --git a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java index 8f8115197e..403c7f6aa5 100644 --- a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java +++ b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java @@ -1,6 +1,6 @@ package com.baeldung.swaggerui.disable.controllers; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -14,7 +14,7 @@ public class VersionController { this.environment = environment; } - @ApiOperation(value = "Get the currently deployed API version and active Spring profiles") + @Operation(summary = "Get the currently deployed API version and active Spring profiles") @GetMapping("/api/version") public Version getVersion() { return new Version("1.0", environment.getActiveProfiles()); diff --git a/spring-web-modules/spring-rest-testing/README.md b/spring-web-modules/spring-rest-testing/README.md index 806e67b7ec..e043667160 100644 --- a/spring-web-modules/spring-rest-testing/README.md +++ b/spring-web-modules/spring-rest-testing/README.md @@ -10,7 +10,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: -- [Integration Testing with the Maven Cargo plugin](https://www.baeldung.com/integration-testing-with-the-maven-cargo-plugin) +- [Integration Testing With the Maven Cargo Plugin](https://www.baeldung.com/integration-testing-with-the-maven-cargo-plugin) - [Testing Exceptions with Spring MockMvc](https://www.baeldung.com/spring-mvc-test-exceptions) ### Build the Project diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/attribute/CheckedAttributeController.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/attribute/CheckedAttributeController.java new file mode 100644 index 0000000000..165e98ac3a --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/attribute/CheckedAttributeController.java @@ -0,0 +1,29 @@ +package com.baeldung.thymeleaf.attribute; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class CheckedAttributeController { + + @GetMapping("/checked") + public String displayCheckboxForm(Model model) { + Engine engine = new Engine(true); + model.addAttribute("engine", engine); + model.addAttribute("flag", true); + return "attribute/index"; + } + + private static class Engine { + private Boolean active; + + public Engine(Boolean active) { + this.active = active; + } + + public Boolean getActive() { + return active; + } + } +} diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/attribute/index.html b/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/attribute/index.html new file mode 100644 index 0000000000..a7c5b90296 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/attribute/index.html @@ -0,0 +1,27 @@ + + + + + Spring Boot Thymeleaf Application - Checkbox Checked Conditionally + + +
+ +
+
+
+ + + +
+
+
+
+ + \ No newline at end of file diff --git a/testing-modules/gatling-java/README.md b/testing-modules/gatling-java/README.md index 4bc07b1910..02c271cd07 100644 --- a/testing-modules/gatling-java/README.md +++ b/testing-modules/gatling-java/README.md @@ -1,6 +1,6 @@ ### Relevant Articles: - [Load Testing Rest Endpoint Using Gatling](https://www.baeldung.com/gatling-load-testing-rest-endpoint) - +- [How to Display a Full HTTP Response Body With Gatling](https://www.baeldung.com/java-gatling-show-response-body) ### Running a simualtion diff --git a/testing-modules/gatling-java/pom.xml b/testing-modules/gatling-java/pom.xml index 54e18b3ac1..abe033f298 100644 --- a/testing-modules/gatling-java/pom.xml +++ b/testing-modules/gatling-java/pom.xml @@ -60,7 +60,12 @@ gatling-maven-plugin ${gatling-maven-plugin.version} - org.baeldung.EmployeeRegistrationSimulation + + org.baeldung.EmployeeRegistrationSimulation + org.baeldung.gatling.http.FetchSinglePostSimulation + org.baeldung.gatling.http.FetchSinglePostSimulationLog + + true
@@ -70,8 +75,8 @@ 1.8 1.8 UTF-8 - 3.9.0 - 4.2.9 + 3.9.5 + 4.3.0 1.0.2 2.7.5 diff --git a/testing-modules/gatling-java/src/test/java/org/baeldung/gatling/http/FetchSinglePostSimulation.java b/testing-modules/gatling-java/src/test/java/org/baeldung/gatling/http/FetchSinglePostSimulation.java new file mode 100644 index 0000000000..16cf25faef --- /dev/null +++ b/testing-modules/gatling-java/src/test/java/org/baeldung/gatling/http/FetchSinglePostSimulation.java @@ -0,0 +1,23 @@ +package org.baeldung.gatling.http; + +import io.gatling.javaapi.core.*; +import io.gatling.javaapi.http.*; +import static io.gatling.javaapi.http.HttpDsl.*; +import static io.gatling.javaapi.core.CoreDsl.*; + +public class FetchSinglePostSimulation extends Simulation { + + public FetchSinglePostSimulation() { + HttpProtocolBuilder httpProtocolBuilder = http.baseUrl("https://jsonplaceholder.typicode.com"); + + ScenarioBuilder scn = scenario("Display Full HTTP Response Body").exec(http("GET Request").get("/posts/1") + .check(status().is(200)) + .check(bodyString().saveAs("responseBody"))) + .exec(session -> { + System.out.println("Response Body:"); + System.out.println(session.getString("responseBody")); + return session; + }); + setUp(scn.injectOpen(atOnceUsers(1))).protocols(httpProtocolBuilder); + } +} diff --git a/testing-modules/gatling-java/src/test/java/org/baeldung/gatling/http/FetchSinglePostSimulationLog.java b/testing-modules/gatling-java/src/test/java/org/baeldung/gatling/http/FetchSinglePostSimulationLog.java new file mode 100644 index 0000000000..9ad4d6edf6 --- /dev/null +++ b/testing-modules/gatling-java/src/test/java/org/baeldung/gatling/http/FetchSinglePostSimulationLog.java @@ -0,0 +1,42 @@ +package org.baeldung.gatling.http; + +import io.gatling.javaapi.core.ScenarioBuilder; +import io.gatling.javaapi.core.Simulation; +import io.gatling.javaapi.http.HttpProtocolBuilder; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; + +import static io.gatling.javaapi.core.CoreDsl.*; +import static io.gatling.javaapi.http.HttpDsl.http; +import static io.gatling.javaapi.http.HttpDsl.status; + +public class FetchSinglePostSimulationLog extends Simulation { + + public FetchSinglePostSimulationLog() { + HttpProtocolBuilder httpProtocolBuilder = http.baseUrl("https://jsonplaceholder.typicode.com"); + + ScenarioBuilder scn = scenario("Display Full HTTP Response Body").exec(http("GET Request").get("/posts/1") + .check(status().is(200)) + .check(bodyString().saveAs("responseBody"))) + .exec(session -> { + + String responseBody = session.getString("responseBody"); + try { + writeFile("response_body.log", responseBody); + } catch (IOException e) { + System.err.println("error writing file"); + } + return session; + }); + setUp(scn.injectOpen(atOnceUsers(1))).protocols(httpProtocolBuilder); + } + + private void writeFile(String fileName, String content) throws IOException { + try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) { + writer.write(content); + writer.newLine(); + } + } +} diff --git a/testing-modules/junit-5-advanced/pom.xml b/testing-modules/junit-5-advanced/pom.xml index 998f6561ea..3ae62eac2e 100644 --- a/testing-modules/junit-5-advanced/pom.xml +++ b/testing-modules/junit-5-advanced/pom.xml @@ -53,6 +53,7 @@ org.apache.maven.plugins maven-surefire-plugin + ${maven-surefire-plugin.version} -javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar @@ -70,6 +71,7 @@ 1.49 3.24.2 1.9.2 + 3.0.0 \ No newline at end of file diff --git a/testing-modules/junit-5-basics/README.md b/testing-modules/junit-5-basics/README.md index 31eb75a792..03b0d4269a 100644 --- a/testing-modules/junit-5-basics/README.md +++ b/testing-modules/junit-5-basics/README.md @@ -7,5 +7,5 @@ - [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) - [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) - [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) -- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) +- [Assert an Exception Is Thrown in JUnit 4 and 5](https://www.baeldung.com/junit-assert-exception) - [The Difference Between Failure and Error in JUnit](https://www.baeldung.com/junit-failure-vs-error) diff --git a/testing-modules/junit-5-basics/pom.xml b/testing-modules/junit-5-basics/pom.xml index a758d79069..9c3cf7a7e4 100644 --- a/testing-modules/junit-5-basics/pom.xml +++ b/testing-modules/junit-5-basics/pom.xml @@ -61,6 +61,17 @@ true + + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.lang=ALL-UNNAMED + + + + diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml index 047eddcbcb..8afaa085b1 100644 --- a/testing-modules/junit-5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -121,8 +121,13 @@ org.apache.maven.plugins - maven-surefire-report-plugin - ${surefire.report.plugin} + maven-surefire-plugin + + + --add-opens java.base/java.lang=ALL-UNNAMED + --add-opens java.base/java.time=ALL-UNNAMED + + @@ -131,7 +136,6 @@ 2.17.1 2.0.9 5.0.1.RELEASE - 3.0.0-M3 3.3.0 diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5vstestng/SelectPackagesSuiteUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5vstestng/SelectPackagesSuiteUnitTest.java index ef8756a2bb..088fc00853 100644 --- a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5vstestng/SelectPackagesSuiteUnitTest.java +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5vstestng/SelectPackagesSuiteUnitTest.java @@ -4,7 +4,7 @@ import org.junit.platform.suite.api.SelectPackages; import org.junit.platform.suite.api.Suite; @Suite -@SelectPackages({ "com.baeldung.java.suite.childpackage1", "com.baeldung.java.suite.childpackage2" }) +@SelectPackages({ "com.baeldung.java.suite.junit4", "com.baeldung.java.suite.junit5" }) public class SelectPackagesSuiteUnitTest { } diff --git a/testing-modules/mocks-2/README.md b/testing-modules/mocks-2/README.md index 5746da09bb..52486eb50b 100644 --- a/testing-modules/mocks-2/README.md +++ b/testing-modules/mocks-2/README.md @@ -1,4 +1,4 @@ ## Relevant articles: - [Introduction to Datafaker](https://www.baeldung.com/java-datafaker) - +- [Mocking Private Fields With Mockito](https://www.baeldung.com/java-mockito-private-fields) diff --git a/testing-modules/mocks-2/pom.xml b/testing-modules/mocks-2/pom.xml index e47649ca33..22a5198b8c 100644 --- a/testing-modules/mocks-2/pom.xml +++ b/testing-modules/mocks-2/pom.xml @@ -23,11 +23,18 @@ jackson-databind ${jackson.version} + + org.springframework + spring-test + ${spring-test.version} + test + 1.6.0 2.13.4 + 5.3.25 \ No newline at end of file diff --git a/testing-modules/mocks-2/src/main/java/com/baeldung/mockprivate/MockService.java b/testing-modules/mocks-2/src/main/java/com/baeldung/mockprivate/MockService.java new file mode 100644 index 0000000000..ab5624d973 --- /dev/null +++ b/testing-modules/mocks-2/src/main/java/com/baeldung/mockprivate/MockService.java @@ -0,0 +1,10 @@ +package com.baeldung.mockprivate; + +public class MockService { + + private final Person person = new Person("John Doe"); + + public String getName() { + return person.getName(); + } +} diff --git a/testing-modules/mocks-2/src/main/java/com/baeldung/mockprivate/Person.java b/testing-modules/mocks-2/src/main/java/com/baeldung/mockprivate/Person.java new file mode 100644 index 0000000000..405b9d58dd --- /dev/null +++ b/testing-modules/mocks-2/src/main/java/com/baeldung/mockprivate/Person.java @@ -0,0 +1,14 @@ +package com.baeldung.mockprivate; + +public class Person { + + private final String name; + + public Person(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/testing-modules/mocks-2/src/test/java/com/baeldung/mockprivate/MockServiceUnitTest.java b/testing-modules/mocks-2/src/test/java/com/baeldung/mockprivate/MockServiceUnitTest.java new file mode 100644 index 0000000000..64367a2290 --- /dev/null +++ b/testing-modules/mocks-2/src/test/java/com/baeldung/mockprivate/MockServiceUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.mockprivate; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.platform.commons.util.ReflectionUtils; +import org.springframework.test.util.ReflectionTestUtils; + +import java.lang.reflect.Field; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class MockServiceUnitTest { + + private Person mockedPerson; + + @BeforeEach + public void setUp(){ + mockedPerson = mock(Person.class); + } + + @Test + void givenNameChangedWithReflection_whenGetName_thenReturnName() throws Exception { + Class mockServiceClass = Class.forName("com.baeldung.mockprivate.MockService"); + MockService mockService = (MockService) mockServiceClass.getDeclaredConstructor().newInstance(); + Field field = mockServiceClass.getDeclaredField("person"); + field.setAccessible(true); + field.set(mockService, mockedPerson); + + when(mockedPerson.getName()).thenReturn("Jane Doe"); + + Assertions.assertEquals("Jane Doe", mockService.getName()); + } + + @Test + void givenNameChangedWithReflectionUtils_whenGetName_thenReturnName() throws Exception { + MockService mockService = new MockService(); + Field field = ReflectionUtils + .findFields(MockService.class, f -> f.getName().equals("person"), + ReflectionUtils.HierarchyTraversalMode.TOP_DOWN) + .get(0); + + field.setAccessible(true); + field.set(mockService, mockedPerson); + + when(mockedPerson.getName()).thenReturn("Jane Doe"); + + Assertions.assertEquals("Jane Doe", mockService.getName()); + } + + @Test + void givenNameChangedWithReflectionTestUtils_whenGetName_thenReturnName() throws Exception { + MockService mockService = new MockService(); + + ReflectionTestUtils.setField(mockService, "person", mockedPerson); + + when(mockedPerson.getName()).thenReturn("Jane Doe"); + Assertions.assertEquals("Jane Doe", mockService.getName()); + } + +} \ No newline at end of file diff --git a/testing-modules/mocks/pom.xml b/testing-modules/mocks/pom.xml index e447639288..281fff38c2 100644 --- a/testing-modules/mocks/pom.xml +++ b/testing-modules/mocks/pom.xml @@ -43,6 +43,26 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.lang=ALL-UNNAMED + -javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar + -Djdk.attach.allowAttachSelf + + true + + **/testsuite/**/*UnitTest.java + + + + + + 0.15 1.5 diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index 9080d5a0ea..8040113a03 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -44,6 +44,7 @@ spring-mockito spring-testing-2 spring-testing + testing-assertions test-containers testing-libraries-2 testing-libraries diff --git a/testing-modules/powermock/pom.xml b/testing-modules/powermock/pom.xml index f3237ed4df..8eedc818af 100644 --- a/testing-modules/powermock/pom.xml +++ b/testing-modules/powermock/pom.xml @@ -26,9 +26,23 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.lang=ALL-UNNAMED + + + + + + 2.21.0 - 2.0.7 + 2.0.9 \ No newline at end of file diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index f03d4f3803..323c46a5fc 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -94,6 +94,21 @@ true + + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.xml/com.sun.org.apache.xerces.internal.jaxp=ALL-UNNAMED + --add-opens java.base/java.util=ALL-UNNAMED + --add-opens java.base/java.lang.reflect=ALL-UNNAMED + --add-opens java.base/java.text=ALL-UNNAMED + --add-opens java.desktop/java.awt.font=ALL-UNNAMED + + + + diff --git a/testing-modules/rest-testing/src/test/java/com/baeldung/rest/karate/KarateIntegrationTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/karate/KarateIntegrationTest.java index 5da2784179..59d14e6ae0 100644 --- a/testing-modules/rest-testing/src/test/java/com/baeldung/rest/karate/KarateIntegrationTest.java +++ b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/karate/KarateIntegrationTest.java @@ -2,16 +2,16 @@ package com.baeldung.rest.karate; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.intuit.karate.junit4.Karate; import cucumber.api.CucumberOptions; import org.junit.AfterClass; import org.junit.BeforeClass; -import org.junit.runner.RunWith; + import static com.github.tomakehurst.wiremock.client.WireMock.*; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -@RunWith(Karate.class) +//We need to upgrade to latest version of Karate for JDK17 --- JAVA-22250 +//@RunWith(Karate.class) @CucumberOptions(features = "classpath:karate") public class KarateIntegrationTest { diff --git a/testing-modules/testing-libraries-2/README.md b/testing-modules/testing-libraries-2/README.md index 7cc08a8140..d075c40919 100644 --- a/testing-modules/testing-libraries-2/README.md +++ b/testing-modules/testing-libraries-2/README.md @@ -4,3 +4,4 @@ - [Guide to the System Stubs Library](https://www.baeldung.com/java-system-stubs) - [Code Coverage with SonarQube and JaCoCo](https://www.baeldung.com/sonarqube-jacoco-code-coverage) - [Exclusions from Jacoco Report](https://www.baeldung.com/jacoco-report-exclude) +- [Gray Box Testing Using the OAT Technique](https://www.baeldung.com/java-gray-box-orthogonal-array-testing) diff --git a/testing-modules/testing-libraries-2/pom.xml b/testing-modules/testing-libraries-2/pom.xml index b0680c1e40..6e8ab599b4 100644 --- a/testing-modules/testing-libraries-2/pom.xml +++ b/testing-modules/testing-libraries-2/pom.xml @@ -93,6 +93,16 @@
+ + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.util=ALL-UNNAMED + --add-opens java.base/java.lang=ALL-UNNAMED + + + diff --git a/testing-modules/testng/pom.xml b/testing-modules/testng/pom.xml index 72c220c118..62e2b2e578 100644 --- a/testing-modules/testng/pom.xml +++ b/testing-modules/testng/pom.xml @@ -79,7 +79,7 @@ - 7.1.0 + 7.8.0 \ No newline at end of file diff --git a/web-modules/jee-7/pom.xml b/web-modules/jee-7/pom.xml index 33ecfb3d2b..b26027d9bf 100644 --- a/web-modules/jee-7/pom.xml +++ b/web-modules/jee-7/pom.xml @@ -258,6 +258,17 @@ src/main/java + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.lang=ALL-UNNAMED + --add-opens=java.base/java.lang.reflect=ALL-UNNAMED + --add-opens java.base/java.io=ALL-UNNAMED + + + @@ -523,7 +534,7 @@ 1.0.0.Final 1.0.2.Final 1.0.0.Final - 1.4.2.Final + 2.1.1.Final 2.1.1.Final 2.22.1 diff --git a/web-modules/jee-7/src/test/java/com/baeldung/singleton/CarServiceIntegrationTest.java b/web-modules/jee-7/src/test/java/com/baeldung/singleton/CarServiceLiveTest.java similarity index 98% rename from web-modules/jee-7/src/test/java/com/baeldung/singleton/CarServiceIntegrationTest.java rename to web-modules/jee-7/src/test/java/com/baeldung/singleton/CarServiceLiveTest.java index 60a647f32c..c054f9c2db 100644 --- a/web-modules/jee-7/src/test/java/com/baeldung/singleton/CarServiceIntegrationTest.java +++ b/web-modules/jee-7/src/test/java/com/baeldung/singleton/CarServiceLiveTest.java @@ -31,9 +31,9 @@ import org.slf4j.LoggerFactory; @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class CarServiceIntegrationTest { +public class CarServiceLiveTest { - public static final Logger LOG = LoggerFactory.getLogger(CarServiceIntegrationTest.class); + public static final Logger LOG = LoggerFactory.getLogger(CarServiceLiveTest.class); @Deployment public static JavaArchive createDeployment() { diff --git a/web-modules/play-modules/README.md b/web-modules/play-modules/README.md index a28c3f7ad7..d1ac7eb2d4 100644 --- a/web-modules/play-modules/README.md +++ b/web-modules/play-modules/README.md @@ -4,5 +4,5 @@ This module contains articles about the Play Framework. ### Relevant Articles: - [REST API with Play Framework in Java](https://www.baeldung.com/rest-api-with-play) -- [Routing In Play Applications in Java](https://www.baeldung.com/routing-in-play) -- [Introduction To Play In Java](https://www.baeldung.com/java-intro-to-the-play-framework) +- [Routing in Play Applications in Java](https://www.baeldung.com/routing-in-play) +- [Introduction to Play in Java](https://www.baeldung.com/java-intro-to-the-play-framework) diff --git a/web-modules/pom.xml b/web-modules/pom.xml index efd87ba642..c009837186 100644 --- a/web-modules/pom.xml +++ b/web-modules/pom.xml @@ -23,10 +23,10 @@ javax-servlets javax-servlets-2 - + jee-7 jooby linkrest - ninja + ratpack @@ -49,4 +49,4 @@ - \ No newline at end of file + diff --git a/xml-2/README.md b/xml-2/README.md index 383d0763d4..e91078dbf0 100644 --- a/xml-2/README.md +++ b/xml-2/README.md @@ -6,3 +6,4 @@ This module contains articles about eXtensible Markup Language (XML) - [Pretty-Print XML in Java](https://www.baeldung.com/java-pretty-print-xml) - [Validate an XML File Against an XSD File](https://www.baeldung.com/java-validate-xml-xsd) +- [Converting JSON to XML in Java](https://www.baeldung.com/java-convert-json-to-xml)