Merge branch 'eugenp:master' into master

This commit is contained in:
Ulisses Lima 2023-06-07 12:18:36 -03:00 committed by GitHub
commit b0e5cff217
256 changed files with 2687 additions and 506 deletions

View File

@ -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)

View File

@ -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)

View File

@ -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)
- [Prims Algorithm with a Java Implementation](https://www.baeldung.com/java-prim-algorithm)
- [Maximum Subarray Problem in Java](https://www.baeldung.com/java-maximum-subarray)

View File

@ -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)

View File

@ -90,6 +90,12 @@
</exclusions>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty</artifactId>
<version>${mockserver.version}</version>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
@ -112,6 +118,7 @@
<!-- util -->
<httpasyncclient.version>4.1.4</httpasyncclient.version>
<!-- testing -->
<mockserver.version>5.6.1</mockserver.version>
<wiremock.version>2.5.1</wiremock.version>
<httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
<!-- http client & core 5 -->

View File

@ -0,0 +1,79 @@
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 {
serverPort = getFreePort();
System.out.println("Free port "+serverPort);
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();
}
}
}

View File

@ -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;
@ -38,7 +39,7 @@ import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
class HttpAsyncClientLiveTest {
class HttpAsyncClientLiveTest extends GetRequestMockServer {
private static final String HOST = "http://www.google.com";
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
@ -55,12 +56,12 @@ class HttpAsyncClientLiveTest {
@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 {
@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<SimpleHttpResponse> 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<SimpleHttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getCode(), equalTo(200));
client.close();

View File

@ -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();
}
}
}

View File

@ -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);

View File

@ -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)

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-poi-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
@ -19,10 +19,15 @@
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
</dependencies>
<properties>
<poi.version>5.2.0</poi.version>
<poi.version>5.2.3</poi.version>
</properties>
</project>

View File

@ -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);
}
}
}

View File

@ -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<XWPFParagraph> paragraphs, String originalText, String updatedText) {
paragraphs.forEach(paragraph -> replaceTextInParagraph(paragraph, originalText, updatedText));
}
private void replaceTextInParagraph(XWPFParagraph paragraph, String originalText, String updatedText) {
List<XWPFRun> 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);
}
}
}

View File

@ -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<XWPFParagraph> 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);
}
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -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);
}
}
}

View File

@ -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);
}
}
}

View File

@ -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);
}
}
}

View File

@ -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)

View File

@ -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)
- [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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -7,3 +7,5 @@ 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)

View File

@ -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<String> 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<String> 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<String> result = MY_LIST.stream()
.distinct()
.collect(toList());
assertThat(result).containsExactly("Microsoft Windows", "Mac OS", "GNU Linux", "Free BSD");
}
}

View File

@ -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)

View File

@ -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)

View File

@ -1,2 +1,3 @@
## 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)

View File

@ -0,0 +1,76 @@
package java.com.baeldung.objecttomap;
import com.google.gson.Gson;
import org.junit.Assert;
import org.junit.Test;
import wiremock.com.fasterxml.jackson.core.type.TypeReference;
import wiremock.com.fasterxml.jackson.databind.ObjectMapper;
import wiremock.com.google.common.reflect.TypeToken;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class ObjectToMapUnitTest {
Employee employee = new Employee("John", 3000.0);
@Test
public void givenJavaObject_whenUsingReflection_thenConvertToMap() throws IllegalAccessException {
Map<String, Object> map = convertUsingReflection(employee);
Assert.assertEquals(employee.getName(), map.get("name"));
Assert.assertEquals(employee.getSalary(), map.get("salary"));
}
private Map<String, Object> convertUsingReflection(Object object) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(object));
}
return map;
}
@Test
public void givenJavaObject_whenUsingJackson_thenConvertToMap() {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper.convertValue(employee, new TypeReference<Map<String, Object>>() {});
Assert.assertEquals(employee.getName(), map.get("name"));
Assert.assertEquals(employee.getSalary(), map.get("salary"));
}
@Test
public void givenJavaObject_whenUsingGson_thenConvertToMap() {
Gson gson = new Gson();
String json = gson.toJson(employee);
Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
Assert.assertEquals(employee.getName(), map.get("name"));
Assert.assertEquals(employee.getSalary(), map.get("salary"));
}
private static class Employee {
private String name;
private Double salary;
public Employee(String name, Double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double age) {
this.salary = salary;
}
}
}

View File

@ -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<String, Object> MAP1 = Maps.newHashMap();
static {
MAP1.put("K01", "GNU Linux");
MAP1.put("K02", "Mac OS");
MAP1.put("K03", "MS Windows");
}
private static final Map<String, String> 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<String, Object> MAP2 = Maps.newHashMap();
static {
MAP2.put("K01", "GNU Linux");
MAP2.put("K02", "Mac OS");
MAP2.put("K03", BigDecimal.ONE);
}
private static final Map<String, String> 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<String, String> result = (Map) MAP1;
assertEquals(EXPECTED_MAP1, result);
Map<String, String> result2 = (Map) MAP2;
assertFalse(result2.get("K03") instanceof String);
}
Map<String, String> checkAndTransform(Map<String, Object> inputMap) {
Map<String, String> result = new HashMap<>();
for (Map.Entry<String, Object> entry : inputMap.entrySet()) {
try {
result.put(entry.getKey(), (String) entry.getValue());
} catch (ClassCastException e) {
throw e;
}
}
return result;
}
@Test
void whenCheckAndTransform_shouldGetExpectedResult() {
Map<String, String> result = checkAndTransform(MAP1);
assertEquals(EXPECTED_MAP1, result);
assertThrows(ClassCastException.class, () -> checkAndTransform(MAP2));
}
@Test
void whenUsingStringValueOf_shouldGetExpectedResult() {
Map<String, String> result = MAP1.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue())));
assertEquals(EXPECTED_MAP1, result);
Map<String, String> result2 = MAP2.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue())));
assertEquals(EXPECTED_MAP2_STRING_VALUES, result2);
}
}

View File

@ -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)

View File

@ -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)

View File

@ -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;
}
}

View File

@ -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<CallableFactorialTask> tasks) {
BigInteger result = BigInteger.ZERO;
ExecutorService cachedPool = Executors.newCachedThreadPool();
List<Future<BigInteger>> futures;
try {
futures = cachedPool.invokeAll(tasks);
} catch (InterruptedException e) {
// exception handling example
throw new RuntimeException(e);
}
for (Future<BigInteger> future : futures) {
try {
result = result.add(future.get());
} catch (InterruptedException | ExecutionException e) {
// exception handling example
throw new RuntimeException(e);
}
}
return result;
}
}

View File

@ -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<BigInteger> {
private final Integer value;
public CallableFactorialTask(int value) {
this.value = value;
}
@Override
public BigInteger call() {
return factorial(BigInteger.valueOf(value));
}
}

View File

@ -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<Callable<BigInteger>> forkFactorials) {
List<Future<BigInteger>> futures = forkJoinPool.invokeAll(forkFactorials);
BigInteger result = BigInteger.ZERO;
for (Future<BigInteger> future : futures) {
try {
result = result.add(future.get());
} catch (InterruptedException | ExecutionException e) {
// exception handling example
throw new RuntimeException(e);
}
}
return result;
}
}

View File

@ -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<BigInteger> {
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)));
}
}

View File

@ -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);
}
}

View File

@ -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<BigInteger> completableFuture = CompletableFuture.supplyAsync(() -> factorial(BigInteger.valueOf(10)));
assertEquals(BigInteger.valueOf(3628800), completableFuture.get());
}
@Test
void givenCompletableFuture_whenComposeTasks_thenResultOk() throws ExecutionException, InterruptedException {
CompletableFuture<BigInteger> 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<BigInteger> asyncTask1 = CompletableFuture.supplyAsync(() -> BigInteger.valueOf(5));
CompletableFuture<String> 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);
}
}

View File

@ -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))));
}
}

View File

@ -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)

View File

@ -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)

View File

@ -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)
- [[Next -->]](/core-java-modules/core-java-date-operations-2)

View File

@ -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)

View File

@ -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)

View File

@ -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)
- [Whats 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)

View File

@ -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?](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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -1,10 +1 @@
### 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)

View File

@ -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)

View File

@ -3,33 +3,81 @@ package com.baeldung.regex.z_regexp;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.regex.Pattern;
public class ZRegularExpressionUnitTest {
@Test
public void givenCreditCardNumber_thenReturnIfMatched() {
String creditCardNumber = "1234567890123456";
String creditCardNumber2 = "1234567890123456\n";
String pattern = "\\d{16}\\z";
Assertions.assertTrue(creditCardNumber.matches(pattern));
Assertions.assertTrue(Pattern.compile(pattern).matcher(creditCardNumber).find());
Assertions.assertFalse(Pattern.compile(pattern).matcher(creditCardNumber2).find());
}
@Test
public void givenCreditCardNumber_thenReturnIfNotMatched() {
String creditCardNumber = "1234567890123456\n";
String pattern = "\\d{16}\\z";
Assertions.assertFalse(Pattern.compile(pattern).matcher(creditCardNumber).find());
}
@Test
public void givenLogOutput_thenReturnIfMatched() {
String logLine = "2022-05-01 14:30:00,123 INFO Some log message";
String pattern = ".*message\\z";
Assertions.assertTrue(logLine.matches(pattern));
Assertions.assertTrue(Pattern.compile(pattern).matcher(logLine).find());
}
@Test
public void givenLogOutput_thenReturnIfNotMatched() {
String logLine = "2022-05-01 14:30:00,123 INFO Some log message\n";
String pattern = ".*message\\z";
Assertions.assertFalse(Pattern.compile(pattern).matcher(logLine).find());
}
@Test
public void givenEmailMessage_thenReturnIfMatched() {
String myMessage = "Hello HR, I hope i can write to Baeldung\n";
String pattern = ".*Baeldung\\s*\\Z";
Assertions.assertTrue(myMessage.matches(pattern));
String myMessage2 = "Hello HR, I hope\n i can write to Baeldung";
String pattern = ".*Baeldung\\Z";
String pattern2 = ".*hope\\Z";
Assertions.assertTrue(Pattern.compile(pattern).matcher(myMessage).find());
Assertions.assertFalse(Pattern.compile(pattern2).matcher(myMessage2).find());
}
@Test
public void givenEmailMessage_thenReturnIfNotMatched() {
String myMessage = "Hello HR, I hope\n i can write to Baeldung";
String pattern = ".*hope\\Z";
Assertions.assertFalse(Pattern.compile(pattern).matcher(myMessage).find());
}
@Test
public void givenFileExtension_thenReturnIfMatched() {
String fileName = "image.jpeg";
String fileName = "image.jpeg\n";
String fileName2 = "image2.jpeg\n.png";
String pattern = ".*\\.jpeg\\Z";
Assertions.assertTrue(fileName.matches(pattern));
Assertions.assertTrue(Pattern.compile(pattern).matcher(fileName).find());
Assertions.assertFalse(Pattern.compile(pattern).matcher(fileName2).find());
}
}
@Test
public void givenFileExtension_thenReturnIfNotMatched() {
String fileName = "image2.jpeg\n.png";
String pattern = ".*\\.jpeg\\Z";
Assertions.assertFalse(Pattern.compile(pattern).matcher(fileName).find());
}
@Test
public void givenURL_thenReturnIfMatched() {
String url = "https://www.example.com/api/endpoint\n";
String pattern = ".*/endpoint$";
Assertions.assertTrue(Pattern.compile(pattern).matcher(url).find());
}
@Test
public void givenSentence_thenReturnIfMatched() {
String sentence = "Hello, how are you?";
String pattern = ".*[.?!]$";
Assertions.assertTrue(Pattern.compile(pattern).matcher(sentence).find());
}
}

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -0,0 +1 @@
rootProject.name = 'gradle-protobuf'

View File

@ -1 +0,0 @@
rootProject.name = 'protobuf'

View File

@ -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)

View File

@ -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)

View File

@ -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)
- More articles: [[next -->]](../javaxval-2)

View File

@ -3,5 +3,5 @@
This module contains articles about Gson
### Relevant Articles:
- [Solving Gson Parsing Errors](https://www.baeldung.com/gson-parsing-errors)

View File

@ -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

View File

@ -129,13 +129,6 @@
</dependency>
</dependencies>
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<build>
<finalName>libraries-3</finalName>
<plugins>

View File

@ -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)

View File

@ -82,7 +82,31 @@
<artifactId>converter-gson</artifactId>
<version>${retrofit.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>${jmockit.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
-javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar
</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<okhttp.version>4.9.1</okhttp.version>
@ -95,6 +119,7 @@
<spring.webflux.version>5.1.9.RELEASE</spring.webflux.version>
<reactive.stream.version>1.0.3</reactive.stream.version>
<reactor.version>3.2.12.RELEASE</reactor.version>
<jmockit.version>1.49</jmockit.version>
</properties>
</project>

View File

@ -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();
}
}

View File

@ -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 {
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -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: ");
}
}

View File

@ -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: ");
}
}

View File

@ -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: ");
}
}

Some files were not shown because too many files have changed in this diff Show More