diff --git a/.gitignore b/.gitignore
index 7b448f6cb0..5dc7abec6a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -67,6 +67,8 @@ ethereum/logs/
jmeter/src/main/resources/*-JMeter.csv
jmeter/src/main/resources/*-Basic*.csv
jmeter/src/main/resources/*-JMeter*.csv
+jmeter/src/main/resources/*ReportsDashboard*.csv
+jmeter/src/main/resources/dashboard/*ReportsDashboard*.csv
ninja/devDb.mv.db
diff --git a/README.md b/README.md
index aecd561645..7ed1e6990a 100644
--- a/README.md
+++ b/README.md
@@ -31,9 +31,11 @@ The projects are broadly divided into 3 lists: first, second and heavy.
Next, they are segregated further on the basis of the tests that we want to execute.
-Additionally, there are 2 profiles dedicated for JDK9 and above builds.
+Additionally, there are 2 profiles dedicated for JDK9 and above builds - **which require JDK 17**.
-Therefore, we have a total of 8 profiles:
+We also have a parents profile to build only parent modules.
+
+Therefore, we have a total of 9 profiles:
| Profile | Includes | Type of test enabled |
| -------------------------- | --------------------------- | -------------------- |
@@ -45,6 +47,7 @@ Therefore, we have a total of 8 profiles:
| integration-heavy | Heavy/long running projects | *IntegrationTest |
| default-jdk9-and-above | JDK9 and above projects | *UnitTest |
| integration-jdk9-and-above | JDK9 and above projects | *IntegrationTest |
+| parents | Set of parent modules | None |
Building the project
====================
diff --git a/akka-modules/akka-http/pom.xml b/akka-modules/akka-http/pom.xml
index 9372107fc9..3af7c492ca 100644
--- a/akka-modules/akka-http/pom.xml
+++ b/akka-modules/akka-http/pom.xml
@@ -36,6 +36,7 @@
+
10.0.11
2.5.11
diff --git a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java b/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java
index 2ac7adc3aa..f828d148ba 100644
--- a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java
+++ b/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java
@@ -1,22 +1,24 @@
package com.baeldung.algorithms;
-import org.junit.Assert;
-import org.junit.Test;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
-public class AntColonyOptimizationLongRunningUnitTest {
+class AntColonyOptimizationLongRunningUnitTest {
@Test
- public void testGenerateRandomMatrix() {
+ void testGenerateRandomMatrix() {
AntColonyOptimization antTSP = new AntColonyOptimization(5);
- Assert.assertNotNull(antTSP.generateRandomMatrix(5));
+ assertNotNull(antTSP.generateRandomMatrix(5));
}
@Test
- public void testStartAntOptimization() {
+ void testStartAntOptimization() {
AntColonyOptimization antTSP = new AntColonyOptimization(5);
- Assert.assertNotNull(antTSP.solve());
+ assertNotNull(antTSP.solve());
}
}
diff --git a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java b/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
index e819da4b36..a2f869e171 100644
--- a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
+++ b/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
@@ -1,16 +1,19 @@
package com.baeldung.algorithms;
-import org.junit.Assert;
-import org.junit.Test;
+
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
-public class BinaryGeneticAlgorithmLongRunningUnitTest {
+class BinaryGeneticAlgorithmLongRunningUnitTest {
@Test
- public void testGA() {
+ void testGA() {
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
- Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"));
+ assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"));
}
}
diff --git a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java b/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java
index 2ce7d75e43..461e3e9128 100644
--- a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java
+++ b/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java
@@ -1,15 +1,17 @@
package com.baeldung.algorithms;
-import org.junit.Assert;
-import org.junit.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
-public class SimulatedAnnealingLongRunningUnitTest {
+class SimulatedAnnealingLongRunningUnitTest {
@Test
- public void testSimulateAnnealing() {
- Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
+ void testSimulateAnnealing() {
+ assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
}
}
diff --git a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java
index e817d195b3..4e8f927750 100644
--- a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java
+++ b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java
@@ -1,23 +1,25 @@
package com.baeldung.algorithms;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
import com.baeldung.algorithms.hillclimbing.HillClimbing;
import com.baeldung.algorithms.hillclimbing.State;
-import org.junit.Before;
-import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-public class HillClimbingAlgorithmUnitTest {
+class HillClimbingAlgorithmUnitTest {
private Stack initStack;
private Stack goalStack;
- @Before
+ @BeforeEach
public void initStacks() {
String blockArr[] = { "B", "C", "D", "A" };
String goalBlockArr[] = { "A", "B", "C", "D" };
@@ -30,7 +32,7 @@ public class HillClimbingAlgorithmUnitTest {
}
@Test
- public void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() {
+ void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() {
HillClimbing hillClimbing = new HillClimbing();
List path;
@@ -46,7 +48,7 @@ public class HillClimbingAlgorithmUnitTest {
}
@Test
- public void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
+ void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
HillClimbing hillClimbing = new HillClimbing();
List> initList = new ArrayList<>();
initList.add(initStack);
diff --git a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
index fddccfcd9f..f3e896541d 100644
--- a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
+++ b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
@@ -1,14 +1,16 @@
package com.baeldung.algorithms;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+
import com.baeldung.algorithms.automata.*;
-import org.junit.Test;
-import static org.junit.Assert.assertTrue;
-
-public final class RtFiniteStateMachineLongRunningUnitTest {
+class RtFiniteStateMachineLongRunningUnitTest {
@Test
- public void acceptsSimplePair() {
+ void acceptsSimplePair() {
String json = "{\"key\":\"value\"}";
FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i = 0; i < json.length(); i++) {
@@ -18,7 +20,7 @@ public final class RtFiniteStateMachineLongRunningUnitTest {
}
@Test
- public void acceptsMorePairs() {
+ void acceptsMorePairs() {
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i = 0; i < json.length(); i++) {
@@ -27,13 +29,15 @@ public final class RtFiniteStateMachineLongRunningUnitTest {
assertTrue(machine.canStop());
}
- @Test(expected = IllegalArgumentException.class)
- public void missingColon() {
+ @Test
+ void missingColon() {
String json = "{\"key\"\"value\"}";
- FiniteStateMachine machine = this.buildJsonStateMachine();
- for (int i = 0; i < json.length(); i++) {
- machine = machine.switchState(String.valueOf(json.charAt(i)));
- }
+ assertThrows(IllegalArgumentException.class, () -> {
+ FiniteStateMachine machine = this.buildJsonStateMachine();
+ for (int i = 0; i < json.length(); i++) {
+ machine = machine.switchState(String.valueOf(json.charAt(i)));
+ }
+ });
}
/**
diff --git a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java
index 6fbb7c163a..e877d9945a 100644
--- a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java
+++ b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java
@@ -1,54 +1,54 @@
package com.baeldung.algorithms.kthlargest;
-import static org.assertj.core.api.Assertions.*;
+import static org.assertj.core.api.Assertions.assertThat;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class FindKthLargestUnitTest {
+class FindKthLargestUnitTest {
private FindKthLargest findKthLargest;
private Integer[] arr = { 3, 7, 1, 2, 8, 10, 4, 5, 6, 9 };
- @Before
+ @BeforeEach
public void setup() {
findKthLargest = new FindKthLargest();
}
@Test
- public void givenIntArray_whenFindKthLargestBySorting_thenGetResult() {
+ void givenIntArray_whenFindKthLargestBySorting_thenGetResult() {
int k = 3;
assertThat(findKthLargest.findKthLargestBySorting(arr, k)).isEqualTo(8);
}
@Test
- public void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() {
+ void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() {
int k = 3;
assertThat(findKthLargest.findKthLargestBySortingDesc(arr, k)).isEqualTo(8);
}
@Test
- public void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() {
+ void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() {
int k = 3;
int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
}
@Test
- public void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() {
+ void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() {
int k = 3;
int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByQuickSelectWithIterativePartition(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
}
@Test
- public void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() {
+ void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() {
int k = 3;
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, k - 1)).isEqualTo(3);
}
@Test
- public void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() {
+ void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() {
int k = 3;
int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByRandomizedQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
diff --git a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java
index 59f0fcf053..e36e3651de 100644
--- a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java
+++ b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java
@@ -1,23 +1,24 @@
package com.baeldung.algorithms.minimax;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.Assert.*;
-import com.baeldung.algorithms.minimax.MiniMax;
-import com.baeldung.algorithms.minimax.Tree;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class MinimaxUnitTest {
+class MinimaxUnitTest {
private Tree gameTree;
private MiniMax miniMax;
- @Before
+ @BeforeEach
public void initMiniMaxUtility() {
miniMax = new MiniMax();
}
@Test
- public void givenMiniMax_whenConstructTree_thenNotNullTree() {
+ void givenMiniMax_whenConstructTree_thenNotNullTree() {
assertNull(gameTree);
miniMax.constructTree(6);
gameTree = miniMax.getTree();
@@ -25,7 +26,7 @@ public class MinimaxUnitTest {
}
@Test
- public void givenMiniMax_whenCheckWin_thenComputeOptimal() {
+ void givenMiniMax_whenCheckWin_thenComputeOptimal() {
miniMax.constructTree(6);
boolean result = miniMax.checkWin();
assertTrue(result);
diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
index bbc4d4f398..7e80d335be 100644
--- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
+++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
@@ -1,6 +1,6 @@
package com.baeldung.algorithms;
-import org.junit.Test;
+
import com.baeldung.algorithms.ga.dijkstra.Dijkstra;
import com.baeldung.algorithms.ga.dijkstra.Graph;
@@ -11,7 +11,9 @@ import java.util.List;
import static org.junit.Assert.assertTrue;
-public class DijkstraAlgorithmLongRunningUnitTest {
+import org.junit.jupiter.api.Test;
+
+class DijkstraAlgorithmLongRunningUnitTest {
@Test
public void whenSPPSolved_thenCorrect() {
diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/astar/underground/RouteFinderIntegrationTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/astar/underground/RouteFinderIntegrationTest.java
index aba7f149da..ba492b33cf 100644
--- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/astar/underground/RouteFinderIntegrationTest.java
+++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/astar/underground/RouteFinderIntegrationTest.java
@@ -1,5 +1,6 @@
package com.baeldung.algorithms.astar.underground;
+
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
@@ -10,22 +11,22 @@ import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
import com.baeldung.algorithms.astar.Graph;
import com.baeldung.algorithms.astar.RouteFinder;
import lombok.extern.slf4j.Slf4j;
-import org.junit.Before;
-import org.junit.Test;
-
@Slf4j
-public class RouteFinderIntegrationTest {
+class RouteFinderIntegrationTest {
private Graph underground;
private RouteFinder routeFinder;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
Set stations = new HashSet<>();
Map> connections = new HashMap<>();
@@ -641,7 +642,7 @@ public class RouteFinderIntegrationTest {
}
@Test
- public void findRoute() {
+ void findRoute() {
List route = routeFinder.findRoute(underground.getNode("74"), underground.getNode("7"));
assertThat(route).size().isPositive();
diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java
deleted file mode 100644
index d11da61191..0000000000
--- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.baeldung.algorithms.editdistance;
-
-import org.junit.runners.Parameterized.Parameters;
-
-import java.util.Arrays;
-import java.util.Collection;
-
-public class EditDistanceDataProvider {
-
- @Parameters
- public static Collection
-
\ No newline at end of file
+
diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java
index 7576e49034..720049378b 100644
--- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java
+++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java
@@ -1,19 +1,24 @@
package com.baeldung.httpclient;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpStatus;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.entity.ContentType;
-import org.apache.http.entity.mime.HttpMultipartMode;
-import org.apache.http.entity.mime.MultipartEntityBuilder;
-import org.apache.http.entity.mime.content.FileBody;
-import org.apache.http.entity.mime.content.StringBody;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import org.apache.hc.client5.http.classic.methods.HttpPost;
+import org.apache.hc.client5.http.entity.mime.FileBody;
+import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
+import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
+import org.apache.hc.client5.http.entity.mime.StringBody;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
+import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
+
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpEntity;
+import org.apache.hc.core5.http.HttpStatus;
import java.io.BufferedReader;
import java.io.File;
@@ -22,14 +27,10 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
+import com.baeldung.httpclient.handler.CustomHttpClientResponseHandler;
-public class HttpClientMultipartLiveTest {
+class HttpClientMultipartLiveTest {
// No longer available
// private static final String SERVER = "http://echo.200please.com";
@@ -38,41 +39,16 @@ public class HttpClientMultipartLiveTest {
private static final String TEXTFILENAME = "temp.txt";
private static final String IMAGEFILENAME = "image.jpg";
private static final String ZIPFILENAME = "zipFile.zip";
- private static final Logger LOGGER = Logger.getLogger("com.baeldung.httpclient.HttpClientMultipartLiveTest");
- private CloseableHttpClient client;
private HttpPost post;
private BufferedReader rd;
- private CloseableHttpResponse response;
- @Before
- public final void before() {
- client = HttpClientBuilder.create()
- .build();
+ @BeforeEach
+ public void before() {
post = new HttpPost(SERVER);
}
- @After
- public final void after() throws IllegalStateException, IOException {
- post.completed();
- try {
- client.close();
- } catch (final IOException e1) {
- LOGGER.log(Level.SEVERE, e1.getMessage(), e1);
- throw e1;
- }
- try {
- rd.close();
- } catch (final IOException e) {
- LOGGER.log(Level.SEVERE, e.getMessage(), e);
- throw e;
- }
- ResponseUtil.closeResponse(response);
- }
-
- // tests
-
@Test
- public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
+ void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
final URL url = Thread.currentThread()
.getContextClassLoader()
.getResource("uploads/" + TEXTFILENAME);
@@ -83,53 +59,61 @@ public class HttpClientMultipartLiveTest {
final StringBody stringBody2 = new StringBody("This is message 2", ContentType.MULTIPART_FORM_DATA);
//
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
- builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
+ builder.setMode(HttpMultipartMode.LEGACY);
builder.addPart("file", fileBody);
builder.addPart("text1", stringBody1);
builder.addPart("text2", stringBody2);
final HttpEntity entity = builder.build();
- //
- post.setEntity(entity);
- response = client.execute(post);
- final int statusCode = response.getStatusLine()
- .getStatusCode();
- final String responseString = getContent();
- final String contentTypeInHeader = getContentTypeHeader();
- assertThat(statusCode, equalTo(HttpStatus.SC_OK));
- // assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
- assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
- System.out.println(responseString);
- System.out.println("POST Content Type: " + contentTypeInHeader);
+ post.setEntity(entity);
+ try(CloseableHttpClient client = HttpClientBuilder.create()
+ .build();
+
+ CloseableHttpResponse response = (CloseableHttpResponse) client
+ .execute(post, new CustomHttpClientResponseHandler())){
+ final int statusCode = response.getCode();
+ final String responseString = getContent(response.getEntity());
+ final String contentTypeInHeader = getContentTypeHeader();
+
+ assertThat(statusCode, equalTo(HttpStatus.SC_OK));
+ assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
+ System.out.println(responseString);
+ System.out.println("POST Content Type: " + contentTypeInHeader);
+ }
}
@Test
- public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
+ void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
final URL url = Thread.currentThread()
.getContextClassLoader()
.getResource("uploads/" + TEXTFILENAME);
final File file = new File(url.getPath());
final String message = "This is a multipart post";
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
- builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
+ builder.setMode(HttpMultipartMode.LEGACY);
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, TEXTFILENAME);
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
final HttpEntity entity = builder.build();
post.setEntity(entity);
- response = client.execute(post);
- final int statusCode = response.getStatusLine()
- .getStatusCode();
- final String responseString = getContent();
- final String contentTypeInHeader = getContentTypeHeader();
- assertThat(statusCode, equalTo(HttpStatus.SC_OK));
- // assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
- assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
- System.out.println(responseString);
- System.out.println("POST Content Type: " + contentTypeInHeader);
+
+ try(CloseableHttpClient client = HttpClientBuilder.create()
+ .build();
+
+ CloseableHttpResponse response = (CloseableHttpResponse) client
+ .execute(post, new CustomHttpClientResponseHandler())){
+
+ final int statusCode = response.getCode();
+ final String responseString = getContent(response.getEntity());
+ final String contentTypeInHeader = getContentTypeHeader();
+ assertThat(statusCode, equalTo(HttpStatus.SC_OK));
+ assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
+ System.out.println(responseString);
+ System.out.println("POST Content Type: " + contentTypeInHeader);
+ }
}
@Test
- public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
+ void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
final URL url = Thread.currentThread()
.getContextClassLoader()
.getResource("uploads/" + ZIPFILENAME);
@@ -140,64 +124,75 @@ public class HttpClientMultipartLiveTest {
final File file = new File(url2.getPath());
final String message = "This is a multipart post";
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
- builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
+ builder.setMode(HttpMultipartMode.LEGACY);
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, IMAGEFILENAME);
builder.addBinaryBody("upstream", inputStream, ContentType.create("application/zip"), ZIPFILENAME);
builder.addTextBody("text", message, ContentType.TEXT_PLAIN);
final HttpEntity entity = builder.build();
post.setEntity(entity);
- response = client.execute(post);
- final int statusCode = response.getStatusLine()
- .getStatusCode();
- final String responseString = getContent();
- final String contentTypeInHeader = getContentTypeHeader();
- assertThat(statusCode, equalTo(HttpStatus.SC_OK));
- // assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
- assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
- System.out.println(responseString);
- System.out.println("POST Content Type: " + contentTypeInHeader);
- inputStream.close();
+
+ try(CloseableHttpClient client = HttpClientBuilder.create()
+ .build();
+
+ CloseableHttpResponse response = (CloseableHttpResponse) client
+ .execute(post, new CustomHttpClientResponseHandler())){
+
+ final int statusCode = response.getCode();
+ final String responseString = getContent(response.getEntity());
+ final String contentTypeInHeader = getContentTypeHeader();
+ assertThat(statusCode, equalTo(HttpStatus.SC_OK));
+ assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
+ System.out.println(responseString);
+ System.out.println("POST Content Type: " + contentTypeInHeader);
+ inputStream.close();
+ }
}
@Test
- public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
+ void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
final String message = "This is a multipart post";
final byte[] bytes = "binary code".getBytes();
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
- builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
+ builder.setMode(HttpMultipartMode.LEGACY);
builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, TEXTFILENAME);
builder.addTextBody("text", message, ContentType.TEXT_PLAIN);
final HttpEntity entity = builder.build();
post.setEntity(entity);
- response = client.execute(post);
- final int statusCode = response.getStatusLine()
- .getStatusCode();
- final String responseString = getContent();
- final String contentTypeInHeader = getContentTypeHeader();
- assertThat(statusCode, equalTo(HttpStatus.SC_OK));
- // assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
- assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
- System.out.println(responseString);
- System.out.println("POST Content Type: " + contentTypeInHeader);
+
+ try(CloseableHttpClient client = HttpClientBuilder.create()
+ .build();
+
+ CloseableHttpResponse response = (CloseableHttpResponse) client
+ .execute(post, new CustomHttpClientResponseHandler())){
+
+ final int statusCode = response.getCode();
+ final String responseString = getContent(response.getEntity());
+ final String contentTypeInHeader = getContentTypeHeader();
+ assertThat(statusCode, equalTo(HttpStatus.SC_OK));
+ assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
+ System.out.println(responseString);
+ System.out.println("POST Content Type: " + contentTypeInHeader);
+ }
+
}
// UTIL
- private String getContent() throws IOException {
- rd = new BufferedReader(new InputStreamReader(response.getEntity()
- .getContent()));
+ private String getContent(HttpEntity httpEntity) throws IOException {
+ rd = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
String body = "";
StringBuilder content = new StringBuilder();
while ((body = rd.readLine()) != null) {
- content.append(body).append("\n");
+ content.append(body)
+ .append("\n");
}
- return content.toString().trim();
+ return content.toString()
+ .trim();
}
- private String getContentTypeHeader() throws IOException {
+ private String getContentTypeHeader() {
return post.getEntity()
- .getContentType()
- .toString();
+ .getContentType();
}
}
diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java
new file mode 100644
index 0000000000..0559854b35
--- /dev/null
+++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java
@@ -0,0 +1,11 @@
+package com.baeldung.httpclient.handler;
+
+import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.io.HttpClientResponseHandler;
+
+public class CustomHttpClientResponseHandler implements HttpClientResponseHandler {
+ @Override
+ public ClassicHttpResponse handleResponse(ClassicHttpResponse response) {
+ return response;
+ }
+}
\ No newline at end of file
diff --git a/apache-libraries/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java b/apache-libraries/src/main/java/com/baeldung/avro/util/serialization/AvroDeSerializer.java
similarity index 84%
rename from apache-libraries/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
rename to apache-libraries/src/main/java/com/baeldung/avro/util/serialization/AvroDeSerializer.java
index 7d30c3d1ee..cf4c360ba4 100644
--- a/apache-libraries/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
+++ b/apache-libraries/src/main/java/com/baeldung/avro/util/serialization/AvroDeSerializer.java
@@ -1,4 +1,4 @@
-package com.baeldung.avro.util.serealization;
+package com.baeldung.avro.util.serialization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.DatumReader;
@@ -10,11 +10,11 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
-public class AvroDeSerealizer {
+public class AvroDeSerializer {
- private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
+ private static Logger logger = LoggerFactory.getLogger(AvroDeSerializer.class);
- public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) {
+ public AvroHttpRequest deSerializeAvroHttpRequestJSON(byte[] data) {
DatumReader reader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = null;
try {
@@ -27,7 +27,7 @@ public class AvroDeSerealizer {
return null;
}
- public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data) {
+ public AvroHttpRequest deSerializeAvroHttpRequestBinary(byte[] data) {
DatumReader employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = DecoderFactory.get()
.binaryDecoder(data, null);
diff --git a/apache-libraries/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java b/apache-libraries/src/main/java/com/baeldung/avro/util/serialization/AvroSerializer.java
similarity index 87%
rename from apache-libraries/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
rename to apache-libraries/src/main/java/com/baeldung/avro/util/serialization/AvroSerializer.java
index 767b688dea..6d39060ec8 100644
--- a/apache-libraries/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
+++ b/apache-libraries/src/main/java/com/baeldung/avro/util/serialization/AvroSerializer.java
@@ -1,4 +1,4 @@
-package com.baeldung.avro.util.serealization;
+package com.baeldung.avro.util.serialization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.*;
@@ -9,11 +9,11 @@ import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-public class AvroSerealizer {
+public class AvroSerializer {
- private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class);
+ private static final Logger logger = LoggerFactory.getLogger(AvroSerializer.class);
- public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request) {
+ public byte[] serializeAvroHttpRequestJSON(AvroHttpRequest request) {
DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
@@ -30,7 +30,7 @@ public class AvroSerealizer {
return data;
}
- public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request) {
+ public byte[] serializeAvroHttpRequestBinary(AvroHttpRequest request) {
DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
diff --git a/apache-libraries/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerIntegrationTest.java b/apache-libraries/src/test/java/com/baeldung/avro/util/serialization/AvroSerializerDeSerializerIntegrationTest.java
similarity index 75%
rename from apache-libraries/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerIntegrationTest.java
rename to apache-libraries/src/test/java/com/baeldung/avro/util/serialization/AvroSerializerDeSerializerIntegrationTest.java
index 3d413e1939..964eeb6d87 100644
--- a/apache-libraries/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerIntegrationTest.java
+++ b/apache-libraries/src/test/java/com/baeldung/avro/util/serialization/AvroSerializerDeSerializerIntegrationTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.avro.util.serealization;
+package com.baeldung.avro.util.serialization;
import com.baeldung.avro.util.model.Active;
import com.baeldung.avro.util.model.AvroHttpRequest;
@@ -13,16 +13,16 @@ import java.util.Objects;
import static org.junit.Assert.*;
-public class AvroSerealizerDeSerealizerIntegrationTest {
+public class AvroSerializerDeSerializerIntegrationTest {
- AvroSerealizer serealizer;
- AvroDeSerealizer deSerealizer;
+ AvroSerializer serializer;
+ AvroDeSerializer deserializer;
AvroHttpRequest request;
@Before
public void setUp() throws Exception {
- serealizer = new AvroSerealizer();
- deSerealizer = new AvroDeSerealizer();
+ serializer = new AvroSerializer();
+ deserializer = new AvroDeSerializer();
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder()
.setHostName("localhost")
@@ -49,22 +49,22 @@ public class AvroSerealizerDeSerealizerIntegrationTest {
@Test
public void WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() {
- byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
+ byte[] data = serializer.serializeAvroHttpRequestJSON(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() {
- byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
+ byte[] data = serializer.serializeAvroHttpRequestBinary(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() {
- byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
- AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
+ byte[] data = serializer.serializeAvroHttpRequestJSON(request);
+ AvroHttpRequest actualRequest = deserializer.deSerializeAvroHttpRequestJSON(data);
assertEquals(actualRequest, request);
assertTrue(actualRequest.getRequestTime()
.equals(request.getRequestTime()));
@@ -72,12 +72,12 @@ public class AvroSerealizerDeSerealizerIntegrationTest {
@Test
public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() {
- byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
- AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
+ byte[] data = serializer.serializeAvroHttpRequestBinary(request);
+ AvroHttpRequest actualRequest = deserializer.deSerializeAvroHttpRequestBinary(data);
assertEquals(actualRequest, request);
assertTrue(actualRequest.getRequestTime()
.equals(request.getRequestTime()));
}
-
+
}
diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml
index f4b6de8872..a562ebeec0 100644
--- a/apache-velocity/pom.xml
+++ b/apache-velocity/pom.xml
@@ -63,6 +63,7 @@
4.5.2
1.7
2.0
+ 3.3.2
\ No newline at end of file
diff --git a/asciidoctor/pom.xml b/asciidoctor/pom.xml
index e24917f2f4..b72f050379 100644
--- a/asciidoctor/pom.xml
+++ b/asciidoctor/pom.xml
@@ -62,10 +62,10 @@
- 1.5.6
- 1.5.6
- 1.5.0-alpha.15
- 1.5.0-alpha.15
+ 2.2.2
+ 2.5.7
+ 2.3.4
+ 2.3.4
\ No newline at end of file
diff --git a/aws-modules/aws-reactive/pom.xml b/aws-modules/aws-reactive/pom.xml
index fbad5e30d0..e6b50cadb2 100644
--- a/aws-modules/aws-reactive/pom.xml
+++ b/aws-modules/aws-reactive/pom.xml
@@ -77,6 +77,7 @@
org.projectlombok
lombok
+ ${lombok.version}
@@ -92,6 +93,7 @@
2.2.1.RELEASE
2.17.283
+ 1.18.20
\ No newline at end of file
diff --git a/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointIntegrationTest.java b/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java
similarity index 98%
rename from axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointIntegrationTest.java
rename to axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java
index a30e42766b..3b5c130c89 100644
--- a/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointIntegrationTest.java
+++ b/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java
@@ -27,7 +27,8 @@ import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(classes = OrderApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
-class OrderRestEndpointIntegrationTest {
+//marked as manual as the test is unstable on Jenkins due to low resources
+class OrderRestEndpointManualTest {
@LocalServerPort
private int port;
diff --git a/azure/pom.xml b/azure/pom.xml
index ae20ae7785..6a06282a71 100644
--- a/azure/pom.xml
+++ b/azure/pom.xml
@@ -36,8 +36,8 @@
runtime
- mysql
- mysql-connector-java
+ com.mysql
+ mysql-connector-j
runtime
diff --git a/core-java-modules/core-java-11-3/README.md b/core-java-modules/core-java-11-3/README.md
index e77e5b7f3d..4f5eb3ea56 100644
--- a/core-java-modules/core-java-11-3/README.md
+++ b/core-java-modules/core-java-11-3/README.md
@@ -5,3 +5,4 @@ This module contains articles about Java 11 core features
### Relevant articles
- [Adding Parameters to Java HttpClient Requests](https://www.baeldung.com/java-httpclient-request-parameters)
- [Writing a List of Strings Into a Text File](https://www.baeldung.com/java-list-to-text-file)
+- [Java HttpClient – Map JSON Response to Java Class](https://www.baeldung.com/java-httpclient-map-json-response)
diff --git a/core-java-modules/core-java-14/README.md b/core-java-modules/core-java-14/README.md
index 00fd2fa320..97be9391fb 100644
--- a/core-java-modules/core-java-14/README.md
+++ b/core-java-modules/core-java-14/README.md
@@ -12,3 +12,4 @@ This module contains articles about Java 14.
- [Java 14 Record Keyword](https://www.baeldung.com/java-record-keyword)
- [New Features in Java 14](https://www.baeldung.com/java-14-new-features)
- [Java 14 Record vs. Lombok](https://www.baeldung.com/java-record-vs-lombok)
+- [Record vs. Final Class in Java](https://www.baeldung.com/java-record-vs-final-class)
diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordvsfinal/USCitizen.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordvsfinal/USCitizen.java
new file mode 100644
index 0000000000..9ff3676ae7
--- /dev/null
+++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordvsfinal/USCitizen.java
@@ -0,0 +1,18 @@
+package com.baeldung.java14.recordvsfinal;
+
+public record USCitizen(String firstName, String lastName, String address) {
+ static int countryCode;
+
+ // static initializer
+ static {
+ countryCode = 1;
+ }
+
+ public static int getCountryCode() {
+ return countryCode;
+ }
+
+ public String getFullName() {
+ return firstName + " " + lastName;
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/recordvsfinal/USCitizenUnitTest.java b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/recordvsfinal/USCitizenUnitTest.java
new file mode 100644
index 0000000000..bb4c16b500
--- /dev/null
+++ b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/recordvsfinal/USCitizenUnitTest.java
@@ -0,0 +1,26 @@
+package com.baeldung.java14.recordvsfinal;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class USCitizenUnitTest {
+
+ @Test
+ public void givenName_whenGetNameAndCode_thenExpectedValuesReturned() {
+
+ String firstName = "Joan";
+ String lastName = "Winn";
+ String address = "1892 Black Stallion Road";
+ int countryCode = 1;
+
+ USCitizen citizen = new USCitizen(firstName, lastName, address);
+
+ assertEquals(firstName + " " + lastName, citizen.getFullName());
+ assertEquals(countryCode, USCitizen.getCountryCode());
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-19/README.md b/core-java-modules/core-java-19/README.md
index 9663296da0..6a9c6c7fdd 100644
--- a/core-java-modules/core-java-19/README.md
+++ b/core-java-modules/core-java-19/README.md
@@ -1,2 +1,3 @@
## Relevant Articles
- [Record Patterns in Java 19](https://www.baeldung.com/java-19-record-patterns)
+- [Structured Concurrency in Java 19](https://www.baeldung.com/java-structured-concurrency)
diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/argsVsvarargs/StringArrayAndVarargs.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/argsVsvarargs/StringArrayAndVarargs.java
new file mode 100644
index 0000000000..dc9137646f
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/argsVsvarargs/StringArrayAndVarargs.java
@@ -0,0 +1,19 @@
+package com.baeldung.argsVsvarargs;
+
+public class StringArrayAndVarargs {
+ public static void capitalizeNames(String[] args) {
+ for(int i = 0; i < args.length; i++){
+ args[i] = args[i].toUpperCase();
+ }
+
+ }
+
+ public static String[] firstLetterOfWords(String... args) {
+ String[] firstLetter = new String[args.length];
+ for(int i = 0; i < args.length; i++){
+ firstLetter[i] = String.valueOf(args[i].charAt(0));
+ }
+ return firstLetter;
+ }
+
+}
diff --git a/core-java-modules/core-java-8-2/src/test/java/com/baeldung/argsVsvarargs/StringArrayAndVarargsUnitTest.java b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/argsVsvarargs/StringArrayAndVarargsUnitTest.java
new file mode 100644
index 0000000000..f917373229
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/argsVsvarargs/StringArrayAndVarargsUnitTest.java
@@ -0,0 +1,24 @@
+package com.baeldung.argsVsvarargs;
+
+import static com.baeldung.argsVsvarargs.StringArrayAndVarargs.capitalizeNames;
+import static com.baeldung.argsVsvarargs.StringArrayAndVarargs.firstLetterOfWords;
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class StringArrayAndVarargsUnitTest {
+
+ @Test
+ void whenCheckingArgumentClassName_thenNameShouldBeStringArray() {
+ String[] names = {"john", "ade", "kofi", "imo"};
+ assertNotNull(names);
+ assertEquals("java.lang.String[]", names.getClass().getTypeName());
+ capitalizeNames(names);
+ }
+
+ @Test
+ void whenCheckingReturnedObjectClass_thenClassShouldBeStringArray() {
+ assertEquals(String[].class, firstLetterOfWords("football", "basketball", "volleyball").getClass());
+ assertEquals(3, firstLetterOfWords("football", "basketball", "volleyball").length);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/StringArrayToIntArrayUnitTest.java b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/StringArrayToIntArrayUnitTest.java
new file mode 100644
index 0000000000..3675778f90
--- /dev/null
+++ b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/StringArrayToIntArrayUnitTest.java
@@ -0,0 +1,63 @@
+package com.baeldung.array.conversions;
+
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+
+
+public class StringArrayToIntArrayUnitTest {
+ private final String[] stringArray = new String[] { "1", "2", "3", "4", "5", "6", "42" };
+ private final int[] expected = new int[] { 1, 2, 3, 4, 5, 6, 42 };
+
+ private final String[] stringArrayWithInvalidNum = new String[] { "1", "2", "hello", "4", "world", "6", "42" };
+ private final int[] expectedWithInvalidInput = new int[] { 1, 2, Integer.MIN_VALUE, 4, Integer.MIN_VALUE, 6, 42 };
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ @Test
+ void givenStringArray_whenUseStreamApi_shouldGetExpectedIntArray() {
+ int[] result = Arrays.stream(stringArray).mapToInt(Integer::parseInt).toArray();
+ assertArrayEquals(expected, result);
+ }
+
+ @Test
+ void givenStringArrayWithInvalidNum_whenUseStreamApi_shouldGetExpectedIntArray() {
+ int[] result = Arrays.stream(stringArrayWithInvalidNum).mapToInt(s -> {
+ try {
+ return Integer.parseInt(s);
+ } catch (NumberFormatException ex) {
+ logger.warn("Invalid number format detected: {}, use Int.MinValue as the fallback", s);
+ return Integer.MIN_VALUE;
+ }
+ }).toArray();
+ assertArrayEquals(expectedWithInvalidInput, result);
+ }
+
+ @Test
+ void givenStringArray_whenConvertInLoop_shouldGetExpectedIntArray() {
+ int[] result = new int[stringArray.length];
+ for (int i = 0; i < stringArray.length; i++) {
+ result[i] = Integer.parseInt(stringArray[i]);
+ }
+ assertArrayEquals(expected, result);
+ }
+
+ @Test
+ void givenStringArrayWithInvalidNum_whenConvertInLoop_shouldGetExpectedIntArray() {
+ int[] result = new int[stringArrayWithInvalidNum.length];
+ for (int i = 0; i < stringArrayWithInvalidNum.length; i++) {
+ try {
+ result[i] = Integer.parseInt(stringArrayWithInvalidNum[i]);
+ } catch (NumberFormatException exception) {
+ logger.warn("Invalid number format detected: [{}], use Int.MinValue as the fallback", stringArrayWithInvalidNum[i]);
+ result[i] = Integer.MIN_VALUE;
+ }
+ }
+
+ assertArrayEquals(expectedWithInvalidInput, result);
+ }
+}
diff --git a/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/isobjectarray/CheckObjectIsArrayUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/isobjectarray/CheckObjectIsArrayUnitTest.java
new file mode 100644
index 0000000000..ed38ab0765
--- /dev/null
+++ b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/isobjectarray/CheckObjectIsArrayUnitTest.java
@@ -0,0 +1,78 @@
+package com.baeldung.array.isobjectarray;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Array;
+
+import org.junit.jupiter.api.Test;
+
+public class CheckObjectIsArrayUnitTest {
+ private static final Object ARRAY_INT = new int[] { 1, 2, 3, 4, 5 };
+ private static final Object ARRAY_PERSON = new Person[] { new Person("Jackie Chan", "Hong Kong"), new Person("Tom Hanks", "United States") };
+
+ boolean isArray(Object obj) {
+ return obj instanceof Object[] || obj instanceof boolean[] || obj instanceof byte[] || obj instanceof short[] || obj instanceof char[] || obj instanceof int[] || obj instanceof long[] || obj instanceof float[] || obj instanceof double[];
+ }
+
+ @Test
+ void givenAnArrayObject_whenUsingInstanceof_getExpectedResult() {
+ assertTrue(ARRAY_PERSON instanceof Object[]);
+ assertFalse(ARRAY_INT instanceof Object[]);
+ assertTrue(ARRAY_INT instanceof int[]);
+ }
+
+ @Test
+ void givenAnArrayObject_whenUsingOurIsArray_getExpectedResult() {
+ assertTrue(isArray(ARRAY_PERSON));
+ assertTrue(isArray(ARRAY_INT));
+ }
+
+ @Test
+ void givenAnArrayObject_whenUsingClassIsArray_getExpectedResult() {
+ assertTrue(ARRAY_INT.getClass()
+ .isArray());
+ assertTrue(ARRAY_PERSON.getClass()
+ .isArray());
+
+ assertEquals(Person.class, ARRAY_PERSON.getClass()
+ .getComponentType());
+ assertEquals(int.class, ARRAY_INT.getClass()
+ .getComponentType());
+
+ }
+
+ @Test
+ void givenAnArrayObject_whenUsingArrayGet_getExpectedElement() {
+ if (ARRAY_PERSON.getClass()
+ .isArray() && ARRAY_PERSON.getClass()
+ .getComponentType() == Person.class) {
+ Person person = (Person) Array.get(ARRAY_PERSON, 1);
+ assertEquals("Tom Hanks", person.getName());
+ }
+ if (ARRAY_INT.getClass()
+ .isArray() && ARRAY_INT.getClass()
+ .getComponentType() == int.class) {
+ assertEquals(2, ((int) Array.get(ARRAY_INT, 1)));
+ }
+ }
+}
+
+class Person {
+ private String name;
+ private String Location;
+
+ public Person(String name, String location) {
+ this.name = name;
+ this.Location = location;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getLocation() {
+ return Location;
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-array-list/README.md b/core-java-modules/core-java-collections-array-list/README.md
index 53568ca98a..e3d41d8f88 100644
--- a/core-java-modules/core-java-collections-array-list/README.md
+++ b/core-java-modules/core-java-collections-array-list/README.md
@@ -12,3 +12,4 @@ This module contains articles about the Java ArrayList collection
- [Case-Insensitive Searching in ArrayList](https://www.baeldung.com/java-arraylist-case-insensitive-search)
- [Storing Data Triple in a List in Java](https://www.baeldung.com/java-list-storing-triple)
- [Convert an ArrayList of Object to an ArrayList of String Elements](https://www.baeldung.com/java-object-list-to-strings)
+- [Initialize an ArrayList with Zeroes or Null in Java](https://www.baeldung.com/java-arraylist-with-zeroes-or-null)
diff --git a/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/combine2liststomap/CombineTwoListsInAMapUnitTest.java b/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/combine2liststomap/CombineTwoListsInAMapUnitTest.java
new file mode 100644
index 0000000000..501ec16a21
--- /dev/null
+++ b/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/combine2liststomap/CombineTwoListsInAMapUnitTest.java
@@ -0,0 +1,62 @@
+package com.baeldung.combine2liststomap;
+
+import static java.lang.Math.min;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import org.junit.jupiter.api.Test;
+
+public class CombineTwoListsInAMapUnitTest {
+ private static final List KEY_LIST = Arrays.asList("Number One", "Number Two", "Number Three", "Number Four", "Number Five");
+ private static final List VALUE_LIST = Arrays.asList(1, 2, 3, 4, 5);
+ private static final Map EXPECTED_MAP = new HashMap() {{
+ put("Number One", 1);
+ put("Number Two", 2);
+ put("Number Three", 3);
+ put("Number Four", 4);
+ put("Number Five", 5);
+ }};
+
+ @Test
+ void givenTwoLists_whenUsingLoopAndListGet_shouldGetExpectedMap() {
+ Map result = new HashMap<>();
+ int size = KEY_LIST.size();
+ if (KEY_LIST.size() != VALUE_LIST.size()) {
+ // throw an exception or print a warning
+ size = min(KEY_LIST.size(), VALUE_LIST.size());
+ }
+ for (int i = 0; i < size; i++) {
+ result.put(KEY_LIST.get(i), VALUE_LIST.get(i));
+ }
+ assertEquals(EXPECTED_MAP, result);
+ }
+
+ @Test
+ void givenTwoLists_whenUsingStreamApiAndListGet_shouldGetExpectedMap() {
+ Map result = IntStream.range(0, KEY_LIST.size())
+ .boxed()
+ .collect(Collectors.toMap(KEY_LIST::get, VALUE_LIST::get));
+ assertEquals(EXPECTED_MAP, result);
+ }
+
+ @Test
+ void givenTwoLists_whenUsingIterators_shouldGetExpectedMap() {
+ Map result = new HashMap<>();
+
+ Iterator ik = KEY_LIST.iterator();
+ Iterator iv = VALUE_LIST.iterator();
+ while (ik.hasNext() && iv.hasNext()) {
+ result.put(ik.next(), iv.next());
+ }
+
+ assertEquals(EXPECTED_MAP, result);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-maps-6/pom.xml b/core-java-modules/core-java-collections-maps-6/pom.xml
new file mode 100644
index 0000000000..9910d08691
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-6/pom.xml
@@ -0,0 +1,20 @@
+
+
+ core-java-collections-maps-6
+ 0.1.0-SNAPSHOT
+ core-java-collections-maps-6
+ jar
+
+ core-java-modules
+ com.baeldung.core-java-modules
+ 0.0.1-SNAPSHOT
+
+ 4.0.0
+
+
+ 5.2.5.RELEASE
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-maps-6/src/main/java/com/baeldung/map/hashmapcopy/CopyingAHashMapToAnother.java b/core-java-modules/core-java-collections-maps-6/src/main/java/com/baeldung/map/hashmapcopy/CopyingAHashMapToAnother.java
new file mode 100644
index 0000000000..77a6402a75
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-6/src/main/java/com/baeldung/map/hashmapcopy/CopyingAHashMapToAnother.java
@@ -0,0 +1,47 @@
+package com.baeldung.map.hashmapcopy;
+
+import java.util.Map;
+
+import com.google.common.collect.MapDifference;
+import com.google.common.collect.Maps;
+
+public class CopyingAHashMapToAnother {
+ public Map copyByIteration(Map sourceMap, Map targetMap) {
+ for (Map.Entry entry : sourceMap.entrySet()) {
+ if (!targetMap.containsKey(entry.getKey())) {
+ targetMap.put(entry.getKey(), entry.getValue());
+ }
+ }
+ return targetMap;
+ }
+
+ public Map copyUsingPutAll(Map sourceMap, Map targetMap) {
+ sourceMap.keySet()
+ .removeAll(targetMap.keySet());
+ targetMap.putAll(sourceMap);
+ return targetMap;
+ }
+
+ public Map copyUsingPutIfAbsent(Map sourceMap, Map targetMap) {
+ for (Map.Entry entry : sourceMap.entrySet()) {
+ targetMap.putIfAbsent(entry.getKey(), entry.getValue());
+ }
+ return targetMap;
+ }
+
+ public Map copyUsingPutIfAbsentForEach(Map sourceMap, Map targetMap) {
+ sourceMap.forEach(targetMap::putIfAbsent);
+ return targetMap;
+ }
+
+ public Map copyUsingMapMerge(Map sourceMap, Map targetMap) {
+ sourceMap.forEach((key, value) -> targetMap.merge(key, value, (oldVal, newVal) -> oldVal));
+ return targetMap;
+ }
+
+ public Map copyUsingGuavaMapDifference(Map sourceMap, Map targetMap) {
+ MapDifference differenceMap = Maps.difference(sourceMap, targetMap);
+ targetMap.putAll(differenceMap.entriesOnlyOnLeft());
+ return targetMap;
+ }
+}
diff --git a/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/hashmapcopy/CopyHashMapIntoAnotherUnitTest.java b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/hashmapcopy/CopyHashMapIntoAnotherUnitTest.java
new file mode 100644
index 0000000000..b11f470eb3
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/hashmapcopy/CopyHashMapIntoAnotherUnitTest.java
@@ -0,0 +1,68 @@
+package com.baeldung.map.hashmapcopy;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.baeldung.map.hashmapcopy.CopyingAHashMapToAnother;
+
+public class CopyHashMapIntoAnotherUnitTest {
+ @Test
+ public void givenSourceAndTargetMapsWhenIteratedOverThenCopyingSuccess(){
+ CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother();
+ Assert.assertEquals(generateExpectedResultMap(), obj.copyByIteration(generateSourceMap(), generateTargetMap()));
+ }
+
+ @Test
+ public void givenSourceAndTargetMapsWhenUsedPutAllThenCopyingSuccess(){
+ CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother();
+ Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingPutAll(generateSourceMap(), generateTargetMap()));
+ }
+
+ @Test
+ public void givenSourceAndTargetMapsWhenUsedPutIfAbsentThenCopyingSuccess(){
+ CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother();
+ Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingPutIfAbsent(generateSourceMap(), generateTargetMap()));
+ Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingPutIfAbsentForEach(generateSourceMap(), generateTargetMap()));
+ }
+
+ @Test
+ public void givenSourceAndTargetMapsWhenUsedMapMergeThenCopyingSuccess(){
+ CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother();
+ Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingMapMerge(generateSourceMap(), generateTargetMap()));
+ }
+
+ @Test
+ public void givenSourceAndTargetMapsWhenMapDifferenceUsedThenCopyingSuccess(){
+ CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother();
+ Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingGuavaMapDifference(generateSourceMap(), generateTargetMap()));
+ }
+
+ private Map generateSourceMap(){
+ Map sourceMap = new HashMap<>();
+ sourceMap.put("India", "Delhi");
+ sourceMap.put("United States", "Washington D.C.");
+ sourceMap.put("United Kingdom", "London DC");
+ return sourceMap;
+ }
+
+ private Map generateTargetMap(){
+ Map targetMap = new HashMap<>();
+ targetMap.put("Zimbabwe", "Harare");
+ targetMap.put("Norway", "Oslo");
+ targetMap.put("United Kingdom", "London");
+ return targetMap;
+ }
+
+ private Map generateExpectedResultMap(){
+ Map resultMap = new HashMap<>();
+ resultMap.put("India", "Delhi");
+ resultMap.put("United States", "Washington D.C.");
+ resultMap.put("United Kingdom", "London");
+ resultMap.put("Zimbabwe", "Harare");
+ resultMap.put("Norway", "Oslo");
+ return resultMap;
+ }
+}
diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java
index ef6b7ee8c8..09dfe575e6 100644
--- a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java
+++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java
@@ -1,7 +1,7 @@
package com.baeldung.concurrent.atomic;
public class SafeCounterWithLock {
- private volatile int counter;
+ private int counter;
int getValue() {
return counter;
diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java
index 8b2aebba7c..e1117dd842 100644
--- a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java
+++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java
@@ -10,12 +10,6 @@ public class SafeCounterWithoutLock {
}
void increment() {
- while(true) {
- int existingValue = getValue();
- int newValue = existingValue + 1;
- if(counter.compareAndSet(existingValue, newValue)) {
- return;
- }
- }
+ counter.incrementAndGet();
}
}
diff --git a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java
index c3c44b40cf..9b4b628d0f 100644
--- a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java
+++ b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java
@@ -17,8 +17,8 @@ public class ThreadSafeCounterIntegrationTest {
SafeCounterWithLock safeCounter = new SafeCounterWithLock();
IntStream.range(0, 1000)
- .forEach(count -> service.submit(safeCounter::increment));
- service.awaitTermination(100, TimeUnit.MILLISECONDS);
+ .forEach(count -> service.execute(safeCounter::increment));
+ shutdownAndAwaitTermination(service);
assertEquals(1000, safeCounter.getValue());
}
@@ -29,10 +29,30 @@ public class ThreadSafeCounterIntegrationTest {
SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock();
IntStream.range(0, 1000)
- .forEach(count -> service.submit(safeCounter::increment));
- service.awaitTermination(100, TimeUnit.MILLISECONDS);
+ .forEach(count -> service.execute(safeCounter::increment));
+ shutdownAndAwaitTermination(service);
assertEquals(1000, safeCounter.getValue());
}
+
+ private void shutdownAndAwaitTermination(ExecutorService pool) {
+ // Disable new tasks from being submitted
+ pool.shutdown();
+ try {
+ // Wait a while for existing tasks to terminate
+ if (!pool.awaitTermination(100, TimeUnit.MILLISECONDS)) {
+ // Cancel currently executing tasks forcefully
+ pool.shutdownNow();
+ // Wait a while for tasks to respond to being cancelled
+ if (!pool.awaitTermination(100, TimeUnit.MILLISECONDS))
+ System.err.println("Pool did not terminate");
+ }
+ } catch (InterruptedException ex) {
+ // (Re-)Cancel if current thread also interrupted
+ pool.shutdownNow();
+ // Preserve interrupt status
+ Thread.currentThread().interrupt();
+ }
+ }
}
diff --git a/core-java-modules/core-java-concurrency-basic-3/pom.xml b/core-java-modules/core-java-concurrency-basic-3/pom.xml
index 7771d1200c..7289877550 100644
--- a/core-java-modules/core-java-concurrency-basic-3/pom.xml
+++ b/core-java-modules/core-java-concurrency-basic-3/pom.xml
@@ -24,4 +24,16 @@
+
+ 4.2.0
+
+
+
+
+ org.awaitility
+ awaitility
+ ${awaitility.version}
+ test
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/RequestProcessor.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/RequestProcessor.java
new file mode 100644
index 0000000000..9557a27f2a
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/RequestProcessor.java
@@ -0,0 +1,35 @@
+package com.baeldung.concurrent;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Random;
+import java.util.UUID;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+public class RequestProcessor {
+
+ private Map requestStatuses = new HashMap<>();
+
+ public String processRequest() {
+ String requestId = UUID.randomUUID().toString();
+ requestStatuses.put(requestId, "PROCESSING");
+
+ ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
+ executorService.schedule((() -> {
+ requestStatuses.put(requestId, "DONE");
+ }), getRandomNumberBetween(500, 2000), TimeUnit.MILLISECONDS);
+
+ return requestId;
+ }
+
+ public String getStatus(String requestId) {
+ return requestStatuses.get(requestId);
+ }
+
+ private int getRandomNumberBetween(int min, int max) {
+ Random random = new Random();
+ return random.nextInt(max - min) + min;
+ }
+}
diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java
new file mode 100644
index 0000000000..c437b08b34
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.concurrent;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.not;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.concurrent.TimeUnit;
+
+import org.awaitility.Awaitility;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+@DisplayName("Request processor")
+public class RequestProcessorUnitTest {
+
+ RequestProcessor requestProcessor = new RequestProcessor();
+
+ @Test
+ @DisplayName("Wait for completion using Thread.sleep")
+ void whenWaitingWithThreadSleep_thenStatusIsDone() throws InterruptedException {
+ String requestId = requestProcessor.processRequest();
+
+ Thread.sleep(2000);
+
+ assertEquals("DONE", requestProcessor.getStatus(requestId));
+ }
+
+ @Test
+ @DisplayName("Wait for completion using Awaitility")
+ void whenWaitingWithAwaitility_thenStatusIsDone() {
+ String requestId = requestProcessor.processRequest();
+
+ Awaitility.await()
+ .atMost(2, TimeUnit.SECONDS)
+ .pollDelay(500, TimeUnit.MILLISECONDS)
+ .until(() -> requestProcessor.getStatus(requestId), not(equalTo("PROCESSING")));
+
+ assertEquals("DONE", requestProcessor.getStatus(requestId));
+ }
+
+}
diff --git a/core-java-modules/core-java-functional/README.md b/core-java-modules/core-java-functional/README.md
index 51185f13a1..addb312542 100644
--- a/core-java-modules/core-java-functional/README.md
+++ b/core-java-modules/core-java-functional/README.md
@@ -2,3 +2,4 @@
- [Functional Programming in Java](https://www.baeldung.com/java-functional-programming)
- [Functors in Java](https://www.baeldung.com/java-functors)
+- [Callback Functions in Java](https://www.baeldung.com/java-callback-functions)
diff --git a/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/AsynchronousCallbackUnitTest.java b/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/AsynchronousCallbackUnitTest.java
index 494d7365d3..de9e386395 100644
--- a/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/AsynchronousCallbackUnitTest.java
+++ b/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/AsynchronousCallbackUnitTest.java
@@ -6,8 +6,7 @@ import com.baeldung.callbackfunctions.EventListener;
import com.baeldung.callbackfunctions.asynchronous.AsynchronousEventConsumer;
import com.baeldung.callbackfunctions.asynchronous.AsynchronousEventListenerImpl;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.*;
public class AsynchronousCallbackUnitTest {
@@ -17,6 +16,6 @@ public class AsynchronousCallbackUnitTest {
AsynchronousEventConsumer asynchronousEventListenerConsumer = new AsynchronousEventConsumer(listener);
asynchronousEventListenerConsumer.doAsynchronousOperation();
- verify(listener, times(1)).onTrigger();
+ verify(listener, timeout(1000).times(1)).onTrigger();
}
}
diff --git a/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/ConsumerCallbackUnitTest.java b/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/ConsumerCallbackUnitTest.java
index ba09a7e50c..9ba5cdb6ef 100644
--- a/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/ConsumerCallbackUnitTest.java
+++ b/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/ConsumerCallbackUnitTest.java
@@ -3,18 +3,25 @@ package com.baeldung.callbackfunctions;
import org.junit.jupiter.api.Test;
import com.baeldung.callbackfunctions.ConsumerCallback;
+import java.util.concurrent.atomic.AtomicInteger;
+
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ConsumerCallbackUnitTest {
@Test
- public void whenIncreasingInitialAgeByGivenValueThroughCallback_shouldIncreaseAge(){
+ void whenIncreasingInitialAgeByGivenValueThroughCallback_shouldIncreaseAge(){
ConsumerCallback consumerCallback = new ConsumerCallback();
- consumerCallback.getAge(20, (initialAge) -> {
- int ageDifference = 10;
+ int ageDifference = 10;
+ AtomicInteger newAge1 = new AtomicInteger();
+ int initialAge = 20;
+ consumerCallback.getAge(initialAge, (initialAge1) -> {
consumerCallback.increaseAge(initialAge, ageDifference, (newAge) -> {
- assertEquals(initialAge + ageDifference, newAge);
+ System.out.printf("New age ==> %s", newAge);
+ newAge1.set(newAge);
+
});
});
+ assertEquals(initialAge + ageDifference, newAge1.get());
}
}
diff --git a/core-java-modules/core-java-hex/README.md b/core-java-modules/core-java-hex/README.md
new file mode 100644
index 0000000000..0ba4d1372f
--- /dev/null
+++ b/core-java-modules/core-java-hex/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Convert Hex to RGB Using Java](https://www.baeldung.com/java-convert-hex-to-rgb)
diff --git a/core-java-modules/core-java-hex/pom.xml b/core-java-modules/core-java-hex/pom.xml
new file mode 100644
index 0000000000..afac1c4d66
--- /dev/null
+++ b/core-java-modules/core-java-hex/pom.xml
@@ -0,0 +1,25 @@
+
+
+ 4.0.0
+ core-java-hex
+ 0.1.0-SNAPSHOT
+ core-java-hex
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-hex/src/test/java/com/baeldung/hextorgb/HexToRgbUnitTest.java b/core-java-modules/core-java-hex/src/test/java/com/baeldung/hextorgb/HexToRgbUnitTest.java
new file mode 100644
index 0000000000..35e5b87d29
--- /dev/null
+++ b/core-java-modules/core-java-hex/src/test/java/com/baeldung/hextorgb/HexToRgbUnitTest.java
@@ -0,0 +1,25 @@
+package com.baeldung.hextorgb;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class HexToRgbUnitTest {
+
+ @Test
+ public void givenHexCode_whenConvertedToRgb_thenCorrectRgbValuesAreReturned() {
+ String hexCode = "FF9933";
+ int red = 255;
+ int green = 153;
+ int blue = 51;
+
+ int resultRed = Integer.valueOf(hexCode.substring(0, 2), 16);
+ int resultGreen = Integer.valueOf(hexCode.substring(2, 4), 16);
+ int resultBlue = Integer.valueOf(hexCode.substring(4, 6), 16);
+
+ assertEquals(red, resultRed);
+ assertEquals(green, resultGreen);
+ assertEquals(blue, resultBlue);
+ }
+
+}
diff --git a/core-java-modules/core-java-httpclient/README.md b/core-java-modules/core-java-httpclient/README.md
index 68f828e81b..5dbb7a08ef 100644
--- a/core-java-modules/core-java-httpclient/README.md
+++ b/core-java-modules/core-java-httpclient/README.md
@@ -5,3 +5,4 @@ This module contains articles about Java HttpClient
### Relevant articles
- [Posting with Java HttpClient](https://www.baeldung.com/java-httpclient-post)
- [Custom HTTP Header With the Java HttpClient](https://www.baeldung.com/java-http-client-custom-header)
+- [Java HttpClient Connection Management](https://www.baeldung.com/java-httpclient-connection-management)
diff --git a/core-java-modules/core-java-httpclient/pom.xml b/core-java-modules/core-java-httpclient/pom.xml
index 57b23e96c1..3df0447ff0 100644
--- a/core-java-modules/core-java-httpclient/pom.xml
+++ b/core-java-modules/core-java-httpclient/pom.xml
@@ -32,6 +32,12 @@
${assertj.version}
test
+
+ com.github.tomakehurst
+ wiremock
+ ${wiremock.version}
+ test
+
@@ -53,6 +59,7 @@
11
3.22.0
5.11.2
+ 2.27.2
\ No newline at end of file
diff --git a/core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/HttpClientConnectionManagementUnitTest.java b/core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/HttpClientConnectionManagementUnitTest.java
new file mode 100644
index 0000000000..3b7610276c
--- /dev/null
+++ b/core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/HttpClientConnectionManagementUnitTest.java
@@ -0,0 +1,147 @@
+package com.baeldung.httpclient.conn;
+
+import com.github.tomakehurst.wiremock.WireMockServer;
+import com.github.tomakehurst.wiremock.client.WireMock;
+import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
+import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.util.List;
+
+import static java.net.URI.create;
+
+
+public class HttpClientConnectionManagementUnitTest {
+
+ WireMockConfiguration firstConfiguration = WireMockConfiguration
+ .options()
+ .dynamicPort();
+ WireMockConfiguration secondConfiguration = WireMockConfiguration
+ .options()
+ .dynamicPort();
+ WireMockServer firstServer = new WireMockServer(firstConfiguration);
+ WireMockServer secondServer = new WireMockServer(secondConfiguration);
+ private String firstUrl;
+ private String secondUrl;
+
+ private HttpClient client = HttpClient.newHttpClient();
+ private HttpClient secondClient = HttpClient.newHttpClient();
+
+ private HttpRequest getRequest;
+ private HttpRequest secondGet;
+
+ @Before
+ public void setup() {
+ firstServer.start();
+ secondServer.start();
+
+ // add some request matchers
+ firstServer.stubFor(WireMock
+ .get(WireMock.anyUrl())
+ .willReturn(WireMock
+ .aResponse()
+ .withStatus(200)));
+ secondServer.stubFor(WireMock
+ .get(WireMock.anyUrl())
+ .willReturn(WireMock
+ .aResponse()
+ .withStatus(200)));
+
+ firstUrl = "http://localhost:" + firstServer.port() + "/first";
+ secondUrl = "http://localhost:" + secondServer.port() + "/second";
+
+ getRequest = HttpRequest
+ .newBuilder()
+ .uri(create(firstUrl))
+ .version(HttpClient.Version.HTTP_1_1)
+ .build();
+
+ secondGet = HttpRequest
+ .newBuilder()
+ .uri(create(secondUrl))
+ .version(HttpClient.Version.HTTP_1_1)
+ .build();
+ }
+
+ @After
+ public void tearDown() {
+ // display all the requests that the WireMock servers handled
+ List firstWiremockAllServeEvents = firstServer.getAllServeEvents();
+ List secondWiremockAllServeEvents = secondServer.getAllServeEvents();
+ firstWiremockAllServeEvents
+ .stream()
+ .map(event -> event
+ .getRequest()
+ .getAbsoluteUrl())
+ .forEach(System.out::println);
+ secondWiremockAllServeEvents
+ .stream()
+ .map(event -> event
+ .getRequest()
+ .getAbsoluteUrl())
+ .forEach(System.out::println);
+
+ // stop the WireMock servers
+ firstServer.stop();
+ secondServer.stop();
+ }
+
+ // Example 1. Use an HttpClient to connect to the same endpoint - reuses a connection from the internal pool
+ @Test
+ public final void givenAnHttpClient_whenTwoConnectionsToSameEndpointMadeSequentially_thenConnectionReused() throws InterruptedException, IOException {
+
+ // given two requests to the same destination
+ final HttpResponse firstResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
+ final HttpResponse secondResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
+
+ assert (firstResponse.statusCode() == 200) && (secondResponse.statusCode() == 200);
+ }
+
+ // Example 2. Use separate HttpClients to connect to the same endpoint - creates a connection per client
+ @Test
+ public final void givenTwoHttpClients_whenEachClientMakesConnectionSequentially_thenConnectionCreatedForEach() throws InterruptedException, IOException {
+
+ // given requests from two different client to same destination
+ final HttpResponse firstResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
+ final HttpResponse secondResponse = secondClient.send(getRequest, HttpResponse.BodyHandlers.ofString());
+
+ assert (firstResponse.statusCode() == 200) && (secondResponse.statusCode() == 200);
+ }
+
+ // Example 3. Use an HttpClient to Connect to first, second, then first endpoint again.
+ // New connections made each time when pool size is 1, or re-used when not restricted.
+ // Make sure to set the JVM arg when running the test:
+ // -Djdk.httpclient.connectionPoolSize=1
+ @Test
+ public final void givenAnHttpClientAndAPoolSizeOfOne_whenTwoConnectionsMadeBackToOriginal_thenFirstConnectionPurged() throws InterruptedException, IOException {
+
+ // given 3 requests, two to the first server and one to the second server
+ final HttpResponse firstResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
+ final HttpResponse secondResponse = client.send(secondGet, HttpResponse.BodyHandlers.ofString());
+ final HttpResponse thirdResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
+
+ assert ((firstResponse.statusCode() == 200) && (secondResponse.statusCode() == 200) && (thirdResponse.statusCode() == 200));
+ }
+
+ // Example 4. Use an HttpClient to connect, wait for connection keepalive to pass, then connect again. New connection made for both calls.
+ // Make sure to set the JVM arg when running the test:
+ // -Djdk.httpclient.keepalive.timeout=2
+ @Test
+ public final void givenAnHttpClientAndConnectionKeepAliveOfTwoSeconds_whenCallMadeAfterKeepaliveExpires_thenNewConnection() throws InterruptedException, IOException {
+
+ // given 2 requests to the same destination with the second call made after the keepalive timeout has passed
+ final HttpResponse firstResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
+ Thread.sleep(3000); // exceeds 2 seconds configured by JVM arg
+ final HttpResponse secondResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
+
+ assert ((firstResponse.statusCode() == 200) && (secondResponse.statusCode() == 200));
+ }
+
+}
+
diff --git a/core-java-modules/core-java-httpclient/src/test/resources/jetty-logging.properties b/core-java-modules/core-java-httpclient/src/test/resources/jetty-logging.properties
new file mode 100644
index 0000000000..a21bdbcd09
--- /dev/null
+++ b/core-java-modules/core-java-httpclient/src/test/resources/jetty-logging.properties
@@ -0,0 +1,3 @@
+org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StrErrLog
+org.eclipse.jetty.LEVEL=DEBUG
+jetty.logs=logs
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-5/README.md b/core-java-modules/core-java-lang-5/README.md
index b8deff199e..5ff3e83d2c 100644
--- a/core-java-modules/core-java-lang-5/README.md
+++ b/core-java-modules/core-java-lang-5/README.md
@@ -14,3 +14,4 @@ This module contains articles about core features in the Java language
- [Convert Between int and char in Java](https://www.baeldung.com/java-convert-int-char)
- [Converting a Number from One Base to Another in Java](https://www.baeldung.com/java-converting-a-number-from-one-base-to-another)
- [Check if Command-Line Arguments Are Null in Java](https://www.baeldung.com/java-check-command-line-args)
+- [Determine if a Class Implements an Interface in Java](https://www.baeldung.com/java-check-class-implements-interface)
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java
new file mode 100644
index 0000000000..24e7d435c7
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java
@@ -0,0 +1,8 @@
+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-lang-oop-constructors/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java b/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java
new file mode 100644
index 0000000000..cd1f48d720
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java
@@ -0,0 +1,17 @@
+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-lang-oop-types-2/README.md b/core-java-modules/core-java-lang-oop-types-2/README.md
index 61b2853af9..ca8742d6c0 100644
--- a/core-java-modules/core-java-lang-oop-types-2/README.md
+++ b/core-java-modules/core-java-lang-oop-types-2/README.md
@@ -8,3 +8,4 @@ This module contains articles about types in Java
- [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-search-enum-values)
- [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value)
- [Filling a List With All Enum Values in Java](https://www.baeldung.com/java-enum-values-to-list)
+- [Comparing a String to an Enum Value in Java](https://www.baeldung.com/java-comparing-string-to-enum)
diff --git a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java
index 0e082b69d3..6ba8ed024c 100644
--- a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java
+++ b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java
@@ -1,55 +1,67 @@
package com.baeldung.keyword;
-import org.junit.Assert;
import org.junit.jupiter.api.Test;
-import com.baeldung.keyword.Circle;
-import com.baeldung.keyword.Ring;
-import com.baeldung.keyword.Round;
-import com.baeldung.keyword.Shape;
-import com.baeldung.keyword.Triangle;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.*;
public class InstanceOfUnitTest {
@Test
- public void giveWhenInstanceIsCorrect_thenReturnTrue() {
+ void giveWhenInstanceIsCorrect_thenReturnTrue() {
Ring ring = new Ring();
- Assert.assertTrue("ring is instance of Round ", ring instanceof Round);
+ assertTrue(ring instanceof Round);
}
@Test
- public void giveWhenObjectIsInstanceOfType_thenReturnTrue() {
+ void giveWhenObjectIsInstanceOfType_thenReturnTrue() {
Circle circle = new Circle();
- Assert.assertTrue("circle is instance of Circle ", circle instanceof Circle);
+ assertTrue(circle instanceof Circle);
}
-
+
@Test
- public void giveWhenInstanceIsOfSubtype_thenReturnTrue() {
+ void giveWhenInstanceIsOfSubtype_thenReturnTrue() {
Circle circle = new Circle();
- Assert.assertTrue("circle is instance of Round", circle instanceof Round);
+ assertTrue(circle instanceof Round);
}
@Test
- public void giveWhenTypeIsInterface_thenReturnTrue() {
+ void giveWhenTypeIsInterface_thenReturnTrue() {
Circle circle = new Circle();
- Assert.assertTrue("circle is instance of Shape", circle instanceof Shape);
+ assertTrue(circle instanceof Shape);
}
-
+
@Test
- public void giveWhenTypeIsOfObjectType_thenReturnTrue() {
+ void giveWhenTypeIsOfObjectType_thenReturnTrue() {
Thread thread = new Thread();
- Assert.assertTrue("thread is instance of Object", thread instanceof Object);
+ assertTrue(thread instanceof Object);
}
@Test
- public void giveWhenInstanceValueIsNull_thenReturnFalse() {
+ void giveWhenInstanceValueIsNull_thenReturnFalse() {
Circle circle = null;
- Assert.assertFalse("circle is instance of Round", circle instanceof Round);
+ assertFalse(circle instanceof Round);
}
@Test
- public void giveWhenComparingClassInDiffHierarchy_thenCompilationError() {
- // Assert.assertFalse("circle is instance of Triangle", circle instanceof Triangle);
+ void giveWhenComparingClassInDiffHierarchy_thenCompilationError() {
+ //assertFalse( circle instanceof Triangle);
}
-}
+
+ @Test
+ void giveWhenStream_whenCastWithoutInstanceOfChk_thenGetException() {
+ Stream roundStream = Stream.of(new Ring(), new Ring(), new Circle());
+ assertThrows(ClassCastException.class, () -> roundStream.map(it -> (Ring) it).collect(Collectors.toList()));
+ }
+
+ @Test
+ void giveWhenStream_whenCastAfterInstanceOfChk_thenGetExpectedResult() {
+ Stream roundStream = Stream.of(new Ring(), new Ring(), new Circle());
+ List ringList = roundStream.filter(it -> it instanceof Ring).map(it -> (Ring) it).collect(Collectors.toList());
+ assertEquals(2, ringList.size());
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-networking-4/README.md b/core-java-modules/core-java-networking-4/README.md
index 5f0958fae0..daec647ebe 100644
--- a/core-java-modules/core-java-networking-4/README.md
+++ b/core-java-modules/core-java-networking-4/README.md
@@ -1,3 +1,4 @@
## Relevant Articles:
- [Difference Between URI.create() and new URI()](https://www.baeldung.com/java-uri-create-and-new-uri)
-- [Validating URL in Java](https://www.baeldung.com/java-validate-url)
\ No newline at end of file
+- [Validating URL in Java](https://www.baeldung.com/java-validate-url)
+- [Validating IPv4 Address in Java](https://www.baeldung.com/java-validate-ipv4-address)
diff --git a/core-java-modules/core-java-networking-4/src/main/java/com/baeldung/urlvalidation/IPv4Validation.java b/core-java-modules/core-java-networking-4/src/main/java/com/baeldung/urlvalidation/IPv4Validation.java
new file mode 100644
index 0000000000..5d72873745
--- /dev/null
+++ b/core-java-modules/core-java-networking-4/src/main/java/com/baeldung/urlvalidation/IPv4Validation.java
@@ -0,0 +1,27 @@
+package com.baeldung.urlvalidation;
+
+import com.google.common.net.InetAddresses;
+import org.apache.commons.validator.routines.InetAddressValidator;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class IPv4Validation {
+
+ public static boolean validateWithApacheCommons(String ip) {
+ InetAddressValidator validator = InetAddressValidator.getInstance();
+ return validator.isValid(ip);
+ }
+
+ public static boolean validateWithGuava(String ip) {
+ return InetAddresses.isInetAddress(ip);
+ }
+
+ public static boolean validateWithRegex(String ip) {
+ String regex = "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$";
+ Pattern pattern = Pattern.compile(regex);
+ Matcher matcher = pattern.matcher(ip);
+ return matcher.matches();
+ }
+
+}
diff --git a/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/ipv4validation/IPv4ValidationUnitTest.java b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/ipv4validation/IPv4ValidationUnitTest.java
new file mode 100644
index 0000000000..367d70117a
--- /dev/null
+++ b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/ipv4validation/IPv4ValidationUnitTest.java
@@ -0,0 +1,121 @@
+package com.baeldung.ipv4validation;
+
+import org.junit.Test;
+
+import static com.baeldung.urlvalidation.IPv4Validation.*;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class IPv4ValidationUnitTest {
+
+ @Test
+ public void givenValidIPv4_whenValidate_thenReturnsTrue() {
+ String ip = "192.168.0.1";
+ assertTrue(validateWithApacheCommons(ip));
+ assertTrue(validateWithGuava(ip));
+ assertTrue(validateWithRegex(ip));
+ }
+
+ @Test
+ public void givenIPv4WithThreeOctets_whenValidate_thenReturnsFalse() {
+ String ip = "192.168.0";
+ assertFalse(validateWithApacheCommons(ip));
+ assertFalse(validateWithGuava(ip));
+ assertFalse(validateWithRegex(ip));
+ }
+
+ @Test
+ public void givenIPv4WithLeadingZero_whenValidate_thenReturnsFalse() {
+ String ip = "192.168.0.01";
+ assertFalse(validateWithApacheCommons(ip));
+ assertFalse(validateWithGuava(ip));
+ assertFalse(validateWithRegex(ip));
+ }
+
+ @Test
+ public void givenIPv4WithInvalidCharacter_whenValidate_thenReturnsFalse() {
+ String ip = "a.168.0.01";
+ assertFalse(validateWithApacheCommons(ip));
+ assertFalse(validateWithGuava(ip));
+ assertFalse(validateWithRegex(ip));
+ }
+
+ @Test
+ public void givenIPv4HaveValueAbove255_whenValidate_thenReturnsFalse() {
+ String ip = "192.168.256.1";
+ assertFalse(validateWithApacheCommons(ip));
+ assertFalse(validateWithGuava(ip));
+ assertFalse(validateWithRegex(ip));
+ }
+
+ @Test
+ public void givenValidIPv4WithTwoDigitOctet_whenValidate_thenReturnsTrue() {
+ String ip = "192.168.42.1";
+ assertTrue(validateWithApacheCommons(ip));
+ assertTrue(validateWithGuava(ip));
+ assertTrue(validateWithRegex(ip));
+ }
+ @Test
+ public void givenValidIPv4WithNumberInRange200And249_whenValidate_thenReturnsTrue() {
+ String ip = "192.168.42.222";
+ assertTrue(validateWithApacheCommons(ip));
+ assertTrue(validateWithGuava(ip));
+ assertTrue(validateWithRegex(ip));
+ }
+
+ @Test
+ public void givenIPv4WithFourDigitOctet_whenValidate_thenReturnsFalse() {
+ String ip = "1921.168.42.222";
+ assertFalse(validateWithApacheCommons(ip));
+ assertFalse(validateWithGuava(ip));
+ assertFalse(validateWithRegex(ip));
+ }
+
+ @Test
+ public void givenIPv4WithFiveOctets_whenValidate_thenReturnsFalse() {
+ String ip = "192.168.42.222.10";
+ assertFalse(validateWithApacheCommons(ip));
+ assertFalse(validateWithGuava(ip));
+ assertFalse(validateWithRegex(ip));
+ }
+
+ @Test
+ public void givenIPv4WithTwoConsecutiveDots_whenValidate_thenReturnsFalse() {
+ String ip = "192.168..1";
+ assertFalse(validateWithApacheCommons(ip));
+ assertFalse(validateWithGuava(ip));
+ assertFalse(validateWithRegex(ip));
+ }
+
+ @Test
+ public void givenOnlyDots_whenValidate_thenReturnsFalse() {
+ String ip = "...";
+ assertFalse(validateWithApacheCommons(ip));
+ assertFalse(validateWithGuava(ip));
+ assertFalse(validateWithRegex(ip));
+ }
+
+ @Test
+ public void givenBlankString_whenValidate_thenReturnsFalse() {
+ String ip = " ";
+ assertFalse(validateWithApacheCommons(ip));
+ assertFalse(validateWithGuava(ip));
+ assertFalse(validateWithRegex(ip));
+ }
+
+ @Test
+ public void givenIPv4StartWithDot_whenValidate_thenReturnsFalse() {
+ String ip = ".192.168.0.1";
+ assertFalse(validateWithApacheCommons(ip));
+ assertFalse(validateWithGuava(ip));
+ assertFalse(validateWithRegex(ip));
+ }
+ @Test
+ public void givenIPv4EndWithDot_whenValidate_thenReturnsFalse() {
+ String ip = "192.168.0.1.";
+ assertFalse(validateWithApacheCommons(ip));
+ assertFalse(validateWithGuava(ip));
+ assertFalse(validateWithRegex(ip));
+ }
+
+}
diff --git a/core-java-modules/core-java-numbers-5/README.md b/core-java-modules/core-java-numbers-5/README.md
index 7a010e2fbf..fcc3d55dd9 100644
--- a/core-java-modules/core-java-numbers-5/README.md
+++ b/core-java-modules/core-java-numbers-5/README.md
@@ -7,3 +7,5 @@
- [Make Division of Two Integers Result in a Float](https://www.baeldung.com/java-integer-division-float-result)
- [Creating Random Numbers With No Duplicates in Java](https://www.baeldung.com/java-unique-random-numbers)
- [Multiply a BigDecimal by an Integer in Java](https://www.baeldung.com/java-bigdecimal-multiply-integer)
+- [Check if an Integer Value is null or Zero in Java](https://www.baeldung.com/java-check-integer-null-or-zero)
+- [Return Absolute Difference of Two Integers in Java](https://www.baeldung.com/java-absolute-difference-of-two-integers)
diff --git a/core-java-modules/core-java-numbers-5/src/test/java/com/baeldung/absintdiff/AbsoluteDifferenceOfTwoIntUnitTest.java b/core-java-modules/core-java-numbers-5/src/test/java/com/baeldung/absintdiff/AbsoluteDifferenceOfTwoIntUnitTest.java
new file mode 100644
index 0000000000..eec3924202
--- /dev/null
+++ b/core-java-modules/core-java-numbers-5/src/test/java/com/baeldung/absintdiff/AbsoluteDifferenceOfTwoIntUnitTest.java
@@ -0,0 +1,58 @@
+package com.baeldung.absintdiff;
+
+import static com.baeldung.absintdiff.IntDiffUtil.absDiff;
+import static com.baeldung.absintdiff.IntDiffUtil.absDiff2;
+import static com.baeldung.absintdiff.IntDiffUtil.absDiffAsLong;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import org.junit.jupiter.api.Test;
+
+class IntDiffUtil {
+ static int absDiff(int num1, int num2) {
+ int result = Math.abs(num1 - num2);
+ System.out.println("Absolute diff: " + result);
+ return result;
+ }
+
+ static int absDiff2(int num1, int num2) {
+ return Math.abs(Math.subtractExact(num1, num2));
+ }
+
+ static long absDiffAsLong(int num1, int num2) {
+ return Math.abs((long) num1 - num2);
+ }
+}
+
+public class AbsoluteDifferenceOfTwoIntUnitTest {
+
+ @Test
+ void givenTwoIntegers_whenCallingAbsDiff_shouldGetExpectedResult() {
+ int diff1 = absDiff(100, -200);
+ assertEquals(300, diff1);
+
+ int diff2 = absDiff(100, 200);
+ assertEquals(100, diff2);
+
+ //integer overflow! output: Absolute diff: 2147483449
+ //absDiff(Integer.MAX_VALUE, -200);
+ }
+
+ @Test
+ void givenTwoIntegers_whenCallingAbsDiff2_shouldThrowException() {
+ int diff1 = absDiff2(100, -200);
+ assertEquals(300, diff1);
+
+ int diff2 = absDiff2(100, 200);
+ assertEquals(100, diff2);
+
+ //overflow -> exception
+ assertThrows(ArithmeticException.class, () -> absDiff2(Integer.MAX_VALUE, -200));
+ }
+
+ @Test
+ void givenTwoIntegers_whenCallingAbsDiffAsLong_shouldThrowException() {
+ long diff = absDiffAsLong(Integer.MAX_VALUE, -200);
+ assertEquals(Integer.MAX_VALUE + 200L, diff);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-security-3/src/main/java/com/baeldung/crypto/exception/BadPaddingExamples.java b/core-java-modules/core-java-security-3/src/main/java/com/baeldung/crypto/exception/BadPaddingExamples.java
index 3fff4410e3..135510785f 100644
--- a/core-java-modules/core-java-security-3/src/main/java/com/baeldung/crypto/exception/BadPaddingExamples.java
+++ b/core-java-modules/core-java-security-3/src/main/java/com/baeldung/crypto/exception/BadPaddingExamples.java
@@ -16,7 +16,7 @@ public class BadPaddingExamples {
SecretKey encryptionKey = CryptoUtils.getKeyForText("BaeldungIsASuperCoolSite");
SecretKey differentKey = CryptoUtils.getKeyForText("ThisGivesUsAnAlternative");
- Cipher cipher = Cipher.getInstance("AES/ECB/ISO10126Padding");
+ Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
byte[] cipherTextBytes = cipher.doFinal(plainTextBytes);
@@ -28,12 +28,12 @@ public class BadPaddingExamples {
public static byte[] encryptAndDecryptUsingDifferentAlgorithms(SecretKey key, IvParameterSpec ivParameterSpec,
byte[] plainTextBytes) throws InvalidKeyException, GeneralSecurityException {
- Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
+ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
byte[] cipherTextBytes = cipher.doFinal(plainTextBytes);
- cipher = Cipher.getInstance("AES/ECB/ISO10126Padding");
+ cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
diff --git a/core-java-modules/core-java-streams-4/README.md b/core-java-modules/core-java-streams-4/README.md
index b210c2775a..67b16ac153 100644
--- a/core-java-modules/core-java-streams-4/README.md
+++ b/core-java-modules/core-java-streams-4/README.md
@@ -6,3 +6,6 @@
- [Java 8 Streams: Multiple Filters vs. Complex Condition](https://www.baeldung.com/java-streams-multiple-filters-vs-condition)
- [Finding Max Date in List Using Streams](https://www.baeldung.com/java-max-date-list-streams)
- [Batch Processing of Stream Data in Java](https://www.baeldung.com/java-stream-batch-processing)
+- [Stream to Iterable in Java](https://www.baeldung.com/java-stream-to-iterable)
+- [Understanding the Difference Between Stream.of() and IntStream.range()](https://www.baeldung.com/java-stream-of-and-intstream-range)
+- [Check if Object Is an Array in Java](https://www.baeldung.com/java-check-if-object-is-an-array)
diff --git a/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/intarraytostrings/ArrayConversionUtils.java b/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/intarraytostrings/ArrayConversionUtils.java
new file mode 100644
index 0000000000..3bb58b43d2
--- /dev/null
+++ b/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/intarraytostrings/ArrayConversionUtils.java
@@ -0,0 +1,43 @@
+package com.baeldung.streams.intarraytostrings;
+
+import java.util.Arrays;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+public class ArrayConversionUtils {
+
+ public static void createStreamExample() {
+ int[] intArray = { 1, 2, 3, 4, 5 };
+ IntStream intStream = Arrays.stream(intArray);
+
+ Integer[] integerArray = { 1, 2, 3, 4, 5 };
+ Stream integerStream = Arrays.stream(integerArray);
+ }
+
+ public static String[] convertToStringArray(Integer[] input) {
+ return Arrays.stream(input)
+ .map(Object::toString)
+ .toArray(String[]::new);
+ }
+
+ public static String[] convertToStringArray(int[] input) {
+ return Arrays.stream(input)
+ .mapToObj(Integer::toString)
+ .toArray(String[]::new);
+ }
+
+ public static String[] convertToStringArrayWithBoxing(int[] input) {
+ return Arrays.stream(input)
+ .boxed()
+ .map(Object::toString)
+ .toArray(String[]::new);
+ }
+
+ public static String convertToString(int[] input){
+ return Arrays.stream(input)
+ .mapToObj(Integer::toString)
+ .collect(Collectors.joining(", "));
+ }
+
+}
diff --git a/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/intarraytostrings/IntArrayToStringUnitTest.java b/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/intarraytostrings/IntArrayToStringUnitTest.java
new file mode 100644
index 0000000000..3f6fb0be8e
--- /dev/null
+++ b/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/intarraytostrings/IntArrayToStringUnitTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.streams.intarraytostrings;
+
+import static com.baeldung.streams.intarraytostrings.ArrayConversionUtils.convertToString;
+import static com.baeldung.streams.intarraytostrings.ArrayConversionUtils.convertToStringArray;
+import static com.baeldung.streams.intarraytostrings.ArrayConversionUtils.convertToStringArrayWithBoxing;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class IntArrayToStringUnitTest {
+
+ @Test
+ public void whenConvertingIntegers_thenHandleStreamOfIntegers() {
+ Integer[] integerNumbers = { 1, 2, 3, 4, 5 };
+ String[] expectedOutput = { "1", "2", "3", "4", "5" };
+
+ String[] strings = convertToStringArray(integerNumbers);
+
+ Assert.assertArrayEquals(expectedOutput, strings);
+ }
+
+ @Test
+ public void whenConvertingInts_thenHandleIntStream() {
+ int[] intNumbers = { 1, 2, 3, 4, 5 };
+ String[] expectedOutput = { "1", "2", "3", "4", "5" };
+
+ String[] strings = convertToStringArray(intNumbers);
+
+ Assert.assertArrayEquals(expectedOutput, strings);
+ }
+
+ @Test
+ public void givenAnIntArray_whenBoxingToInteger_thenHandleStreamOfIntegers() {
+ int[] intNumbers = { 1, 2, 3, 4, 5 };
+ String[] expectedOutput = { "1", "2", "3", "4", "5" };
+
+ String[] strings = convertToStringArrayWithBoxing(intNumbers);
+
+ Assert.assertArrayEquals(expectedOutput, strings);
+ }
+
+ @Test
+ public void givenAnIntArray_whenUsingCollectorsJoining_thenReturnCommaSeparatedString(){
+ int[] intNumbers = { 1, 2, 3, 4, 5 };
+ String expectedOutput = "1, 2, 3, 4, 5";
+
+ String string = convertToString(intNumbers);
+
+ Assert.assertEquals(expectedOutput, string);
+ }
+
+}
diff --git a/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/streamofvsintstream/DiffBetweenStreamOfAndIntStreamRangeUnitTest.java b/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/streamofvsintstream/DiffBetweenStreamOfAndIntStreamRangeUnitTest.java
new file mode 100644
index 0000000000..23957fe2c6
--- /dev/null
+++ b/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/streamofvsintstream/DiffBetweenStreamOfAndIntStreamRangeUnitTest.java
@@ -0,0 +1,66 @@
+package com.baeldung.streams.streamofvsintstream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.TreeSet;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.Test;
+
+public class DiffBetweenStreamOfAndIntStreamRangeUnitTest {
+ @Test
+ void givenStreamOfAndIntStreamRange_whenPeekSortAndFirst_shouldResultDifferent() {
+ Stream normalStream = Stream.of(1, 2, 3, 4, 5);
+ IntStream intStreamByRange = IntStream.range(1, 6);
+ List normalStreamPeekResult = new ArrayList<>();
+ List intStreamPeekResult = new ArrayList<>();
+
+ // First, the regular Stream
+ normalStream.peek(normalStreamPeekResult::add)
+ .sorted()
+ .findFirst();
+ assertEquals(Arrays.asList(1, 2, 3, 4, 5), normalStreamPeekResult);
+
+ // Then, the IntStream
+ intStreamByRange.peek(intStreamPeekResult::add)
+ .sorted()
+ .findFirst();
+ assertEquals(Arrays.asList(1), intStreamPeekResult);
+ }
+
+ @Test
+ void givenStream_whenPeekAndFirst_shouldHaveOnlyFirstElement() {
+ Stream normalStream = Stream.of(1, 2, 3, 4, 5);
+ IntStream intStreamByRange = IntStream.range(1, 6);
+ List normalStreamPeekResult = new ArrayList<>();
+ List intStreamPeekResult = new ArrayList<>();
+
+ // First, the regular Stream
+ normalStream.peek(normalStreamPeekResult::add)
+ .findFirst();
+ assertEquals(Arrays.asList(1), normalStreamPeekResult);
+
+ // Then, the IntStream
+ intStreamByRange.peek(intStreamPeekResult::add)
+ .findFirst();
+ assertEquals(Arrays.asList(1), intStreamPeekResult);
+ }
+
+ @Test
+ void givenSortedStream_whenPeekSortAndFirst_shouldOnlyHaveOneElement() {
+ List peekResult = new ArrayList<>();
+
+ TreeSet treeSet = new TreeSet<>(Arrays.asList("CCC", "BBB", "AAA", "DDD", "KKK"));
+
+ treeSet.stream()
+ .peek(peekResult::add)
+ .sorted()
+ .findFirst();
+
+ assertEquals(Arrays.asList("AAA"), peekResult);
+ }
+}
\ No newline at end of file
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 622730c834..d2863be8e5 100644
--- a/core-java-modules/core-java-string-algorithms-3/README.md
+++ b/core-java-modules/core-java-string-algorithms-3/README.md
@@ -9,3 +9,4 @@ This module contains articles about string-related algorithms.
- [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)
+- [Find the First Embedded Occurrence of an Integer in a Java String](https://www.baeldung.com/java-string-find-embedded-integer)
diff --git a/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnInteger.java b/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnInteger.java
new file mode 100644
index 0000000000..ca86208e59
--- /dev/null
+++ b/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnInteger.java
@@ -0,0 +1,18 @@
+package com.baeldung.firstocurrenceofaninteger;
+
+public class FirstOccurrenceOfAnInteger {
+
+ static Integer findFirstInteger(String s) {
+ int i = 0;
+ while (i < s.length() && !Character.isDigit(s.charAt(i))) {
+ i++;
+ }
+ int j = i;
+ while (j < s.length() && Character.isDigit(s.charAt(j))) {
+ j++;
+ }
+ return Integer.parseInt(s.substring(i, j));
+ }
+
+}
+
diff --git a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnIntegerUnitTest.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnIntegerUnitTest.java
new file mode 100644
index 0000000000..ab40316708
--- /dev/null
+++ b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnIntegerUnitTest.java
@@ -0,0 +1,46 @@
+package com.baeldung.firstocurrenceofaninteger;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Scanner;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+class FirstOccurrenceOfAnIntegerUnitTest {
+
+ @Test
+ void whenUsingPatternMatcher_findFirstInteger() {
+ String s = "ba31dung123";
+ Matcher matcher = Pattern.compile("\\d+").matcher(s);
+ matcher.find();
+ int i = Integer.parseInt(matcher.group());
+ Assertions.assertEquals(31, i);
+ }
+
+ @Test
+ void whenUsingScanner_findFirstInteger() {
+ int i = new Scanner("ba31dung123").useDelimiter("\\D+").nextInt();
+ Assertions.assertEquals(31, i);
+ }
+
+ @Test
+ void whenUsingSplit_findFirstInteger() {
+ String str = "ba31dung123";
+ List tokens = Arrays.stream(str.split("\\D+"))
+ .filter(s -> s.length() > 0).collect(Collectors.toList());
+ Assertions.assertEquals(31, Integer.parseInt(tokens.get(0)));
+ }
+
+ @Test
+ void whenUsingCustomMethod_findFirstInteger() {
+ String str = "ba31dung123";
+ Integer i = FirstOccurrenceOfAnInteger.findFirstInteger(str);
+ Assertions.assertEquals(31, i);
+ }
+
+
+}
diff --git a/core-java-modules/core-java-time-measurements/src/main/java/com/baeldung/timer/NewsletterTask.java b/core-java-modules/core-java-time-measurements/src/main/java/com/baeldung/timer/NewsletterTask.java
index 16dd6c12ff..d99f7acea7 100644
--- a/core-java-modules/core-java-time-measurements/src/main/java/com/baeldung/timer/NewsletterTask.java
+++ b/core-java-modules/core-java-time-measurements/src/main/java/com/baeldung/timer/NewsletterTask.java
@@ -3,12 +3,24 @@ package com.baeldung.timer;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
+import java.util.Random;
import java.util.TimerTask;
+import java.util.concurrent.TimeUnit;
public class NewsletterTask extends TimerTask {
@Override
public void run() {
System.out.println("Email sent at: "
+ LocalDateTime.ofInstant(Instant.ofEpochMilli(scheduledExecutionTime()), ZoneId.systemDefault()));
+ Random random = new Random();
+ int value = random.ints(1, 7)
+ .findFirst()
+ .getAsInt();
+ System.out.println("The duration of sending the mail will took: " + value);
+ try {
+ TimeUnit.SECONDS.sleep(value);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
}
}
diff --git a/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitManualTest.java
similarity index 76%
rename from core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java
rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitManualTest.java
index ffbe39c2bc..049fc3bf6d 100644
--- a/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java
+++ b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitManualTest.java
@@ -5,7 +5,7 @@ import org.junit.jupiter.api.Test;
import java.util.Timer;
-class NewsletterTaskUnitTest {
+class NewsletterTaskUnitManualTest {
private final Timer timer = new Timer();
@AfterEach
@@ -17,17 +17,13 @@ class NewsletterTaskUnitTest {
void givenNewsletterTask_whenTimerScheduledEachSecondFixedDelay_thenNewsletterSentEachSecond() throws Exception {
timer.schedule(new NewsletterTask(), 0, 1000);
- for (int i = 0; i < 3; i++) {
- Thread.sleep(1000);
- }
+ Thread.sleep(20000);
}
@Test
void givenNewsletterTask_whenTimerScheduledEachSecondFixedRate_thenNewsletterSentEachSecond() throws Exception {
timer.scheduleAtFixedRate(new NewsletterTask(), 0, 1000);
- for (int i = 0; i < 3; i++) {
- Thread.sleep(1000);
- }
+ Thread.sleep(20000);
}
}
\ No newline at end of file
diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md
index 0000962164..6d9bbe03c2 100644
--- a/core-java-modules/core-java/README.md
+++ b/core-java-modules/core-java/README.md
@@ -10,3 +10,4 @@
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
- [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error)
- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)
+- [Difference Between Class.forName() and Class.forName().newInstance()](https://www.baeldung.com/java-class-forname-vs-class-forname-newinstance)
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java b/core-java-modules/core-java/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java
index a58dbf9864..1ea85942ee 100644
--- a/core-java-modules/core-java/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java
+++ b/core-java-modules/core-java/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java
@@ -9,5 +9,6 @@ public class AnonymousClassExample{
System.out.println("Thread: "+Thread.currentThread().getName()+" started");
}
});
+ t1.start();
}
}
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/loadclass/MyClassForLoad.java b/core-java-modules/core-java/src/main/java/com/baeldung/loadclass/MyClassForLoad.java
new file mode 100644
index 0000000000..e97848fb1f
--- /dev/null
+++ b/core-java-modules/core-java/src/main/java/com/baeldung/loadclass/MyClassForLoad.java
@@ -0,0 +1,8 @@
+package com.baeldung.loadclass;
+
+
+public class MyClassForLoad {
+
+ private String data = "some data";
+
+}
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/loadclass/LoadClassUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/loadclass/LoadClassUnitTest.java
new file mode 100644
index 0000000000..1f7eb139a2
--- /dev/null
+++ b/core-java-modules/core-java/src/test/java/com/baeldung/loadclass/LoadClassUnitTest.java
@@ -0,0 +1,30 @@
+package com.baeldung.loadclass;
+
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.InvocationTargetException;
+
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+
+
+public class LoadClassUnitTest {
+
+ @Test
+ public void whenUseClassForName_createdInstanceOfClassClass() throws ClassNotFoundException {
+ Class instance = Class.forName("com.baeldung.loadclass.MyClassForLoad");
+ assertInstanceOf(Class.class, instance, "instance should be of Class.class");
+ }
+
+ @Test
+ public void whenUseClassForNameWithNewInstance_createdInstanceOfTargetClas() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
+ Object instance = Class.forName("com.baeldung.loadclass.MyClassForLoad").newInstance();
+ assertInstanceOf(MyClassForLoad.class, instance, "instance should be of MyClassForLoad class");
+ }
+
+ @Test
+ public void whenUseClassForNameWithDeclaredConstructor_newInstanceCreatedInstanceOfTargetClas() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
+ Object instance = Class.forName("com.baeldung.loadclass.MyClassForLoad").getDeclaredConstructor().newInstance();
+ assertInstanceOf(MyClassForLoad.class, instance, "instance should be of MyClassForLoad class");
+ }
+
+}
diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml
index bbbca6adf5..1033213cd1 100644
--- a/core-java-modules/pom.xml
+++ b/core-java-modules/pom.xml
@@ -62,6 +62,7 @@
core-java-exceptions-4
core-java-function
core-java-functional
+ core-java-hex
core-java-io
core-java-io-2
core-java-io-3
@@ -131,6 +132,7 @@
core-java-regex-2
core-java-uuid
pre-jpms
+ core-java-collections-maps-6
diff --git a/ddd/pom.xml b/ddd/pom.xml
index 3beb43bb35..6128bb1cd9 100644
--- a/ddd/pom.xml
+++ b/ddd/pom.xml
@@ -59,8 +59,8 @@
runtime
- mysql
- mysql-connector-java
+ com.mysql
+ mysql-connector-j
runtime
diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml
index c63e67d573..01bac93214 100644
--- a/deeplearning4j/pom.xml
+++ b/deeplearning4j/pom.xml
@@ -57,11 +57,20 @@
httpclient
${httpclient.version}
+
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+ provided
+
+
0.9.1
4.3.5
+ 1.18.20
\ No newline at end of file
diff --git a/di-modules/guice/pom.xml b/di-modules/guice/pom.xml
index cbadf2119d..a28dbe5297 100644
--- a/di-modules/guice/pom.xml
+++ b/di-modules/guice/pom.xml
@@ -23,7 +23,7 @@
- 4.1.0
+ 5.0.1
\ No newline at end of file
diff --git a/discord4j/pom.xml b/discord4j/pom.xml
index e15bd47583..3ea85c05c7 100644
--- a/discord4j/pom.xml
+++ b/discord4j/pom.xml
@@ -53,19 +53,10 @@
org.springframework.boot
spring-boot-maven-plugin
-
- org.apache.maven.plugins
- maven-compiler-plugin
-
- 1.8
- 1.8
-
-
- 1.8
3.1.1
diff --git a/docker-modules/docker-compose-2/README.md b/docker-modules/docker-compose-2/README.md
index 729105e3fd..353b85f154 100644
--- a/docker-modules/docker-compose-2/README.md
+++ b/docker-modules/docker-compose-2/README.md
@@ -1 +1,2 @@
## Relevant Articles:
+- [Communicating With Docker Containers on the Same Machine](https://www.baeldung.com/ops/docker-communicating-with-containers-on-same-machine)
diff --git a/feign/pom.xml b/feign/pom.xml
index 369fa00137..3ac816fc1d 100644
--- a/feign/pom.xml
+++ b/feign/pom.xml
@@ -116,7 +116,6 @@
- 1.8
11.8
1.6.3
diff --git a/gcp-firebase/src/main/resources/application.properties b/gcp-firebase/src/main/resources/application.properties
index aacbde0d92..494aeb2444 100644
--- a/gcp-firebase/src/main/resources/application.properties
+++ b/gcp-firebase/src/main/resources/application.properties
@@ -1,2 +1,2 @@
-# Service account location. Can be a filesystem path or a classpath resource
-gcp.firebase.service-account=file:firebase-service-account.json
\ No newline at end of file
+# Service account location. Can be a filesystem path or a classpath resource. NB: Generate and use your own firebase-service-account.json file.
+gcp.firebase.service-account=classpath:firebase-service-account.json
\ No newline at end of file
diff --git a/gcp-firebase/src/main/resources/firebase-service-account.json b/gcp-firebase/src/main/resources/firebase-service-account.json
new file mode 100644
index 0000000000..ed5afa9f13
--- /dev/null
+++ b/gcp-firebase/src/main/resources/firebase-service-account.json
@@ -0,0 +1,12 @@
+{
+ "type": "service_account",
+ "project_id": "tutorials-2cdfb",
+ "private_key_id": "d9f6a684d6814f85ed2d0490585eb7bf590f983a",
+ "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDdJWTeGT2eBFo+\nXxzT9xFJYPtyawTAj0K1rVUNlWNUwj3zszK6P2sAsrpI2Rz1klwQ9aDz9i3+Opxv\n7UZ3pOzur6S58JnoswtNs6BZ9P7oeggLJJC6MPjioxwh8jLLIGMgdVtC2/iPYW3r\nGzurWlwkM8M8DyCgNq7KKJcx44pGcyy16ZGCYiijuTEmK6R+WHJTTyICzRFu3Org\nuHGlZUs/G4E76p10HanoFX2AIS/fDEEMP2DXBB73yoCal5GuvMY9yZWxnvV65Y5z\nGveY3NDB9EESbO2AAhDvHekWT17uWhymtO5N3gM8da48J9d51tVzi0D/NIPZnF0u\nTS64uxK3AgMBAAECggEAYuEQa7oPcfLyQscWRbRH1250n2E4e7zSkBcTW4J7Km+7\ncZajTOGEP4iqgF4Lc8XgQnkBYXOmdvDP97+47VAh3EtOtRDeUEyV9kUlonNH8rx1\nkj3kNEwnTHav4oG/slEl4WJ3zro6NinTEvdXQ7OgVVOLrPP6m4g3uQ5TJCxgLEUI\nTd3Hs3cg3P71mzEqfBF4NmGVmC1ea5lXFELd6giJJMvL7g+O2w22/fquGWOrreAM\ncj/G2Xv9/vmzeb9yzbgGxqCJyY6vspmd90fQLUu7bxkEY5/PPc6Zk8qay4AdEn47\nkL6hnJiR8H1wMCzV2RTUKE7ospriNVdBilXgxm9IMQKBgQD1TmF0Bg85zvXmEKBa\nLBhbc3xTtM7DOgKs+pI12sYDKwgL/QKEI/TKkYXua0aVGiQWc2Bk2/0sYhO6aB2f\n6AN1ZUrf4PRM8c53jebChc7beVLSjWI8Tx+kE+0t8864OwvELYZUzP35oSx3RdJD\nE/CvqBM7NQfJwx2Mw2VJK/YRGQKBgQDmyWLm/IWitehkITw6xMQpkkFs2m4Joq3A\nJvAyri58TRkw/7rqWaIxb5Wcy/7BOvjDN8PZNTHh4ZvhQiHpn7NGUks2/ULnWxUB\nWAA9YbeO9PNHJfZ6PjD2FSvwOXHj+vVkWt2GCXT8pDGYM2ImqXon85Oe3OH/h+N5\nktO9taesTwKBgQCSdPGKK/P7N61oZpTWQW1pbFHWSCUKOiBO1mtk6/E9AvwS7EQM\nUMteBfRInJPPgYP6Q3hRv2YwkX3l1TOavRMTjB5f/BbfuZ7jkj0r9mfCcXUZcIAu\nMa9abus0fFP3eolT3zpMdvdLiwbZTz5x/f29YkPZHZhAxdVmrWJThYOsQQKBgBDu\nZVsc25D8V3hBF/IXzWxfVn1t6PS8ApM+SBDvxmlIHrkBiez3dna6APfn32C9utJX\nnP6qcGZp7s2v1F0XYkeecfYuzmG6xOe8VQgryxOp1M87ccG2HlFvbDHLhRd8qdQa\n9nWG7BY81Yac/m5nsJaNwB6/hbUBeybIJtCcKxjxAoGBAJ3y+QSFb4AYmxLFtmMA\nklOvlT+r70w4RV/z4SEO1gjWEh9IozNSXknl5Q/8Zh9IVm3+/qYap//IzEv9JUc3\nv4+HlpZu0trxTpvRWWjPqVr3ssxRdiFLC0LCLEk4rzqWLBVyzJm8uHVIF9Inv8PE\naudInvdbnfAWi60+1Wi8u0Co\n-----END PRIVATE KEY-----\n",
+ "client_email": "firebase-adminsdk-2afzd@tutorials-2cdfb.iam.gserviceaccount.com",
+ "client_id": "111111112074248894669",
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-2afzd%40tutorials-2cdfb.iam.gserviceaccount.com"
+}
diff --git a/geotools/pom.xml b/geotools/pom.xml
index 05cae922a4..6edb344c8c 100644
--- a/geotools/pom.xml
+++ b/geotools/pom.xml
@@ -39,12 +39,19 @@
gt-swing
${geotools-swing.version}
+
+ org.locationtech.jts
+ jts-core
+ 1.19.0
+
+
+
- 15.2
- 15.2
- 15.2
+ 28.1
+ 28.1
+ 28.1
\ No newline at end of file
diff --git a/geotools/src/main/java/com/baeldung/geotools/ShapeFile.java b/geotools/src/main/java/com/baeldung/geotools/ShapeFile.java
index de789918cd..64650fb486 100644
--- a/geotools/src/main/java/com/baeldung/geotools/ShapeFile.java
+++ b/geotools/src/main/java/com/baeldung/geotools/ShapeFile.java
@@ -1,8 +1,8 @@
package com.baeldung.geotools;
-import com.vividsolutions.jts.geom.Coordinate;
-import com.vividsolutions.jts.geom.GeometryFactory;
-import com.vividsolutions.jts.geom.Point;
+import org.locationtech.jts.geom.Coordinate;
+import org.locationtech.jts.geom.GeometryFactory;
+import org.locationtech.jts.geom.Point;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
@@ -35,7 +35,7 @@ public class ShapeFile {
DefaultFeatureCollection collection = new DefaultFeatureCollection();
- GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
+ GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
SimpleFeatureType TYPE = DataUtilities.createType("Location", "location:Point:srid=4326," + "name:String");
diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml
index c39983564f..eea056477c 100644
--- a/httpclient-simple/pom.xml
+++ b/httpclient-simple/pom.xml
@@ -1,7 +1,7 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
httpclient-simple
0.1-SNAPSHOT
@@ -10,90 +10,61 @@
com.baeldung
- parent-spring-5
+ parent-boot-3
0.0.1-SNAPSHOT
- ../parent-spring-5
+ ../parent-boot-3
-
- org.springframework.security
- spring-security-web
- ${spring-security.version}
+ org.springframework.boot
+ spring-boot-starter
- org.springframework.security
- spring-security-config
- ${spring-security.version}
-
-
-
- org.springframework
- spring-core
- ${spring.version}
-
-
- commons-logging
- commons-logging
-
-
+ org.springframework.boot
+ spring-boot-starter-security
- org.springframework
- spring-context
- ${spring.version}
+ org.springframework.boot
+ spring-boot-starter-jdbc
- org.springframework
- spring-jdbc
- ${spring.version}
+ org.springframework.boot
+ spring-boot-starter-aop
- org.springframework
- spring-beans
- ${spring.version}
+ org.springframework.boot
+ spring-boot-starter-web
- org.springframework
- spring-aop
- ${spring.version}
+ jakarta.xml.bind
+ jakarta.xml.bind-api
+ 4.0.0
- org.springframework
- spring-tx
- ${spring.version}
-
-
- org.springframework
- spring-expression
- ${spring.version}
-
-
- org.springframework
- spring-web
- ${spring.version}
-
-
- org.springframework
- spring-webmvc
- ${spring.version}
-
-
- org.springframework
- spring-oxm
- ${spring.version}
+ com.sun.xml.bind
+ jaxb-impl
+ 4.0.0
+ runtime
+
com.fasterxml.jackson.core
jackson-databind
${jackson.version}
+
- org.apache.httpcomponents
- httpcore
- ${httpcore.version}
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+
+ org.apache.httpcomponents.client5
+ httpclient5
+ ${httpclient5.version}
commons-logging
@@ -112,7 +83,6 @@
-
org.apache.httpcomponents.client5
httpclient5-fluent
@@ -124,67 +94,11 @@
-
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
-
-
-
- org.apache.httpcomponents
- httpclient
- ${httpclient.version}
-
-
- commons-logging
- commons-logging
-
-
-
-
- org.apache.httpcomponents
- fluent-hc
- ${httpclient.version}
-
-
- commons-logging
- commons-logging
-
-
-
-
- org.apache.httpcomponents.client5
- httpclient5
- ${httpclient5.version}
-
-
- commons-logging
- commons-logging
-
-
-
-
- org.apache.httpcomponents
- httpmime
- ${httpclient.version}
-
commons-codec
commons-codec
${commons-codec.version}
-
- org.apache.httpcomponents
- httpasyncclient
- ${httpasyncclient.version}
-
-
- commons-logging
- commons-logging
-
-
-
com.github.tomakehurst
wiremock
@@ -210,13 +124,6 @@
guava
${guava.version}
-
-
- org.springframework
- spring-test
- ${spring.version}
- test
-
@@ -231,26 +138,13 @@
org.apache.maven.plugins
maven-war-plugin
- ${maven-war-plugin.version}
+ 3.3.2
- org.codehaus.cargo
- cargo-maven2-plugin
- ${cargo-maven2-plugin.version}
+ org.springframework.boot
+ spring-boot-maven-plugin
- true
-
- jetty8x
- embedded
-
-
-
-
-
-
- 8082
-
-
+ true
@@ -263,7 +157,7 @@
org.codehaus.cargo
- cargo-maven2-plugin
+ cargo-maven3-plugin
start-server
@@ -310,13 +204,11 @@
+ 17
1.10
- 4.1.4
2.5.1
- 4.4.11
- 4.5.8
5.2
5.2
diff --git a/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java
index cafd8cfb7b..487794cc7f 100644
--- a/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java
+++ b/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java
@@ -3,8 +3,8 @@ package com.baeldung.basic;
import java.io.IOException;
import java.io.PrintWriter;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
diff --git a/httpclient-simple/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/httpclient-simple/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java
index 81f82a2c1c..7a0599cd49 100644
--- a/httpclient-simple/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java
+++ b/httpclient-simple/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java
@@ -2,13 +2,13 @@ package com.baeldung.client;
import java.net.URI;
-import org.apache.http.HttpHost;
-import org.apache.http.client.AuthCache;
-import org.apache.http.client.protocol.HttpClientContext;
-import org.apache.http.impl.auth.BasicScheme;
-import org.apache.http.impl.client.BasicAuthCache;
-import org.apache.http.protocol.BasicHttpContext;
-import org.apache.http.protocol.HttpContext;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.client5.http.auth.AuthCache;
+import org.apache.hc.client5.http.impl.auth.BasicAuthCache;
+import org.apache.hc.client5.http.impl.auth.BasicScheme;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.core5.http.protocol.BasicHttpContext;
+import org.apache.hc.core5.http.protocol.HttpContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
@@ -21,6 +21,7 @@ public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpCompone
this.host = host;
}
+ @Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
return createHttpContext();
}
diff --git a/httpclient-simple/src/main/java/com/baeldung/client/RestTemplateFactory.java b/httpclient-simple/src/main/java/com/baeldung/client/RestTemplateFactory.java
index aac4f8cebd..fafaae0157 100644
--- a/httpclient-simple/src/main/java/com/baeldung/client/RestTemplateFactory.java
+++ b/httpclient-simple/src/main/java/com/baeldung/client/RestTemplateFactory.java
@@ -1,6 +1,6 @@
package com.baeldung.client;
-import org.apache.http.HttpHost;
+import org.apache.hc.core5.http.HttpHost;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.client.ClientHttpRequestFactory;
@@ -35,7 +35,7 @@ public class RestTemplateFactory implements FactoryBean, Initializ
@Override
public void afterPropertiesSet() {
- HttpHost host = new HttpHost("localhost", 8082, "http");
+ HttpHost host = new HttpHost("http", "localhost", 8082);
final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host);
restTemplate = new RestTemplate(requestFactory);
restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("user1", "user1Pass"));
diff --git a/httpclient-simple/src/main/java/com/baeldung/filter/CustomFilter.java b/httpclient-simple/src/main/java/com/baeldung/filter/CustomFilter.java
index 6bb12610fa..a9509ddafa 100644
--- a/httpclient-simple/src/main/java/com/baeldung/filter/CustomFilter.java
+++ b/httpclient-simple/src/main/java/com/baeldung/filter/CustomFilter.java
@@ -2,10 +2,10 @@ package com.baeldung.filter;
import org.springframework.web.filter.GenericFilterBean;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
import java.io.IOException;
public class CustomFilter extends GenericFilterBean {
diff --git a/httpclient-simple/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/httpclient-simple/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java
index fb597e46c8..859b900170 100644
--- a/httpclient-simple/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java
+++ b/httpclient-simple/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java
@@ -7,41 +7,38 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
-import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebSecurity
-public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
+public class CustomWebSecurityConfigurerAdapter{
@Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
- .inMemoryAuthentication()
- .withUser("user1")
- .password(passwordEncoder().encode("user1Pass"))
- .authorities("ROLE_USER");
+ .inMemoryAuthentication()
+ .withUser("user1")
+ .password(passwordEncoder().encode("user1Pass"))
+ .authorities("ROLE_USER");
}
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .antMatchers("/securityNone")
- .permitAll()
- .anyRequest()
- .authenticated()
- .and()
- .httpBasic()
- .authenticationEntryPoint(authenticationEntryPoint);
+ @Bean
+ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
+
+ http.authorizeHttpRequests((authorize) -> authorize.anyRequest()
+ .authenticated())
+ .httpBasic()
+ .authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
+ return http.build();
}
-
+
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
diff --git a/httpclient-simple/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/httpclient-simple/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java
index 7dc53e3e1e..d53aa5bdfe 100644
--- a/httpclient-simple/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java
+++ b/httpclient-simple/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java
@@ -2,9 +2,9 @@ package com.baeldung.security;
import java.io.IOException;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
diff --git a/httpclient-simple/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java b/httpclient-simple/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java
index 1ae89adb89..615982fae4 100644
--- a/httpclient-simple/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java
+++ b/httpclient-simple/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java
@@ -2,8 +2,8 @@ package com.baeldung.security;
import java.io.IOException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
diff --git a/httpclient-simple/src/main/java/com/baeldung/web/dto/Bar.java b/httpclient-simple/src/main/java/com/baeldung/web/dto/Bar.java
index eb139b0ec1..1bb7476669 100644
--- a/httpclient-simple/src/main/java/com/baeldung/web/dto/Bar.java
+++ b/httpclient-simple/src/main/java/com/baeldung/web/dto/Bar.java
@@ -2,7 +2,7 @@ package com.baeldung.web.dto;
import java.io.Serializable;
-import javax.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Bar implements Serializable {
diff --git a/httpclient-simple/src/main/java/com/baeldung/web/dto/Foo.java b/httpclient-simple/src/main/java/com/baeldung/web/dto/Foo.java
index 23cfab132d..f904be0ad9 100644
--- a/httpclient-simple/src/main/java/com/baeldung/web/dto/Foo.java
+++ b/httpclient-simple/src/main/java/com/baeldung/web/dto/Foo.java
@@ -2,7 +2,7 @@ package com.baeldung.web.dto;
import java.io.Serializable;
-import javax.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Foo implements Serializable {
diff --git a/httpclient-simple/src/test/java/com/baeldung/client/ClientLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/client/ClientLiveTest.java
index 78e9813f06..1c7e766a72 100644
--- a/httpclient-simple/src/test/java/com/baeldung/client/ClientLiveTest.java
+++ b/httpclient-simple/src/test/java/com/baeldung/client/ClientLiveTest.java
@@ -1,25 +1,23 @@
package com.baeldung.client;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-import com.baeldung.client.spring.ClientConfig;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import org.junit.jupiter.api.Test;
+
import com.baeldung.web.dto.Foo;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { ClientConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class ClientLiveTest {
+class ClientLiveTest {
@Autowired
private RestTemplate secureRestTemplate;
@@ -27,21 +25,24 @@ public class ClientLiveTest {
// tests
@Test
- public final void whenContextIsBootstrapped_thenNoExceptions() {
+ void whenContextIsBootstrapped_thenNoExceptions() {
//
}
@Test
- public final void whenSecuredRestApiIsConsumed_then200OK() {
+ void whenSecuredRestApiIsConsumed_then200OK() {
final ResponseEntity responseEntity = secureRestTemplate.exchange("http://localhost:8082/httpclient-simple/api/foos/1", HttpMethod.GET, null, Foo.class);
assertThat(responseEntity.getStatusCode().value(), is(200));
}
- @Test(expected = ResourceAccessException.class)
- public final void whenHttpsUrlIsConsumed_thenException() {
+ @Test
+ void whenHttpsUrlIsConsumed_thenException() {
final String urlOverHttps = "https://localhost:8443/httpclient-simple/api/bars/1";
- final ResponseEntity response = new RestTemplate().exchange(urlOverHttps, HttpMethod.GET, null, String.class);
- assertThat(response.getStatusCode().value(), equalTo(200));
+ assertThrows(ResourceAccessException.class, () -> {
+ final ResponseEntity response = new RestTemplate()
+ .exchange(urlOverHttps, HttpMethod.GET, null, String.class);
+ assertThat(response.getStatusCode().value(), equalTo(200));
+ });
}
}
diff --git a/httpclient-simple/src/test/java/com/baeldung/client/RestClientLiveManualTest.java b/httpclient-simple/src/test/java/com/baeldung/client/RestClientLiveManualTest.java
index d133bc376c..efa0695aaf 100644
--- a/httpclient-simple/src/test/java/com/baeldung/client/RestClientLiveManualTest.java
+++ b/httpclient-simple/src/test/java/com/baeldung/client/RestClientLiveManualTest.java
@@ -1,112 +1,78 @@
package com.baeldung.client;
-import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.assertThat;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
-import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.config.Registry;
-import org.apache.http.config.RegistryBuilder;
-import org.apache.http.conn.scheme.Scheme;
-import org.apache.http.conn.socket.ConnectionSocketFactory;
-import org.apache.http.conn.socket.PlainConnectionSocketFactory;
-import org.apache.http.conn.ssl.NoopHostnameVerifier;
-import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
-import org.apache.http.conn.ssl.SSLSocketFactory;
-import org.apache.http.conn.ssl.TrustStrategy;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
-import org.apache.http.ssl.SSLContexts;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager;
+import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
+import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
+import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
+import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.config.Registry;
+import org.apache.hc.core5.http.config.RegistryBuilder;
+import org.apache.hc.core5.ssl.SSLContexts;
+import org.apache.hc.core5.ssl.TrustStrategy;
+import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
+import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
+import com.baeldung.handler.CustomHttpClientResponseHandler;
+
+
/**
* This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build
* */
-public class RestClientLiveManualTest {
+class RestClientLiveManualTest {
final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
- // tests
- // old httpClient will throw UnsupportedOperationException
- @Ignore
- @Test
- public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk() throws GeneralSecurityException {
- final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
- final CloseableHttpClient httpClient = (CloseableHttpClient) requestFactory.getHttpClient();
-
- final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
-
- final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, ALLOW_ALL_HOSTNAME_VERIFIER);
- httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 8443, sf));
-
- final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
- assertThat(response.getStatusCode().value(), equalTo(200));
- }
-
// new httpClient : 4.4 and above
@Test
- public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
+ void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk() throws GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
final Registry socketFactoryRegistry = RegistryBuilder. create()
- .register("https", sslsf)
- .register("http", new PlainConnectionSocketFactory())
- .build();
+ .register("https", sslsf)
+ .register("http", new PlainConnectionSocketFactory())
+ .build();
final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
final CloseableHttpClient httpClient = HttpClients.custom()
- .setSSLSocketFactory(sslsf)
- .setConnectionManager(connectionManager)
- .build();
+ .setConnectionManager(connectionManager)
+ .build();
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
- @Test
- public final void givenAcceptingAllCertificatesUsing4_4_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException {
- final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
- final HttpGet getMethod = new HttpGet(urlOverHttps);
- final HttpResponse response = httpClient.execute(getMethod);
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
- }
@Test
- public final void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() throws ClientProtocolException, IOException {
- final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
- final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
- requestFactory.setHttpClient(httpClient);
-
- final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
- assertThat(response.getStatusCode().value(), equalTo(200));
- }
-
- @Test(expected = SSLPeerUnverifiedException.class)
- public void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException {
- CloseableHttpClient httpClient = HttpClients.createDefault();
+ void whenHttpsUrlIsConsumed_thenException() {
String urlOverHttps = "https://localhost:8082/httpclient-simple";
HttpGet getMethod = new HttpGet(urlOverHttps);
- HttpResponse response = httpClient.execute(getMethod);
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ assertThrows(SSLPeerUnverifiedException.class, () -> {
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ HttpResponse response = httpClient.execute(getMethod, new CustomHttpClientResponseHandler());
+ assertThat(response.getCode(), equalTo(200));
+ });
}
}
diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java
index 44262851fd..616b6470af 100644
--- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java
+++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java
@@ -1,100 +1,76 @@
package com.baeldung.httpclient;
import com.google.common.collect.Lists;
-import org.apache.http.Header;
-import org.apache.http.HttpHeaders;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpUriRequest;
-import org.apache.http.client.methods.RequestBuilder;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.message.BasicHeader;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.message.BasicHeader;
+
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.io.IOException;
import java.util.List;
-public class HttpClientHeadersLiveTest {
+class HttpClientHeadersLiveTest {
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
private static final String SAMPLE_URL = "http://www.github.com";
- private CloseableHttpClient client;
-
- private CloseableHttpResponse response;
-
- @Before
- public final void before() {
- client = HttpClientBuilder.create().build();
- }
-
- @After
- public final void after() throws IllegalStateException, IOException {
- ResponseUtil.closeResponse(response);
- }
-
- // tests - headers - deprecated
-
@Test
- public final void givenNewApi_whenClientUsesCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException {
- client = HttpClients.custom().setUserAgent("Mozilla/5.0 Firefox/26.0").build();
-
+ void whenClientUsesCustomUserAgent_thenCorrect() throws IOException {
final HttpGet request = new HttpGet(SAMPLE_URL);
- response = client.execute(request);
+
+ try (CloseableHttpClient client = HttpClients.custom()
+ .setUserAgent("Mozilla/5.0 Firefox/26.0")
+ .build()) {
+
+ String response = client.execute(request, new BasicHttpClientResponseHandler());
+ logger.info("Response -> {}", response);
+ }
}
- // tests - headers - user agent
-
@Test
- public final void givenConfigOnRequest_whenRequestHasCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException {
- client = HttpClients.custom().build();
+ void whenRequestHasCustomUserAgent_thenCorrect() throws IOException {
final HttpGet request = new HttpGet(SAMPLE_URL);
request.setHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 Firefox/26.0");
- response = client.execute(request);
+
+ try (CloseableHttpClient client = HttpClients.createDefault()) {
+ String response = client.execute(request, new BasicHttpClientResponseHandler());
+ logger.info("Response -> {}", response);
+ }
}
@Test
- public final void givenConfigOnClient_whenRequestHasCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException {
- client = HttpClients.custom().setUserAgent("Mozilla/5.0 Firefox/26.0").build();
- response = client.execute(new HttpGet(SAMPLE_URL));
- }
-
- // tests - headers - content type
-
- @Test
- public final void givenUsingNewApi_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException {
- client = HttpClients.custom().build();
+ void whenRequestHasCustomContentType_thenCorrect() throws IOException {
final HttpGet request = new HttpGet(SAMPLE_URL);
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
- response = client.execute(request);
+
+ try (CloseableHttpClient client = HttpClients.createDefault()) {
+ String response = client.execute(request, new BasicHttpClientResponseHandler());
+ logger.debug("Response -> {}", response);
+ }
}
@Test
- public final void givenRequestBuildWithBuilderWithNewApi_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException {
- final CloseableHttpClient client2 = HttpClients.custom().build();
+ void givenConfigOnClient_whenRequestHasCustomContentType_thenCorrect() throws IOException {
final HttpGet request = new HttpGet(SAMPLE_URL);
- request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
- response = client2.execute(request);
- }
-
- @Test
- public final void givenRequestBuildWithBuilder_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException {
- client = HttpClients.custom().build();
- final HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).setHeader(HttpHeaders.CONTENT_TYPE, "application/json").build();
- response = client.execute(request);
- }
-
- @Test
- public final void givenConfigOnClient_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException {
final Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
final List headers = Lists.newArrayList(header);
- client = HttpClients.custom().setDefaultHeaders(headers).build();
- final HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();
- response = client.execute(request);
- }
+
+ try (CloseableHttpClient client = HttpClients.custom()
+ .setDefaultHeaders(headers)
+ .build()) {
+
+ String response = client.execute(request, new BasicHttpClientResponseHandler());
+ logger.debug("Response -> {}", response);
+ }
+ }
}
diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientParamsLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientParamsLiveTest.java
index f56a6863a3..ef662e1bd8 100644
--- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientParamsLiveTest.java
+++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientParamsLiveTest.java
@@ -1,7 +1,8 @@
package com.baeldung.httpclient;
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.assertThat;
+
import java.io.IOException;
import java.net.URI;
@@ -14,28 +15,25 @@ import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
-import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.net.URIBuilder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import org.junit.Before;
-import org.junit.Test;
+import com.baeldung.handler.CustomHttpClientResponseHandler;
-public class HttpClientParamsLiveTest {
+class HttpClientParamsLiveTest {
- private CloseableHttpClient client;
-
- private CloseableHttpResponse response;
private List nameValuePairs;
- @Before
+ @BeforeEach
public void setUp() {
- client = HttpClientBuilder.create()
- .build();
nameValuePairs = new ArrayList<>();
NameValuePair param1NameValuePair = new BasicNameValuePair("param1", "value1");
NameValuePair param2NameValuePair = new BasicNameValuePair("param2", "value2");
@@ -44,63 +42,83 @@ public class HttpClientParamsLiveTest {
}
@Test
- public void givenStringNameValuePairParams_whenGetRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException {
+ void givenStringNameValuePairParams_whenGetRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException {
HttpGet httpGet = new HttpGet("https://postman-echo.com/get");
URI uri = new URIBuilder(httpGet.getUri()).addParameter("param1", "value1")
.addParameter("param2", "value2")
.build();
httpGet.setUri(uri);
- response = client.execute(httpGet);
- assertThat(response.getCode(), equalTo(200));
- client.close();
+ try (CloseableHttpClient client = HttpClients.createDefault();
+ CloseableHttpResponse response = (CloseableHttpResponse) client
+ .execute(httpGet, new CustomHttpClientResponseHandler())) {
+
+ final int statusCode = response.getCode();
+ assertThat(statusCode, equalTo(HttpStatus.SC_OK));
+ }
}
@Test
- public void givenStringNameValuePairParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException {
+ void givenStringNameValuePairParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost("https://postman-echo.com/post");
URI uri = new URIBuilder(httpPost.getUri()).addParameter("param1", "value1")
.addParameter("param2", "value2")
.build();
httpPost.setUri(uri);
- response = client.execute(httpPost);
- assertThat(response.getCode(), equalTo(200));
- client.close();
+ try (CloseableHttpClient client = HttpClients.createDefault();
+ CloseableHttpResponse response = (CloseableHttpResponse) client
+ .execute(httpPost, new CustomHttpClientResponseHandler())) {
+
+ final int statusCode = response.getCode();
+ assertThat(statusCode, equalTo(HttpStatus.SC_OK));
+ }
}
@Test
- public void givenNameValuePairParams_whenGetRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException {
+ void givenNameValuePairParams_whenGetRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException {
HttpGet httpGet = new HttpGet("https://postman-echo.com/get");
URI uri = new URIBuilder(httpGet.getUri()).addParameters(nameValuePairs)
.build();
httpGet.setUri(uri);
- response = client.execute(httpGet);
- assertThat(response.getCode(), equalTo(200));
- client.close();
+ try (CloseableHttpClient client = HttpClients.createDefault();
+ CloseableHttpResponse response = (CloseableHttpResponse) client
+ .execute(httpGet, new CustomHttpClientResponseHandler())) {
+
+ final int statusCode = response.getCode();
+ assertThat(statusCode, equalTo(HttpStatus.SC_OK));
+ }
}
@Test
- public void givenNameValuePairsParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException {
+ void givenNameValuePairsParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost("https://postman-echo.com/post");
URI uri = new URIBuilder(httpPost.getUri()).addParameters(nameValuePairs)
.build();
httpPost.setUri(uri);
- response = client.execute(httpPost);
- assertThat(response.getCode(), equalTo(200));
- client.close();
+ try (CloseableHttpClient client = HttpClients.createDefault();
+ CloseableHttpResponse response = (CloseableHttpResponse) client
+ .execute(httpPost, new CustomHttpClientResponseHandler())) {
+
+ final int statusCode = response.getCode();
+ assertThat(statusCode, equalTo(HttpStatus.SC_OK));
+ }
}
@Test
- public void givenUrlEncodedEntityParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException {
+ void givenUrlEncodedEntityParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost("https://postman-echo.com/post");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8));
- response = client.execute(httpPost);
- assertThat(response.getCode(), equalTo(200));
- client.close();
+ try (CloseableHttpClient client = HttpClients.createDefault();
+ CloseableHttpResponse response = (CloseableHttpResponse) client
+ .execute(httpPost, new CustomHttpClientResponseHandler())) {
+
+ final int statusCode = response.getCode();
+ assertThat(statusCode, equalTo(HttpStatus.SC_OK));
+ }
}
}
diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutLiveTest.java
index ab80d5665f..f3d0a1c27f 100644
--- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutLiveTest.java
+++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutLiveTest.java
@@ -3,7 +3,6 @@ package com.baeldung.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpsClientSslLiveTest.java
index 24ceab0069..54633ba932 100644
--- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpsClientSslLiveTest.java
+++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpsClientSslLiveTest.java
@@ -1,7 +1,6 @@
package com.baeldung.httpclient;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.security.GeneralSecurityException;
@@ -9,73 +8,50 @@ import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.config.Registry;
-import org.apache.http.config.RegistryBuilder;
-import org.apache.http.conn.socket.ConnectionSocketFactory;
-import org.apache.http.conn.ssl.NoopHostnameVerifier;
-import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
-import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
-import org.apache.http.conn.ssl.TrustStrategy;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
-import org.apache.http.ssl.SSLContextBuilder;
-import org.apache.http.ssl.SSLContexts;
-import org.junit.Test;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
+import org.apache.hc.client5.http.io.HttpClientConnectionManager;
+import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
+import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
+import org.apache.hc.client5.http.ssl.TrustSelfSignedStrategy;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.ssl.SSLContextBuilder;
+import org.apache.hc.core5.ssl.SSLContexts;
+import org.apache.hc.core5.ssl.TrustStrategy;
+import org.hamcrest.MatcherAssert;
+import org.hamcrest.Matchers;
+import org.junit.jupiter.api.Test;
+
+import com.baeldung.handler.CustomHttpClientResponseHandler;
/**
* This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build
* */
-public class HttpsClientSslLiveTest {
+class HttpsClientSslLiveTest {
// "https://localhost:8443/spring-security-rest-basic-auth/api/bars/1" // local
// "https://mms.nw.ru/" // hosted
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
- // tests
-
- @Test(expected = SSLHandshakeException.class)
- public final void whenHttpsUrlIsConsumed_thenException() throws IOException {
- final CloseableHttpClient httpClient = HttpClientBuilder.create()
- .build();
-
+ @Test
+ void whenHttpsUrlIsConsumed_thenException() {
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
- final HttpResponse response = httpClient.execute(getMethod);
- assertThat(response.getStatusLine()
- .getStatusCode(), equalTo(200));
+
+ assertThrows(SSLHandshakeException.class, () -> {
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ HttpResponse response = httpClient.execute(getMethod, new CustomHttpClientResponseHandler());
+ MatcherAssert.assertThat(response.getCode(), Matchers.equalTo(200));
+ });
+
}
@Test
- public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
- final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
-
- final SSLContext sslContext = SSLContexts.custom()
- .loadTrustMaterial(null, acceptingTrustStrategy)
- .build();
-
- final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
- Registry socketFactoryRegistry = RegistryBuilder. create().register("https", sslsf).build();
- PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
-
- final CloseableHttpClient httpClient = HttpClients.custom()
- .setSSLSocketFactory(sslsf)
- .setConnectionManager(clientConnectionManager)
- .build();
-
- final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
- final HttpResponse response = httpClient.execute(getMethod);
- assertThat(response.getStatusLine()
- .getStatusCode(), equalTo(200));
-
- httpClient.close();
- }
-
- @Test
- public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
+ void whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
@@ -83,55 +59,45 @@ public class HttpsClientSslLiveTest {
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
- final CloseableHttpClient httpClient = HttpClients.custom()
+ final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslsf)
.build();
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
- final HttpResponse response = httpClient.execute(getMethod);
- assertThat(response.getStatusLine()
- .getStatusCode(), equalTo(200));
+ try (CloseableHttpClient client = HttpClients.custom()
+ .setConnectionManager(cm)
+ .build();
- httpClient.close();
+ CloseableHttpResponse response = (CloseableHttpResponse) client
+ .execute(getMethod, new CustomHttpClientResponseHandler())) {
+
+ final int statusCode = response.getCode();
+ MatcherAssert.assertThat(statusCode, Matchers.equalTo(HttpStatus.SC_OK));
+ }
}
@Test
- public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
+ void usingBuilder_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
- final CloseableHttpClient httpClient = HttpClients.custom()
- .setSSLHostnameVerifier(hostnameVerifier)
+ final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslsf)
.build();
- // new
-
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
- final HttpResponse response = httpClient.execute(getMethod);
- assertThat(response.getStatusLine()
- .getStatusCode(), equalTo(200));
- httpClient.close();
-
- }
-
- @Test
- public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
- final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true)
+ try (CloseableHttpClient client = HttpClients.custom()
+ .setConnectionManager(cm)
.build();
- final CloseableHttpClient client = HttpClients.custom()
- .setSSLContext(sslContext)
- .setSSLHostnameVerifier(new NoopHostnameVerifier())
- .build();
- final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
- httpGet.setHeader("Accept", "application/xml");
+ CloseableHttpResponse response = (CloseableHttpResponse) client
+ .execute(getMethod, new CustomHttpClientResponseHandler())) {
- final HttpResponse response = client.execute(httpGet);
- assertThat(response.getStatusLine()
- .getStatusCode(), equalTo(200));
+ final int statusCode = response.getCode();
+ MatcherAssert.assertThat(statusCode, Matchers.equalTo(HttpStatus.SC_OK));
+ }
}
}
diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/base/HttpClientBasicLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/base/HttpClientBasicLiveTest.java
index e05017ccdd..b850f2e8ba 100644
--- a/httpclient-simple/src/test/java/com/baeldung/httpclient/base/HttpClientBasicLiveTest.java
+++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/base/HttpClientBasicLiveTest.java
@@ -19,12 +19,12 @@ import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
-public class HttpClientBasicLiveTest {
+class HttpClientBasicLiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
@Test
- public final void whenExecutingBasicGetRequest_thenNoExceptions() throws IOException {
+ void whenExecutingBasicGetRequest_thenNoExceptions() throws IOException {
final HttpGet request = new HttpGet(SAMPLE_URL);
try (CloseableHttpClient client = HttpClientBuilder.create().build();
@@ -35,7 +35,7 @@ public class HttpClientBasicLiveTest {
}
@Test
- public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
+ void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
final HttpGet request = new HttpGet(SAMPLE_URL);
try (CloseableHttpClient client = HttpClientBuilder.create().build();
@@ -48,7 +48,7 @@ public class HttpClientBasicLiveTest {
@Test
- public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectMimeType() throws IOException {
+ void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectMimeType() throws IOException {
final HttpGet request = new HttpGet(SAMPLE_URL);
try (CloseableHttpClient client = HttpClientBuilder.create().build();
@@ -63,7 +63,7 @@ public class HttpClientBasicLiveTest {
@Test
- public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectBody() throws IOException, ParseException {
+ void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectBody() throws IOException, ParseException {
final HttpGet request = new HttpGet(SAMPLE_URL);
try (CloseableHttpClient client = HttpClientBuilder.create().build();
diff --git a/httpclient-simple/src/test/java/com/baeldung/test/LiveTestSuite.java b/httpclient-simple/src/test/java/com/baeldung/test/LiveTestSuite.java
deleted file mode 100644
index c864349e02..0000000000
--- a/httpclient-simple/src/test/java/com/baeldung/test/LiveTestSuite.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.baeldung.test;
-
-import com.baeldung.client.ClientLiveTest;
-import com.baeldung.client.RestClientLiveManualTest;
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
-// @formatter:off
- RestClientLiveManualTest.class
- ,ClientLiveTest.class
-}) //
-public class LiveTestSuite {
-
-}
diff --git a/httpclient4/.gitignore b/httpclient4/.gitignore
new file mode 100644
index 0000000000..83c05e60c8
--- /dev/null
+++ b/httpclient4/.gitignore
@@ -0,0 +1,13 @@
+*.class
+
+#folders#
+/target
+/neoDb*
+/data
+/src/main/webapp/WEB-INF/classes
+*/META-INF/*
+
+# Packaged files #
+*.jar
+*.war
+*.ear
\ No newline at end of file
diff --git a/httpclient4/README.md b/httpclient4/README.md
new file mode 100644
index 0000000000..445db1108b
--- /dev/null
+++ b/httpclient4/README.md
@@ -0,0 +1,14 @@
+## Apache HttpClient
+
+This module contains articles about Apache HttpClient 4.5
+
+### Relevant Articles
+
+- [Apache HttpClient with SSL](https://www.baeldung.com/httpclient-ssl)
+- [Apache HttpClient Timeout](https://www.baeldung.com/httpclient-timeout)
+- [Custom HTTP Header with the Apache HttpClient](https://www.baeldung.com/httpclient-custom-http-header)
+
+### Running the Tests
+To run the live tests, use the command: mvn clean install -Plive
+This will start an embedded Jetty server on port 8082 using the Cargo plugin configured in the pom.xml file,
+for the live Maven profile
diff --git a/httpclient4/pom.xml b/httpclient4/pom.xml
new file mode 100644
index 0000000000..8f896283b3
--- /dev/null
+++ b/httpclient4/pom.xml
@@ -0,0 +1,291 @@
+
+
+ 4.0.0
+ httpclient4
+ 0.1-SNAPSHOT
+ httpclient4
+ war
+
+
+ com.baeldung
+ parent-spring-5
+ 0.0.1-SNAPSHOT
+ ../parent-spring-5
+
+
+
+
+
+ org.springframework.security
+ spring-security-web
+ ${spring-security.version}
+
+
+ org.springframework.security
+ spring-security-config
+ ${spring-security.version}
+
+
+
+ org.springframework
+ spring-core
+ ${spring.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ org.springframework
+ spring-context
+ ${spring.version}
+
+
+ org.springframework
+ spring-jdbc
+ ${spring.version}
+
+
+ org.springframework
+ spring-beans
+ ${spring.version}
+
+
+ org.springframework
+ spring-aop
+ ${spring.version}
+
+
+ org.springframework
+ spring-tx
+ ${spring.version}
+
+
+ org.springframework
+ spring-expression
+ ${spring.version}
+
+
+ org.springframework
+ spring-web
+ ${spring.version}
+
+
+ org.springframework
+ spring-webmvc
+ ${spring.version}
+
+
+ org.springframework
+ spring-oxm
+ ${spring.version}
+
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
+
+ org.apache.httpcomponents
+ httpcore
+ ${httpcore.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+
+ org.apache.httpcomponents
+ httpclient
+ ${httpclient.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ org.apache.httpcomponents
+ fluent-hc
+ ${httpclient.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ org.apache.httpcomponents
+ httpmime
+ ${httpclient.version}
+
+
+ commons-codec
+ commons-codec
+ ${commons-codec.version}
+
+
+ org.apache.httpcomponents
+ httpasyncclient
+ ${httpasyncclient.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ com.github.tomakehurst
+ wiremock
+ ${wiremock.version}
+ test
+
+
+
+ javax.servlet
+ javax.servlet-api
+ ${javax.servlet-api.version}
+ provided
+
+
+ javax.servlet
+ jstl
+ ${jstl.version}
+ runtime
+
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+
+ org.springframework
+ spring-test
+ ${spring.version}
+ test
+
+
+
+
+ httpclient-simple
+
+
+ src/main/resources
+ true
+
+
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+
+ org.codehaus.cargo
+ cargo-maven2-plugin
+ ${cargo-maven2-plugin.version}
+
+ true
+
+ jetty8x
+ embedded
+
+
+
+
+
+
+ 8082
+
+
+
+
+
+
+
+
+
+ live
+
+
+
+ org.codehaus.cargo
+ cargo-maven2-plugin
+
+
+ start-server
+ pre-integration-test
+
+ start
+
+
+
+ stop-server
+ post-integration-test
+
+ stop
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ none
+
+
+ **/*LiveTest.java
+
+
+ cargo
+
+
+
+
+
+
+
+
+
+
+
+
+ 1.10
+ 4.1.5
+
+ 2.5.1
+ 4.4.16
+ 4.5.14
+
+ 1.6.1
+
+
+
\ No newline at end of file
diff --git a/httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java
new file mode 100644
index 0000000000..cafd8cfb7b
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java
@@ -0,0 +1,30 @@
+package com.baeldung.basic;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
+import org.springframework.stereotype.Component;
+
+@Component
+public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
+
+ @Override
+ public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException {
+ response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ final PrintWriter writer = response.getWriter();
+ writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage());
+ }
+
+ @Override
+ public void afterPropertiesSet() {
+ setRealmName("Baeldung");
+ super.afterPropertiesSet();
+ }
+
+}
diff --git a/httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java
new file mode 100644
index 0000000000..81f82a2c1c
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java
@@ -0,0 +1,39 @@
+package com.baeldung.client;
+
+import java.net.URI;
+
+import org.apache.http.HttpHost;
+import org.apache.http.client.AuthCache;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.impl.auth.BasicScheme;
+import org.apache.http.impl.client.BasicAuthCache;
+import org.apache.http.protocol.BasicHttpContext;
+import org.apache.http.protocol.HttpContext;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
+
+public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpComponentsClientHttpRequestFactory {
+
+ HttpHost host;
+
+ public HttpComponentsClientHttpRequestFactoryBasicAuth(HttpHost host) {
+ super();
+ this.host = host;
+ }
+
+ protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
+ return createHttpContext();
+ }
+
+ private HttpContext createHttpContext() {
+
+ AuthCache authCache = new BasicAuthCache();
+
+ BasicScheme basicAuth = new BasicScheme();
+ authCache.put(host, basicAuth);
+
+ BasicHttpContext localcontext = new BasicHttpContext();
+ localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
+ return localcontext;
+ }
+}
\ No newline at end of file
diff --git a/httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java b/httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java
new file mode 100644
index 0000000000..aac4f8cebd
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java
@@ -0,0 +1,44 @@
+package com.baeldung.client;
+
+import org.apache.http.HttpHost;
+import org.springframework.beans.factory.FactoryBean;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.http.client.ClientHttpRequestFactory;
+import org.springframework.http.client.support.BasicAuthenticationInterceptor;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.RestTemplate;
+
+@Component
+public class RestTemplateFactory implements FactoryBean, InitializingBean {
+ private RestTemplate restTemplate;
+
+ public RestTemplateFactory() {
+ super();
+ }
+
+ // API
+
+ @Override
+ public RestTemplate getObject() {
+ return restTemplate;
+ }
+
+ @Override
+ public Class getObjectType() {
+ return RestTemplate.class;
+ }
+
+ @Override
+ public boolean isSingleton() {
+ return true;
+ }
+
+ @Override
+ public void afterPropertiesSet() {
+ HttpHost host = new HttpHost("localhost", 8082, "http");
+ final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host);
+ restTemplate = new RestTemplate(requestFactory);
+ restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("user1", "user1Pass"));
+ }
+
+}
\ No newline at end of file
diff --git a/httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java b/httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java
new file mode 100644
index 0000000000..03994b55a5
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java
@@ -0,0 +1,16 @@
+package com.baeldung.client.spring;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan("com.baeldung.client")
+public class ClientConfig {
+
+ public ClientConfig() {
+ super();
+ }
+
+ // beans
+
+}
\ No newline at end of file
diff --git a/httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java b/httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java
new file mode 100644
index 0000000000..6bb12610fa
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java
@@ -0,0 +1,18 @@
+package com.baeldung.filter;
+
+import org.springframework.web.filter.GenericFilterBean;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.io.IOException;
+
+public class CustomFilter extends GenericFilterBean {
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+ chain.doFilter(request, response);
+ }
+
+}
diff --git a/httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java
new file mode 100644
index 0000000000..fb597e46c8
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java
@@ -0,0 +1,49 @@
+package com.baeldung.filter;
+
+import com.baeldung.security.RestAuthenticationEntryPoint;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
+
+@Configuration
+@EnableWebSecurity
+public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
+
+ @Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
+
+ @Autowired
+ public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ .withUser("user1")
+ .password(passwordEncoder().encode("user1Pass"))
+ .authorities("ROLE_USER");
+ }
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .antMatchers("/securityNone")
+ .permitAll()
+ .anyRequest()
+ .authenticated()
+ .and()
+ .httpBasic()
+ .authenticationEntryPoint(authenticationEntryPoint);
+
+ http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
+ }
+
+ @Bean
+ public PasswordEncoder passwordEncoder() {
+ return new BCryptPasswordEncoder();
+ }
+}
diff --git a/httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java
new file mode 100644
index 0000000000..7dc53e3e1e
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java
@@ -0,0 +1,48 @@
+package com.baeldung.security;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.security.core.Authentication;
+import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
+import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
+import org.springframework.security.web.savedrequest.RequestCache;
+import org.springframework.security.web.savedrequest.SavedRequest;
+import org.springframework.util.StringUtils;
+
+public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
+
+ private RequestCache requestCache = new HttpSessionRequestCache();
+
+ @Override
+ public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException {
+ final SavedRequest savedRequest = requestCache.getRequest(request, response);
+
+ if (savedRequest == null) {
+ super.onAuthenticationSuccess(request, response, authentication);
+
+ return;
+ }
+ final String targetUrlParameter = getTargetUrlParameter();
+ if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
+ requestCache.removeRequest(request, response);
+ super.onAuthenticationSuccess(request, response, authentication);
+
+ return;
+ }
+
+ clearAuthenticationAttributes(request);
+
+ // Use the DefaultSavedRequest URL
+ // final String targetUrl = savedRequest.getRedirectUrl();
+ // logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
+ // getRedirectStrategy().sendRedirect(request, response, targetUrl);
+ }
+
+ public void setRequestCache(final RequestCache requestCache) {
+ this.requestCache = requestCache;
+ }
+}
diff --git a/httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java b/httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java
new file mode 100644
index 0000000000..1ae89adb89
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java
@@ -0,0 +1,23 @@
+package com.baeldung.security;
+
+import java.io.IOException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.AuthenticationEntryPoint;
+import org.springframework.stereotype.Component;
+
+/**
+ * The Entry Point will not redirect to any sort of Login - it will return the 401
+ */
+@Component
+public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
+
+ @Override
+ public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException {
+ response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
+ }
+
+}
\ No newline at end of file
diff --git a/httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java
new file mode 100644
index 0000000000..4ba9d47f8d
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java
@@ -0,0 +1,16 @@
+package com.baeldung.spring;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.ImportResource;
+
+@Configuration
+@ImportResource({ "classpath:webSecurityConfig.xml" })
+@ComponentScan("com.baeldung.security")
+public class SecSecurityConfig {
+
+ public SecSecurityConfig() {
+ super();
+ }
+
+}
diff --git a/httpclient4/src/main/java/com/baeldung/spring/WebConfig.java b/httpclient4/src/main/java/com/baeldung/spring/WebConfig.java
new file mode 100644
index 0000000000..8d5c1dc7f1
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/spring/WebConfig.java
@@ -0,0 +1,30 @@
+package com.baeldung.spring;
+
+import java.util.List;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
+import org.springframework.web.servlet.config.annotation.EnableWebMvc;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+@Configuration
+@EnableWebMvc
+@ComponentScan("com.baeldung.web")
+public class WebConfig implements WebMvcConfigurer {
+
+ public WebConfig() {
+ super();
+ }
+
+ // beans
+
+ @Override
+ public void configureMessageConverters(final List> converters) {
+ converters.add(new MappingJackson2HttpMessageConverter());
+ }
+
+ //
+
+}
\ No newline at end of file
diff --git a/httpclient4/src/main/java/com/baeldung/web/controller/BarController.java b/httpclient4/src/main/java/com/baeldung/web/controller/BarController.java
new file mode 100644
index 0000000000..02e6af03af
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/web/controller/BarController.java
@@ -0,0 +1,31 @@
+package com.baeldung.web.controller;
+
+import com.baeldung.web.dto.Bar;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+@Controller
+@RequestMapping(value = "/bars")
+public class BarController {
+
+ @Autowired
+ private ApplicationEventPublisher eventPublisher;
+
+ public BarController() {
+ super();
+ }
+
+ // API
+
+ @RequestMapping(value = "/{id}", method = RequestMethod.GET)
+ @ResponseBody
+ public Bar findOne(@PathVariable("id") final Long id) {
+ return new Bar();
+ }
+
+}
diff --git a/httpclient4/src/main/java/com/baeldung/web/controller/FooController.java b/httpclient4/src/main/java/com/baeldung/web/controller/FooController.java
new file mode 100644
index 0000000000..461a5e351a
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/web/controller/FooController.java
@@ -0,0 +1,33 @@
+package com.baeldung.web.controller;
+
+import com.baeldung.web.dto.Foo;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+@Controller
+@RequestMapping(value = "/foos")
+public class FooController {
+
+ @Autowired
+ private ApplicationEventPublisher eventPublisher;
+
+ public FooController() {
+ super();
+ }
+
+ // API
+
+ @RequestMapping(value = "/{id}", method = RequestMethod.GET)
+ @ResponseBody
+ @PreAuthorize("hasRole('ROLE_USER')")
+ public Foo findOne(@PathVariable("id") final Long id) {
+ return new Foo();
+ }
+
+}
diff --git a/httpclient4/src/main/java/com/baeldung/web/dto/Bar.java b/httpclient4/src/main/java/com/baeldung/web/dto/Bar.java
new file mode 100644
index 0000000000..eb139b0ec1
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/web/dto/Bar.java
@@ -0,0 +1,14 @@
+package com.baeldung.web.dto;
+
+import java.io.Serializable;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement
+public class Bar implements Serializable {
+
+ public Bar() {
+ super();
+ }
+
+}
diff --git a/httpclient4/src/main/java/com/baeldung/web/dto/Foo.java b/httpclient4/src/main/java/com/baeldung/web/dto/Foo.java
new file mode 100644
index 0000000000..23cfab132d
--- /dev/null
+++ b/httpclient4/src/main/java/com/baeldung/web/dto/Foo.java
@@ -0,0 +1,14 @@
+package com.baeldung.web.dto;
+
+import java.io.Serializable;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement
+public class Foo implements Serializable {
+
+ public Foo() {
+ super();
+ }
+
+}
diff --git a/httpclient4/src/main/resources/logback.xml b/httpclient4/src/main/resources/logback.xml
new file mode 100644
index 0000000000..56af2d397e
--- /dev/null
+++ b/httpclient4/src/main/resources/logback.xml
@@ -0,0 +1,19 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/httpclient4/src/main/resources/webSecurityConfig.xml b/httpclient4/src/main/resources/webSecurityConfig.xml
new file mode 100644
index 0000000000..2ff9a1de15
--- /dev/null
+++ b/httpclient4/src/main/resources/webSecurityConfig.xml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/httpclient4/src/main/webapp/WEB-INF/api-servlet.xml b/httpclient4/src/main/webapp/WEB-INF/api-servlet.xml
new file mode 100644
index 0000000000..1dbff70b83
--- /dev/null
+++ b/httpclient4/src/main/webapp/WEB-INF/api-servlet.xml
@@ -0,0 +1,6 @@
+
+
+
+
\ No newline at end of file
diff --git a/httpclient4/src/main/webapp/WEB-INF/web.xml b/httpclient4/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000..4b2dd54266
--- /dev/null
+++ b/httpclient4/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,43 @@
+
+
+
+ Spring Security Custom Application
+
+
+
+ contextClass
+ org.springframework.web.context.support.AnnotationConfigWebApplicationContext
+
+
+ contextConfigLocation
+ com.baeldung.spring
+
+
+
+ org.springframework.web.context.ContextLoaderListener
+
+
+
+
+ api
+ org.springframework.web.servlet.DispatcherServlet
+ 1
+
+
+ api
+ /api/*
+
+
+
+
+ springSecurityFilterChain
+ org.springframework.web.filter.DelegatingFilterProxy
+
+
+ springSecurityFilterChain
+ /*
+
+
+
\ No newline at end of file
diff --git a/httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java b/httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java
new file mode 100644
index 0000000000..2785bc5d08
--- /dev/null
+++ b/httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java
@@ -0,0 +1,99 @@
+package com.baeldung.client;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLPeerUnverifiedException;
+
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.config.Registry;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.conn.socket.ConnectionSocketFactory;
+import org.apache.http.conn.socket.PlainConnectionSocketFactory;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.TrustStrategy;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
+import org.apache.http.ssl.SSLContexts;
+
+import org.springframework.http.HttpMethod;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
+import org.springframework.web.client.RestTemplate;
+
+
+class ClientLiveTest {
+
+ final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
+
+ @Test
+ void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
+
+ final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
+ final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
+ final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
+ final Registry socketFactoryRegistry = RegistryBuilder. create()
+ .register("https", sslsf)
+ .register("http", new PlainConnectionSocketFactory())
+ .build();
+
+ final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
+ final CloseableHttpClient httpClient = HttpClients.custom()
+ .setSSLSocketFactory(sslsf)
+ .setConnectionManager(connectionManager)
+ .build();
+
+ final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
+ final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
+ assertThat(response.getStatusCode().value(), equalTo(200));
+ }
+
+ @Test
+ void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
+ final HttpGet getMethod = new HttpGet(urlOverHttps);
+
+ try (final CloseableHttpClient httpClient = HttpClients.custom()
+ .setSSLHostnameVerifier(new NoopHostnameVerifier())
+ .build()) {
+
+ final HttpResponse response = httpClient.execute(getMethod);
+ assertThat(response.getStatusLine()
+ .getStatusCode(), equalTo(200));
+ }
+ }
+
+ @Test
+ void givenAcceptingAllCertificates_whenUsingRestTemplate_thenCorrect() {
+ final CloseableHttpClient httpClient = HttpClients.custom()
+ .setSSLHostnameVerifier(new NoopHostnameVerifier())
+ .build();
+ final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
+ requestFactory.setHttpClient(httpClient);
+
+ final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
+ assertThat(response.getStatusCode().value(), equalTo(200));
+ }
+
+ @Test
+ void whenHttpsUrlIsConsumed_thenException() {
+ String urlOverHttps = "https://localhost:8082/httpclient-simple";
+ HttpGet getMethod = new HttpGet(urlOverHttps);
+
+ assertThrows(SSLPeerUnverifiedException.class, () -> {
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ HttpResponse response = httpClient.execute(getMethod);
+ assertThat(response.getStatusLine()
+ .getStatusCode(), equalTo(200));
+ });
+ }
+}
\ No newline at end of file
diff --git a/httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java b/httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java
new file mode 100644
index 0000000000..c336e6a068
--- /dev/null
+++ b/httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java
@@ -0,0 +1,92 @@
+package com.baeldung.client;
+
+import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+
+import javax.net.ssl.SSLContext;
+
+
+import org.apache.http.HttpResponse;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.config.Registry;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.conn.socket.ConnectionSocketFactory;
+import org.apache.http.conn.socket.PlainConnectionSocketFactory;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+
+import org.apache.http.conn.ssl.TrustStrategy;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
+import org.apache.http.ssl.SSLContexts;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
+import org.springframework.web.client.RestTemplate;
+
+/**
+ * This test requires a localhost server over HTTPS
+ * It should only be manually run, not part of the automated build
+ * */
+public class RestClientV4LiveManualTest {
+
+ final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
+
+ @Test
+ void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
+
+ final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
+ final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
+ final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
+ final Registry socketFactoryRegistry = RegistryBuilder. create()
+ .register("https", sslsf)
+ .register("http", new PlainConnectionSocketFactory())
+ .build();
+
+ final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
+ final CloseableHttpClient httpClient = HttpClients.custom()
+ .setSSLSocketFactory(sslsf)
+ .setConnectionManager(connectionManager)
+ .build();
+
+ final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
+ final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
+ assertThat(response.getStatusCode().value(), equalTo(200));
+ }
+
+ @Test
+ void givenAcceptingAllCertificatesUsing4_4_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
+ final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
+
+ final HttpGet getMethod = new HttpGet(urlOverHttps);
+ final HttpResponse response = httpClient.execute(getMethod);
+ assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ }
+
+ @Test
+ void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect(){
+ final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
+ final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
+ requestFactory.setHttpClient(httpClient);
+
+ final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
+ assertThat(response.getStatusCode().value(), equalTo(200));
+ }
+
+ @Test
+ public void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException {
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ String urlOverHttps = "https://localhost:8082/httpclient-simple";
+ HttpGet getMethod = new HttpGet(urlOverHttps);
+ HttpResponse response = httpClient.execute(getMethod);
+ assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
+ }
+}
diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java b/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java
new file mode 100644
index 0000000000..eef813b3ff
--- /dev/null
+++ b/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java
@@ -0,0 +1,24 @@
+package com.baeldung.httpclient;
+
+import java.io.IOException;
+import org.apache.http.HttpHeaders;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.client.methods.RequestBuilder;
+import org.apache.http.impl.client.HttpClients;
+import org.junit.jupiter.api.Test;
+
+class HttpClientHeaderV4LiveTest {
+
+ private static final String SAMPLE_URL = "http://www.github.com";
+
+ @Test
+ void givenRequestBuildWithBuilder_whenRequestHasCustomContentType_thenCorrect() throws IOException {
+ HttpClient client = HttpClients.custom().build();
+ HttpUriRequest request = RequestBuilder.get()
+ .setUri(SAMPLE_URL)
+ .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
+ .build();
+ client.execute(request);
+ }
+}
\ No newline at end of file
diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java b/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java
similarity index 97%
rename from httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java
rename to httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java
index 9bf523590e..4d4dd7be15 100644
--- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java
+++ b/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java
@@ -76,7 +76,7 @@ class HttpClientTimeoutV4LiveTest {
*/
@Test
@Disabled
- public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException {
+ void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException {
final int timeout = 3;
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java b/httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java
new file mode 100644
index 0000000000..6c7bcf9b08
--- /dev/null
+++ b/httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java
@@ -0,0 +1,111 @@
+package com.baeldung.httpclient;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLHandshakeException;
+
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
+import org.apache.http.conn.ssl.TrustStrategy;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.client.HttpClients;
+
+import org.apache.http.ssl.SSLContextBuilder;
+import org.apache.http.ssl.SSLContexts;
+import org.junit.jupiter.api.Test;
+
+class HttpsClientV4SslLiveTest {
+
+
+ // "https://localhost:8443/spring-security-rest-basic-auth/api/bars/1" // local
+ // "https://mms.nw.ru/" // hosted
+ private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
+
+ // tests
+
+ @Test
+ void whenHttpsUrlIsConsumed_thenException() {
+ final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
+
+ assertThrows(SSLHandshakeException.class, () -> {
+ final CloseableHttpClient httpClient = HttpClientBuilder
+ .create()
+ .build();
+ final HttpResponse response = httpClient.execute(getMethod);
+ assertThat(response.getStatusLine()
+ .getStatusCode(), equalTo(200));
+ });
+ }
+
+
+ @Test
+ void whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
+ final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
+ final SSLContext sslContext = SSLContexts.custom()
+ .loadTrustMaterial(null, acceptingTrustStrategy)
+ .build();
+
+ final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
+
+ final CloseableHttpClient httpClient = HttpClients.custom()
+ .setSSLSocketFactory(sslsf)
+ .build();
+
+ final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
+ final HttpResponse response = httpClient.execute(getMethod);
+ assertThat(response.getStatusLine()
+ .getStatusCode(), equalTo(200));
+
+ httpClient.close();
+ }
+
+ @Test
+ void using_builder_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
+ final SSLContext sslContext = new SSLContextBuilder()
+ .loadTrustMaterial(null, new TrustSelfSignedStrategy())
+ .build();
+ final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
+
+ final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
+ final CloseableHttpClient httpClient = HttpClients.custom()
+ .setSSLHostnameVerifier(hostnameVerifier)
+ .setSSLSocketFactory(sslsf)
+ .build();
+
+ final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
+ final HttpResponse response = httpClient.execute(getMethod);
+ assertThat(response.getStatusLine()
+ .getStatusCode(), equalTo(200));
+ httpClient.close();
+
+ }
+
+ @Test
+ void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
+ final SSLContext sslContext = new SSLContextBuilder()
+ .loadTrustMaterial(null, (certificate, authType) -> true)
+ .build();
+
+ final CloseableHttpClient client = HttpClients.custom()
+ .setSSLContext(sslContext)
+ .setSSLHostnameVerifier(new NoopHostnameVerifier())
+ .build();
+ final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
+ httpGet.setHeader("Accept", "application/xml");
+
+ final HttpResponse response = client.execute(httpGet);
+ assertThat(response.getStatusLine()
+ .getStatusCode(), equalTo(200));
+ }
+
+}
\ No newline at end of file
diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/ResponseUtil.java b/httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java
similarity index 100%
rename from httpclient-simple/src/test/java/com/baeldung/httpclient/ResponseUtil.java
rename to httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java
diff --git a/httpclient4/src/test/resources/.gitignore b/httpclient4/src/test/resources/.gitignore
new file mode 100644
index 0000000000..83c05e60c8
--- /dev/null
+++ b/httpclient4/src/test/resources/.gitignore
@@ -0,0 +1,13 @@
+*.class
+
+#folders#
+/target
+/neoDb*
+/data
+/src/main/webapp/WEB-INF/classes
+*/META-INF/*
+
+# Packaged files #
+*.jar
+*.war
+*.ear
\ No newline at end of file
diff --git a/httpclient4/src/test/resources/test.in b/httpclient4/src/test/resources/test.in
new file mode 100644
index 0000000000..95d09f2b10
--- /dev/null
+++ b/httpclient4/src/test/resources/test.in
@@ -0,0 +1 @@
+hello world
\ No newline at end of file
diff --git a/java-blockchain/pom.xml b/java-blockchain/pom.xml
index 6d3910df80..2279a7ceff 100644
--- a/java-blockchain/pom.xml
+++ b/java-blockchain/pom.xml
@@ -24,22 +24,6 @@
true
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- ${maven.compiler.source}
- ${maven.compiler.target}
-
-
-
-
- 1.8
- 1.8
-
-
\ No newline at end of file
diff --git a/javaxval-2/pom.xml b/javaxval-2/pom.xml
index a63d21969b..5c311e10f8 100644
--- a/javaxval-2/pom.xml
+++ b/javaxval-2/pom.xml
@@ -60,9 +60,6 @@
6.2.3.Final
6.2.0.Final
- 3.6.1
- 1.8
- 1.8
3.0.0
5.3.21
2.7.1
diff --git a/javaxval/pom.xml b/javaxval/pom.xml
index 753a46cffe..1feed71abb 100644
--- a/javaxval/pom.xml
+++ b/javaxval/pom.xml
@@ -46,7 +46,7 @@
test
-
+
@@ -60,9 +60,6 @@
6.2.3.Final
6.2.0.Final
- 3.6.1
- 1.8
- 1.8
3.0.0
5.3.21
2.7.1
diff --git a/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java b/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java
index df85e26b76..b158d63720 100644
--- a/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java
+++ b/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java
@@ -9,10 +9,14 @@ import org.glassfish.grizzly.http.server.HttpServer;
import org.junit.After;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
import com.baeldung.jersey.server.http.EmbeddedHttpServer;
+@Disabled
+@Ignore
public class ItemsUnitTest {
private HttpServer server;
diff --git a/jgit/pom.xml b/jgit/pom.xml
index ca58709583..91881fbec8 100644
--- a/jgit/pom.xml
+++ b/jgit/pom.xml
@@ -36,6 +36,7 @@
+
4.5.0.201609210915-r
diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-5/bookstore-monolith/pom.xml
index ccf7a3c85e..ccaa802a39 100644
--- a/jhipster-5/bookstore-monolith/pom.xml
+++ b/jhipster-5/bookstore-monolith/pom.xml
@@ -94,10 +94,6 @@
org.apache.commons
commons-lang3
-
- mysql
- mysql-connector-java
-
org.assertj
assertj-core
@@ -1175,7 +1171,7 @@
2.1.1
- 2.0.8.RELEASE
+ 2.7.8
5.2.17.Final
diff --git a/jmeter/README.md b/jmeter/README.md
index 76d329342d..f01fa4eca5 100644
--- a/jmeter/README.md
+++ b/jmeter/README.md
@@ -55,3 +55,4 @@ Enjoy it :)
- [Write Extracted Data to a File Using JMeter](https://www.baeldung.com/jmeter-write-to-file)
- [Basic Authentication in JMeter](https://www.baeldung.com/jmeter-basic-auth)
- [JMeter: Latency vs. Load Time](https://www.baeldung.com/java-jmeter-latency-vs-load-time)
+- [How Do I Generate a Dashboard Report in JMeter?](https://www.baeldung.com/jmeter-dashboard-report)
diff --git a/jmeter/pom.xml b/jmeter/pom.xml
index b2e4197dfc..acd823b74f 100644
--- a/jmeter/pom.xml
+++ b/jmeter/pom.xml
@@ -68,5 +68,96 @@
2.6.0
+
+
+
+ dashboard
+
+
+ env
+ dash
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-thymeleaf
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+ launch-web-app
+
+ start
+
+
+ com.baeldung.dashboard.DashboardApplication
+
+
+
+
+
+ JMeter-Dashboard
+
+
+
+
+ com.lazerycode.jmeter
+ jmeter-maven-plugin
+ 3.7.0
+
+
+
+ configuration
+
+ configure
+
+
+
+
+ jmeter-tests
+
+ jmeter
+ results
+
+
+
+
+ ${project.basedir}/src/main/resources/dashboard
+ ${project.basedir}/src/main/resources/dashboard
+ true
+ true
+ true
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+ stop-web-app
+
+ stop
+
+
+
+
+
+
+
+
+ 5.5
+
+
+
\ No newline at end of file
diff --git a/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java b/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java
new file mode 100644
index 0000000000..6d62ad7e15
--- /dev/null
+++ b/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java
@@ -0,0 +1,17 @@
+package com.baeldung.dashboard;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
+import org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration;
+import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
+import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
+import org.springframework.context.annotation.Profile;
+
+@Profile("JMeter-Dashboard")
+@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, MongoAutoConfiguration.class, MongoRepositoriesAutoConfiguration.class, MongoDataAutoConfiguration.class })
+public class DashboardApplication {
+ public static void main(String[] args) throws Exception {
+ SpringApplication.run(DashboardApplication.class, args);
+ }
+}
diff --git a/jmeter/src/main/java/com/baeldung/dashboard/controllers/Dashboard.java b/jmeter/src/main/java/com/baeldung/dashboard/controllers/Dashboard.java
new file mode 100644
index 0000000000..8c749b21d8
--- /dev/null
+++ b/jmeter/src/main/java/com/baeldung/dashboard/controllers/Dashboard.java
@@ -0,0 +1,42 @@
+package com.baeldung.dashboard.controllers;
+
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Random;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.GetMapping;
+
+import com.baeldung.dashboard.models.Quotes;
+
+@Controller
+public class Dashboard {
+
+ @GetMapping("/greeting")
+ public String getGreeting(Model model) {
+ model.addAttribute("host", System.getProperty("os.name"));
+ return "greeting";
+ }
+
+ @GetMapping("/quote")
+ public String getQuote(Model model) throws InterruptedException {
+ Random r = new Random();
+ int day = r.nextInt(7);
+ String quote = Quotes.list.get(day);
+
+ int wait = r.nextInt(6);
+ Thread.currentThread().sleep(wait);
+ model.addAttribute("quote", quote);
+
+ return "quote";
+ }
+
+ @GetMapping("/time")
+ public String getTime(Model model) {
+ DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm:ss a");
+ LocalDateTime now = LocalDateTime.now();
+ model.addAttribute("time", fmt.format(now));
+ return "time";
+ }
+}
diff --git a/jmeter/src/main/java/com/baeldung/dashboard/models/Quotes.java b/jmeter/src/main/java/com/baeldung/dashboard/models/Quotes.java
new file mode 100644
index 0000000000..7c8e6a732d
--- /dev/null
+++ b/jmeter/src/main/java/com/baeldung/dashboard/models/Quotes.java
@@ -0,0 +1,13 @@
+package com.baeldung.dashboard.models;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class Quotes {
+ public static final List list = Arrays.asList("The greatest glory in living lies not in never falling, but in rising every time we fall. -Nelson Mandela\r\n",
+ "The way to get started is to quit talking and begin doing. -Walt Disney\r\n",
+ "Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma – which is living with the results of other people's thinking. -Steve Jobs\r\n",
+ "If life were predictable it would cease to be life, and be without flavor. -Eleanor Roosevelt\r\n",
+ "If you look at what you have in life, you'll always have more. If you look at what you don't have in life, you'll never have enough. -Oprah Winfrey\r\n",
+ "If you set your goals ridiculously high and it's a failure, you will fail above everyone else's success. -James Cameron\r\n", "Life is what happens when you're busy making other plans. -John Lennon");
+}
diff --git a/jmeter/src/main/resources/dashboard/ReportsDashboard.csv b/jmeter/src/main/resources/dashboard/ReportsDashboard.csv
new file mode 100644
index 0000000000..046666ca2b
--- /dev/null
+++ b/jmeter/src/main/resources/dashboard/ReportsDashboard.csv
@@ -0,0 +1,16 @@
+timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect
+1674622105952,714,HTTP Request (/greeting),200,,Thread Group 1-4,text,true,,430,126,5,5,http://localhost:8080/greeting,705,0,7
+1674622105450,1216,HTTP Request (/greeting),200,,Thread Group 1-1,text,true,,430,126,5,5,http://localhost:8080/greeting,1207,0,54
+1674622105468,1198,HTTP Request (/greeting),200,,Thread Group 1-2,text,true,,430,126,5,5,http://localhost:8080/greeting,1189,0,36
+1674622106064,602,HTTP Request (/greeting),200,,Thread Group 1-5,text,true,,430,126,5,5,http://localhost:8080/greeting,593,0,2
+1674622105800,866,HTTP Request (/greeting),200,,Thread Group 1-3,text,true,,430,126,5,5,http://localhost:8080/greeting,857,0,1
+1674622106669,13,HTTP Request (/quote),200,,Thread Group 1-4,text,true,,515,123,5,5,http://localhost:8080/quote,12,0,0
+1674622106669,16,HTTP Request (/quote),200,,Thread Group 1-2,text,true,,548,123,5,5,http://localhost:8080/quote,16,0,0
+1674622106671,18,HTTP Request (/quote),200,,Thread Group 1-1,text,true,,629,123,5,5,http://localhost:8080/quote,18,0,0
+1674622106669,24,HTTP Request (/quote),200,,Thread Group 1-5,text,true,,602,123,5,5,http://localhost:8080/quote,24,0,0
+1674622106669,29,HTTP Request (/quote),200,,Thread Group 1-3,text,true,,515,123,5,5,http://localhost:8080/quote,29,0,0
+1674622106690,18,HTTP Request (/time),200,,Thread Group 1-1,text,true,,432,122,5,5,http://localhost:8080/time,18,0,0
+1674622106699,9,HTTP Request (/time),200,,Thread Group 1-3,text,true,,432,122,5,5,http://localhost:8080/time,9,0,0
+1674622106683,26,HTTP Request (/time),200,,Thread Group 1-4,text,true,,432,122,5,5,http://localhost:8080/time,25,0,0
+1674622106688,25,HTTP Request (/time),200,,Thread Group 1-2,text,true,,432,122,2,2,http://localhost:8080/time,25,0,0
+1674622106695,18,HTTP Request (/time),200,,Thread Group 1-5,text,true,,432,122,2,2,http://localhost:8080/time,17,0,0
diff --git a/jmeter/src/main/resources/dashboard/ReportsDashboard.jmx b/jmeter/src/main/resources/dashboard/ReportsDashboard.jmx
new file mode 100644
index 0000000000..081920c671
--- /dev/null
+++ b/jmeter/src/main/resources/dashboard/ReportsDashboard.jmx
@@ -0,0 +1,127 @@
+
+
+
+
+
+ false
+ true
+ false
+
+
+
+
+
+
+
+ Test Greetings Page
+ continue
+
+ false
+ 1
+
+ 5
+ 1
+ false
+
+
+ true
+
+
+
+
+
+
+ localhost
+ 8080
+
+
+ /greeting
+ GET
+ true
+ false
+ true
+ false
+
+
+
+
+
+
+
+
+
+ localhost
+ 8080
+
+
+ /quote
+ GET
+ true
+ false
+ true
+ false
+
+
+
+
+
+
+
+
+
+ localhost
+ 8080
+
+
+ /time
+ 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
+
+
+ dashapp
+
+
+
+
+
+
diff --git a/jmeter/src/main/resources/static/index.html b/jmeter/src/main/resources/static/index.html
new file mode 100644
index 0000000000..fe2e1bf095
--- /dev/null
+++ b/jmeter/src/main/resources/static/index.html
@@ -0,0 +1,15 @@
+
+
+
+
+ Jmeter Dashboard Test APP
+
+
+
+
+ Get your Quote here
+ Get your Time here
+ Get your greeting here
+
+
+
\ No newline at end of file
diff --git a/jmeter/src/main/resources/templates/greeting.html b/jmeter/src/main/resources/templates/greeting.html
new file mode 100644
index 0000000000..3b023db6b1
--- /dev/null
+++ b/jmeter/src/main/resources/templates/greeting.html
@@ -0,0 +1,10 @@
+
+
+
+ Jmeter Dashboard Test APP
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jmeter/src/main/resources/templates/quote.html b/jmeter/src/main/resources/templates/quote.html
new file mode 100644
index 0000000000..8d943c2a3d
--- /dev/null
+++ b/jmeter/src/main/resources/templates/quote.html
@@ -0,0 +1,11 @@
+
+
+
+ Jmeter Dashboard Test APP
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jmeter/src/main/resources/templates/time.html b/jmeter/src/main/resources/templates/time.html
new file mode 100644
index 0000000000..d068bbe050
--- /dev/null
+++ b/jmeter/src/main/resources/templates/time.html
@@ -0,0 +1,10 @@
+
+
+
+ Jmeter Dashboard Test APP
+
+
+
+
+
+
\ No newline at end of file
diff --git a/kubernetes-modules/kubernetes-spring/pom.xml b/kubernetes-modules/kubernetes-spring/pom.xml
index 01064fa384..05532ab0b0 100644
--- a/kubernetes-modules/kubernetes-spring/pom.xml
+++ b/kubernetes-modules/kubernetes-spring/pom.xml
@@ -3,11 +3,10 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.example
- demo
+ kubernetes-spring
0.0.1-SNAPSHOT
- demo
- Demo project for Spring Boot
+ kubernetes-spring
+ Intro to Kubernetes with Spring boot
com.baeldung
diff --git a/libraries-data-db/pom.xml b/libraries-data-db/pom.xml
index 8e5140458e..6c72a4902c 100644
--- a/libraries-data-db/pom.xml
+++ b/libraries-data-db/pom.xml
@@ -127,8 +127,8 @@
- mysql
- mysql-connector-java
+ com.mysql
+ mysql-connector-j
diff --git a/libraries-security/src/main/java/com/baeldung/digitalsignature/DigitalSignatureUtils.java b/libraries-security/src/main/java/com/baeldung/digitalsignature/DigitalSignatureUtils.java
new file mode 100644
index 0000000000..cc0da187b9
--- /dev/null
+++ b/libraries-security/src/main/java/com/baeldung/digitalsignature/DigitalSignatureUtils.java
@@ -0,0 +1,86 @@
+package com.baeldung.digitalsignature;
+
+import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
+import org.bouncycastle.asn1.x509.DigestInfo;
+import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder;
+import org.bouncycastle.operator.DigestAlgorithmIdentifierFinder;
+
+import javax.crypto.Cipher;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.security.*;
+import java.security.cert.Certificate;
+import java.util.Arrays;
+
+public class DigitalSignatureUtils {
+
+ public static PrivateKey getPrivateKey(String file, char[] password, String storeType, String alias) throws Exception {
+ KeyStore keyStore = KeyStore.getInstance(storeType);
+ keyStore.load(new FileInputStream(file), password);
+ return (PrivateKey) keyStore.getKey(alias, password);
+ }
+
+ public static PublicKey getPublicKey(String file, char[] password, String storeType, String alias) throws Exception {
+ KeyStore keyStore = KeyStore.getInstance(storeType);
+ keyStore.load(new FileInputStream(file), password);
+ Certificate certificate = keyStore.getCertificate(alias);
+ return certificate.getPublicKey();
+ }
+
+ public static byte[] sign(byte[] message, String signingAlgorithm, PrivateKey signingKey) throws SecurityException {
+ try {
+ Signature signature = Signature.getInstance(signingAlgorithm);
+ signature.initSign(signingKey);
+ signature.update(message);
+ return signature.sign();
+ } catch (GeneralSecurityException exp) {
+ throw new SecurityException("Error during signature generation", exp);
+ }
+ }
+
+ public static boolean verify(byte[] messageBytes, String signingAlgorithm, PublicKey publicKey, byte[] signedData) {
+ try {
+ Signature signature = Signature.getInstance(signingAlgorithm);
+ signature.initVerify(publicKey);
+ signature.update(messageBytes);
+ return signature.verify(signedData);
+ } catch (GeneralSecurityException exp) {
+ throw new SecurityException("Error during verifying", exp);
+ }
+ }
+
+ public static byte[] signWithMessageDigestAndCipher(byte[] messageBytes, String hashingAlgorithm, PrivateKey privateKey) {
+ try {
+ MessageDigest md = MessageDigest.getInstance(hashingAlgorithm);
+ byte[] messageHash = md.digest(messageBytes);
+ DigestAlgorithmIdentifierFinder hashAlgorithmFinder = new DefaultDigestAlgorithmIdentifierFinder();
+ AlgorithmIdentifier hashingAlgorithmIdentifier = hashAlgorithmFinder.find(hashingAlgorithm);
+ DigestInfo digestInfo = new DigestInfo(hashingAlgorithmIdentifier, messageHash);
+ byte[] hashToEncrypt = digestInfo.getEncoded();
+
+ Cipher cipher = Cipher.getInstance("RSA");
+ cipher.init(Cipher.ENCRYPT_MODE, privateKey);
+ return cipher.doFinal(hashToEncrypt);
+ } catch (GeneralSecurityException | IOException exp) {
+ throw new SecurityException("Error during signature generation", exp);
+ }
+ }
+
+ public static boolean verifyWithMessageDigestAndCipher(byte[] messageBytes, String hashingAlgorithm, PublicKey publicKey, byte[] encryptedMessageHash) {
+ try {
+ MessageDigest md = MessageDigest.getInstance(hashingAlgorithm);
+ byte[] newMessageHash = md.digest(messageBytes);
+ DigestAlgorithmIdentifierFinder hashAlgorithmFinder = new DefaultDigestAlgorithmIdentifierFinder();
+ AlgorithmIdentifier hashingAlgorithmIdentifier = hashAlgorithmFinder.find(hashingAlgorithm);
+ DigestInfo digestInfo = new DigestInfo(hashingAlgorithmIdentifier, newMessageHash);
+ byte[] hashToEncrypt = digestInfo.getEncoded();
+
+ Cipher cipher = Cipher.getInstance("RSA");
+ cipher.init(Cipher.DECRYPT_MODE, publicKey);
+ byte[] decryptedMessageHash = cipher.doFinal(encryptedMessageHash);
+ return Arrays.equals(decryptedMessageHash, hashToEncrypt);
+ } catch (GeneralSecurityException | IOException exp) {
+ throw new SecurityException("Error during verifying", exp);
+ }
+ }
+}
diff --git a/libraries-security/src/main/java/com/baeldung/digitalsignature/Utils.java b/libraries-security/src/main/java/com/baeldung/digitalsignature/Utils.java
deleted file mode 100644
index 9f1e5808c3..0000000000
--- a/libraries-security/src/main/java/com/baeldung/digitalsignature/Utils.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.baeldung.digitalsignature;
-
-import java.io.FileInputStream;
-import java.security.KeyStore;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.cert.Certificate;
-
-public class Utils {
-
- private static final String STORE_TYPE = "PKCS12";
- private static final char[] PASSWORD = "changeit".toCharArray();
- private static final String SENDER_KEYSTORE = "sender_keystore.p12";
- private static final String SENDER_ALIAS = "senderKeyPair";
-
- public static final String SIGNING_ALGORITHM = "SHA256withRSA";
-
- private static final String RECEIVER_KEYSTORE = "receiver_keystore.p12";
- private static final String RECEIVER_ALIAS = "receiverKeyPair";
-
- public static PrivateKey getPrivateKey() throws Exception {
- KeyStore keyStore = KeyStore.getInstance(STORE_TYPE);
- keyStore.load(new FileInputStream(SENDER_KEYSTORE), PASSWORD);
- return (PrivateKey) keyStore.getKey(SENDER_ALIAS, PASSWORD);
- }
-
- public static PublicKey getPublicKey() throws Exception {
- KeyStore keyStore = KeyStore.getInstance(STORE_TYPE);
- keyStore.load(new FileInputStream(RECEIVER_KEYSTORE), PASSWORD);
- Certificate certificate = keyStore.getCertificate(RECEIVER_ALIAS);
- return certificate.getPublicKey();
- }
-}
diff --git a/libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherSigning.java b/libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherSigning.java
deleted file mode 100644
index 78d40dd365..0000000000
--- a/libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherSigning.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.baeldung.digitalsignature.level1;
-
-import com.baeldung.digitalsignature.Utils;
-
-import javax.crypto.Cipher;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.security.MessageDigest;
-import java.security.PrivateKey;
-
-public class DigitalSignatureWithMessageDigestAndCipherSigning {
-
- public static void main(String[] args) throws Exception {
-
- PrivateKey privateKey = Utils.getPrivateKey();
-
- byte[] messageBytes = Files.readAllBytes(Paths.get("src/test/resources/digitalsignature/message.txt"));
-
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- byte[] messageHash = md.digest(messageBytes);
-
- Cipher cipher = Cipher.getInstance("RSA");
- cipher.init(Cipher.ENCRYPT_MODE, privateKey);
- byte[] digitalSignature = cipher.doFinal(messageHash);
-
- Files.write(Paths.get("target/digital_signature_1"), digitalSignature);
- }
-}
diff --git a/libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherVerifying.java b/libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherVerifying.java
deleted file mode 100644
index 0b242a44fb..0000000000
--- a/libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherVerifying.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.baeldung.digitalsignature.level1;
-
-import com.baeldung.digitalsignature.Utils;
-
-import javax.crypto.Cipher;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.security.MessageDigest;
-import java.security.PublicKey;
-import java.util.Arrays;
-
-public class DigitalSignatureWithMessageDigestAndCipherVerifying {
-
- public static void main(String[] args) throws Exception {
-
- PublicKey publicKey = Utils.getPublicKey();
-
- byte[] messageBytes = Files.readAllBytes(Paths.get("src/test/resources/digitalsignature/message.txt"));
-
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- byte[] newMessageHash = md.digest(messageBytes);
-
- byte[] encryptedMessageHash = Files.readAllBytes(Paths.get("target/digital_signature_1"));
-
- Cipher cipher = Cipher.getInstance("RSA");
- cipher.init(Cipher.DECRYPT_MODE, publicKey);
- byte[] decryptedMessageHash = cipher.doFinal(encryptedMessageHash);
-
- boolean isCorrect = Arrays.equals(decryptedMessageHash, newMessageHash);
- System.out.println("Signature " + (isCorrect ? "correct" : "incorrect"));
- }
-
-}
diff --git a/libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureSigning.java b/libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureSigning.java
deleted file mode 100644
index afc8fd1045..0000000000
--- a/libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureSigning.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.baeldung.digitalsignature.level2;
-
-import com.baeldung.digitalsignature.Utils;
-
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.security.PrivateKey;
-import java.security.Signature;
-
-public class DigitalSignatureWithSignatureSigning {
-
- public static void main(String[] args) throws Exception {
-
- PrivateKey privateKey = Utils.getPrivateKey();
-
- Signature signature = Signature.getInstance(Utils.SIGNING_ALGORITHM);
- signature.initSign(privateKey);
-
- byte[] messageBytes = Files.readAllBytes(Paths.get("src/test/resources/digitalsignature/message.txt"));
-
- signature.update(messageBytes);
- byte[] digitalSignature = signature.sign();
-
- Files.write(Paths.get("target/digital_signature_2"), digitalSignature);
- }
-
-}
diff --git a/libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureVerifying.java b/libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureVerifying.java
deleted file mode 100644
index ee34be989c..0000000000
--- a/libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureVerifying.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.baeldung.digitalsignature.level2;
-
-import com.baeldung.digitalsignature.Utils;
-
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.security.PublicKey;
-import java.security.Signature;
-
-public class DigitalSignatureWithSignatureVerifying {
-
- public static void main(String[] args) throws Exception {
-
- PublicKey publicKey = Utils.getPublicKey();
-
- byte[] sig = Files.readAllBytes(Paths.get("target/digital_signature_2"));
-
- Signature signature = Signature.getInstance(Utils.SIGNING_ALGORITHM);
- signature.initVerify(publicKey);
-
- byte[] messageBytes = Files.readAllBytes(Paths.get("src/test/resources/digitalsignature/message.txt"));
-
- signature.update(messageBytes);
-
- boolean isCorrect = signature.verify(sig);
- System.out.println("Signature " + (isCorrect ? "correct" : "incorrect"));
- }
-}
diff --git a/libraries-security/src/test/java/com/baeldung/digitalsignature/DigitalSignatureUnitTest.java b/libraries-security/src/test/java/com/baeldung/digitalsignature/DigitalSignatureUnitTest.java
new file mode 100644
index 0000000000..65058dca52
--- /dev/null
+++ b/libraries-security/src/test/java/com/baeldung/digitalsignature/DigitalSignatureUnitTest.java
@@ -0,0 +1,76 @@
+package com.baeldung.digitalsignature;
+
+import org.junit.Test;
+
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+
+import static org.junit.Assert.assertTrue;
+
+public class DigitalSignatureUnitTest {
+
+ String messagePath = "src/test/resources/digitalsignature/message.txt";
+ String senderKeyStore = "src/test/resources/digitalsignature/sender_keystore.jks";
+ String receiverKeyStore = "src/test/resources/digitalsignature/receiver_keystore.jks";
+ String storeType = "JKS";
+ String senderAlias = "senderKeyPair";
+ String receiverAlias = "receiverKeyPair";
+ char[] password = "changeit".toCharArray();
+ String signingAlgorithm = "SHA256withRSA";
+ String hashingAlgorithm = "SHA-256";
+
+ @Test
+ public void givenMessageData_whenSignWithSignatureSigning_thenVerify() throws Exception {
+ PrivateKey privateKey = DigitalSignatureUtils.getPrivateKey(senderKeyStore, password, storeType, senderAlias);
+ byte[] messageBytes = Files.readAllBytes(Paths.get(messagePath));
+
+ byte[] digitalSignature = DigitalSignatureUtils.sign(messageBytes, signingAlgorithm, privateKey);
+
+ PublicKey publicKey = DigitalSignatureUtils.getPublicKey(receiverKeyStore, password, storeType, receiverAlias);
+ boolean isCorrect = DigitalSignatureUtils.verify(messageBytes, signingAlgorithm, publicKey, digitalSignature);
+
+ assertTrue(isCorrect);
+ }
+
+ @Test
+ public void givenMessageData_whenSignWithMessageDigestAndCipher_thenVerify() throws Exception {
+ PrivateKey privateKey = DigitalSignatureUtils.getPrivateKey(senderKeyStore, password, storeType, senderAlias);
+ byte[] messageBytes = Files.readAllBytes(Paths.get(messagePath));
+
+ byte[] encryptedMessageHash = DigitalSignatureUtils.signWithMessageDigestAndCipher(messageBytes, hashingAlgorithm, privateKey);
+
+ PublicKey publicKey = DigitalSignatureUtils.getPublicKey(receiverKeyStore, password, storeType, receiverAlias);
+ boolean isCorrect = DigitalSignatureUtils.verifyWithMessageDigestAndCipher(messageBytes, hashingAlgorithm, publicKey, encryptedMessageHash);
+
+ assertTrue(isCorrect);
+ }
+
+ @Test
+ public void givenMessageData_whenSignWithSignatureSigning_thenVerifyWithMessageDigestAndCipher() throws Exception {
+ PrivateKey privateKey = DigitalSignatureUtils.getPrivateKey(senderKeyStore, password, storeType, senderAlias);
+ byte[] messageBytes = Files.readAllBytes(Paths.get(messagePath));
+
+ byte[] digitalSignature = DigitalSignatureUtils.sign(messageBytes, signingAlgorithm, privateKey);
+
+ PublicKey publicKey = DigitalSignatureUtils.getPublicKey(receiverKeyStore, password, storeType, receiverAlias);
+ boolean isCorrect = DigitalSignatureUtils.verifyWithMessageDigestAndCipher(messageBytes, hashingAlgorithm, publicKey, digitalSignature);
+
+ assertTrue(isCorrect);
+ }
+
+ @Test
+ public void givenMessageData_whenSignWithMessageDigestAndCipher_thenVerifyWithSignature() throws Exception {
+ PrivateKey privateKey = DigitalSignatureUtils.getPrivateKey(senderKeyStore, password, storeType, senderAlias);
+ byte[] messageBytes = Files.readAllBytes(Paths.get(messagePath));
+
+ byte[] encryptedMessageHash = DigitalSignatureUtils.signWithMessageDigestAndCipher(messageBytes, hashingAlgorithm, privateKey);
+
+ PublicKey publicKey = DigitalSignatureUtils.getPublicKey(receiverKeyStore, password, storeType, receiverAlias);
+ boolean isCorrect = DigitalSignatureUtils.verify(messageBytes, signingAlgorithm, publicKey, encryptedMessageHash);
+
+ assertTrue(isCorrect);
+ }
+
+}
diff --git a/libraries-security/src/test/resources/digitalsignature/receiver_keystore.jks b/libraries-security/src/test/resources/digitalsignature/receiver_keystore.jks
new file mode 100644
index 0000000000..184b5b8600
Binary files /dev/null and b/libraries-security/src/test/resources/digitalsignature/receiver_keystore.jks differ
diff --git a/libraries-security/src/test/resources/digitalsignature/sender_certificate.cer b/libraries-security/src/test/resources/digitalsignature/sender_certificate.cer
new file mode 100644
index 0000000000..98e306bd49
--- /dev/null
+++ b/libraries-security/src/test/resources/digitalsignature/sender_certificate.cer
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIICxTCCAa2gAwIBAgIEala2gjANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhC
+YWVsZHVuZzAeFw0yMzAyMTkwNjA5NTdaFw0yNDAyMTkwNjA5NTdaMBMxETAPBgNV
+BAMTCEJhZWxkdW5nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAifku
+JnJM3U/x3jWpjpUZeSVpbdUTirdB2Ta0mwXXaZmGwtrwZvS8pXdmegFUMnYB92RJ
+98j4iYjivXElwwjFIc4YRa7hQicqMfa1H3BUtDwIpqlXM1jISr5TYAE/t/wpkrVH
+A1QPNv7Fb07ormWKwktTMWyUoLo0chInv07Ip3m6F3X3O0jZFjE8N+7Fnv9oMdsN
+sAAq+f/7jJSdzo/vzHebR0XUxB1YP6sTWRH6nlNw2h+0kTMf33CkXyDG1Y1qsBRK
+MoOia10bi21B7Yd+lJo0ZnT1JNei4eEdPYxWQa43JMY6PnpJI9d5WKvye2NewXvO
+pLap8WR3dgX6n6bUtwIDAQABoyEwHzAdBgNVHQ4EFgQUQVqwZ6AlNlPeeUOmw89A
+u86n09gwDQYJKoZIhvcNAQELBQADggEBAGoV1ECn0h0IYEoQ8pxF1zbXnt35XEO4
+ZPbq8cPuYj92X3c9TWeHJIHGO3ZYMS7eaBRL5HhCTqG3YjAsm6+bea9cBffeZwG3
+EAl0u7e8CI6Ri6065Og4s0c7Y3ZJIJ4i6c5bVqPep8Oj3IFUUAwxz+95c2LX9cfL
+hxzH8N2RzWvGoJBrmWNeQUuKVlMBVBX6n/EcWmCS/VYORw0mwJ9vdmPhGU3hGggG
+S0rAVnQlIdvzWsaNllNWf6ETrrHceCflKsOuettjODZUAqiZ9aEd9WMDGHLtZw94
+zONYICWg2o3Sx9/F26wHdjHn+gxB2Z45Dvd0rBMuCHqwJELxyvofc1E=
+-----END CERTIFICATE-----
diff --git a/libraries-security/src/test/resources/digitalsignature/sender_keystore.jks b/libraries-security/src/test/resources/digitalsignature/sender_keystore.jks
new file mode 100644
index 0000000000..1ad4db895b
Binary files /dev/null and b/libraries-security/src/test/resources/digitalsignature/sender_keystore.jks differ
diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml
index cdcbc798a4..62c9ca5870 100644
--- a/mapstruct/pom.xml
+++ b/mapstruct/pom.xml
@@ -49,10 +49,7 @@
org.apache.maven.plugins
maven-compiler-plugin
- ${maven-compiler-plugin.version}
- ${maven.compiler.source}
- ${maven.compiler.target}
org.mapstruct
@@ -78,8 +75,6 @@
1.5.3.Final
4.3.4.RELEASE
- 1.8
- 1.8
0.2.0
diff --git a/messaging-modules/rabbitmq/README.md b/messaging-modules/rabbitmq/README.md
index 6a74c297fc..93bb795d7b 100644
--- a/messaging-modules/rabbitmq/README.md
+++ b/messaging-modules/rabbitmq/README.md
@@ -7,5 +7,5 @@ This module contains articles about RabbitMQ.
- [Exchanges, Queues, and Bindings in RabbitMQ](https://www.baeldung.com/java-rabbitmq-exchanges-queues-bindings)
- [Pub-Sub vs. Message Queues](https://www.baeldung.com/pub-sub-vs-message-queues)
- [Channels and Connections in RabbitMQ](https://www.baeldung.com/java-rabbitmq-channels-connections)
-
+- [Create Dynamic Queues in RabbitMQ](https://www.baeldung.com/rabbitmq-dynamic-queues)
diff --git a/messaging-modules/rabbitmq/src/main/java/com/baeldung/queue/dynamic/DynamicQueueCreation.java b/messaging-modules/rabbitmq/src/main/java/com/baeldung/queue/dynamic/DynamicQueueCreation.java
new file mode 100644
index 0000000000..f62660bf81
--- /dev/null
+++ b/messaging-modules/rabbitmq/src/main/java/com/baeldung/queue/dynamic/DynamicQueueCreation.java
@@ -0,0 +1,34 @@
+package com.baeldung.queue.dynamic;
+
+import java.io.IOException;
+import java.util.concurrent.TimeoutException;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.rabbitmq.client.AMQP;
+import com.rabbitmq.client.Channel;
+import com.rabbitmq.client.Connection;
+import com.rabbitmq.client.ConnectionFactory;
+
+public class DynamicQueueCreation {
+
+ private static final Logger log = LoggerFactory.getLogger(DynamicQueueCreation.class);
+
+ private static final String QUEUE_NAME = "baeldung-queue";
+
+ public static void main(String[] args) throws IOException, TimeoutException {
+
+ ConnectionFactory factory = new ConnectionFactory();
+ factory.setHost("localhost");
+
+ try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) {
+ AMQP.Queue.DeclareOk declareOk = channel.queueDeclare(QUEUE_NAME, true, false, false, null);
+ log.info(declareOk.getQueue());
+
+ AMQP.Queue.DeclareOk declareOkExists = channel.queueDeclarePassive(QUEUE_NAME);
+ log.info(declareOkExists.getQueue());
+ }
+ }
+
+}
diff --git a/messaging-modules/rabbitmq/src/test/java/com/baeldung/benchmark/queue/dynamic/DynamicQueueCreationLiveTest.java b/messaging-modules/rabbitmq/src/test/java/com/baeldung/benchmark/queue/dynamic/DynamicQueueCreationLiveTest.java
new file mode 100644
index 0000000000..aa430035ef
--- /dev/null
+++ b/messaging-modules/rabbitmq/src/test/java/com/baeldung/benchmark/queue/dynamic/DynamicQueueCreationLiveTest.java
@@ -0,0 +1,71 @@
+package com.baeldung.benchmark.queue.dynamic;
+
+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 java.io.IOException;
+import java.util.concurrent.TimeoutException;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import com.rabbitmq.client.AMQP;
+import com.rabbitmq.client.Channel;
+import com.rabbitmq.client.Connection;
+import com.rabbitmq.client.ConnectionFactory;
+
+public class DynamicQueueCreationLiveTest {
+
+ private static final String QUEUE_NAME = "baeldung-queue";
+ private static final String QUEUE_NAME_NEW = "baeldung-queue-new";
+
+ private static Connection connection;
+
+ @BeforeAll
+ public static void setUpConnection() throws IOException, TimeoutException {
+ ConnectionFactory factory = new ConnectionFactory();
+ factory.setHost("localhost");
+ connection = factory.newConnection();
+ }
+
+ @Test
+ void givenQueueName_whenCreatingQueue_thenCheckingIfQueueCreated() throws IOException, TimeoutException {
+
+ try (Channel channel = connection.createChannel()) {
+ AMQP.Queue.DeclareOk declareOk = channel.queueDeclare(QUEUE_NAME, true, false, false, null);
+
+ assertNotNull(declareOk);
+ assertEquals(QUEUE_NAME, declareOk.getQueue());
+ }
+ }
+
+ @Test
+ void givenQueueName_whenCreatingQueue_thenCheckingIfQueueExists() throws IOException, TimeoutException {
+
+ try (Channel channel = connection.createChannel()) {
+ channel.queueDeclare(QUEUE_NAME, true, false, false, null);
+
+ AMQP.Queue.DeclareOk declareOk = channel.queueDeclarePassive(QUEUE_NAME);
+
+ assertNotNull(declareOk);
+ assertEquals(QUEUE_NAME, declareOk.getQueue());
+ }
+ }
+
+ @Test
+ void givenQueueName_whenQueueDoesNotExist_thenCheckingIfQueueExists() throws IOException, TimeoutException {
+
+ try (Channel channel = connection.createChannel()) {
+ assertThrows(IOException.class, () -> {
+ channel.queueDeclarePassive(QUEUE_NAME_NEW);
+ });
+ }
+ }
+
+ @AfterAll
+ public static void destroyConnection() throws IOException {
+ connection.close();
+ }
+}
diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml
index 115589b1b0..a1f16c4a64 100644
--- a/parent-boot-2/pom.xml
+++ b/parent-boot-2/pom.xml
@@ -24,6 +24,11 @@
pom
import
+
+ mysql
+ mysql-connector-java
+ ${mysql-connector-java.version}
+
org.springframework.boot
spring-boot-dependencies
@@ -89,8 +94,9 @@
3.3.0
1.0.22.RELEASE
- 2.7.5
+ 2.7.8
1.9.1
+ 8.0.31
\ No newline at end of file
diff --git a/pdf/README.md b/pdf/README.md
index dd6931ba78..2a9a23a804 100644
--- a/pdf/README.md
+++ b/pdf/README.md
@@ -8,3 +8,4 @@ This module contains articles about PDF files.
- [Generating PDF Files Using Thymeleaf](https://www.baeldung.com/thymeleaf-generate-pdf)
- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64)
- [HTML to PDF Using OpenPDF](https://www.baeldung.com/java-html-to-pdf)
+- [Reading PDF File Using Java](https://www.baeldung.com/java-pdf-file-read)
diff --git a/pdf/sample.pdf b/pdf/sample.pdf
new file mode 100644
index 0000000000..805a21e6e0
Binary files /dev/null and b/pdf/sample.pdf differ
diff --git a/pdf/src/test/java/com/baeldung/pdfreadertest/ReadPdfFileUnitTest.java b/pdf/src/test/java/com/baeldung/pdfreadertest/ReadPdfFileUnitTest.java
new file mode 100644
index 0000000000..83e3aa711a
--- /dev/null
+++ b/pdf/src/test/java/com/baeldung/pdfreadertest/ReadPdfFileUnitTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.pdfreadertest;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.text.PDFTextStripper;
+import org.junit.jupiter.api.Test;
+
+import com.itextpdf.text.pdf.PdfReader;
+import com.itextpdf.text.pdf.parser.PdfTextExtractor;
+
+class ReadPdfFileUnitTest {
+
+ @Test
+ public void givenSamplePdf_whenUsingApachePdfBox_thenCompareOutput() throws IOException {
+ String expectedText = "Hello World!\n";
+
+ File file = new File("sample.pdf");
+ PDDocument document = PDDocument.load(file);
+
+ PDFTextStripper stripper = new PDFTextStripper();
+
+ String text = stripper.getText(document);
+
+ document.close();
+
+ assertEquals(expectedText, text);
+
+ }
+
+ @Test
+ public void givenSamplePdf_whenUsingiTextPdf_thenCompareOutput() throws IOException {
+ String expectedText = "Hello World!";
+
+ PdfReader reader = new PdfReader("sample.pdf");
+ int pages = reader.getNumberOfPages();
+ StringBuilder text = new StringBuilder();
+
+ for (int i = 1; i <= pages; i++) {
+
+ text.append(PdfTextExtractor.getTextFromPage(reader, i));
+
+ }
+ reader.close();
+ assertEquals(expectedText, text.toString());
+
+ }
+
+}
diff --git a/persistence-modules/rethinkdb/pom.xml b/persistence-modules/rethinkdb/pom.xml
new file mode 100644
index 0000000000..17c7036ed3
--- /dev/null
+++ b/persistence-modules/rethinkdb/pom.xml
@@ -0,0 +1,53 @@
+
+
+ 4.0.0
+ rethinkdb
+ rethinkdb
+ Code snippets for RethinkDB articles
+
+
+ com.baeldung
+ parent-boot-2
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-2
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ com.rethinkdb
+ rethinkdb-driver
+ 2.4.4
+
+
+
+ org.projectlombok
+ lombok
+ provided
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
+ 17
+
+
+
diff --git a/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/InsertIntegrationTest.java b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/InsertIntegrationTest.java
new file mode 100644
index 0000000000..244959d854
--- /dev/null
+++ b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/InsertIntegrationTest.java
@@ -0,0 +1,62 @@
+package com.baeldung.rethinkdb;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+
+import static com.rethinkdb.RethinkDB.r;
+
+/**
+ * Some tests demonstrating inserting data.
+ */
+public class InsertIntegrationTest extends TestBase {
+ /**
+ * Create a table for the tests.
+ */
+ @BeforeEach
+ public void createTable() {
+ r.db(DB_NAME).tableCreate(tableName).run(conn);
+ }
+
+ /**
+ * Insert a single simple record into the database.
+ */
+ @Test
+ public void insertSimpleRecord() {
+ r.db(DB_NAME).table(tableName)
+ .insert(
+ r.hashMap()
+ .with("name", "Baeldung")
+ )
+ .run(conn);
+ }
+
+ @Test
+ public void insertMap() {
+ r.db(DB_NAME).table(tableName)
+ .insert(
+ Map.of("name", "Baeldung")
+ )
+ .run(conn);
+ }
+
+ @Test
+ public void insertComplex() {
+ r.db(DB_NAME).table(tableName)
+ .insert(
+ r.hashMap()
+ .with("name", "Baeldung")
+ .with("articles", r.array(
+ r.hashMap()
+ .with("name", "String Interpolation in Java")
+ .with("url", "https://www.baeldung.com/java-string-interpolation"),
+ r.hashMap()
+ .with("name", "Access HTTPS REST Service Using Spring RestTemplate")
+ .with("url", "https://www.baeldung.com/spring-resttemplate-secure-https-service")
+ )
+ )
+ )
+ .run(conn);
+ }
+}
diff --git a/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/QueryIntegrationTest.java b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/QueryIntegrationTest.java
new file mode 100644
index 0000000000..263dda9bc6
--- /dev/null
+++ b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/QueryIntegrationTest.java
@@ -0,0 +1,81 @@
+package com.baeldung.rethinkdb;
+
+import com.rethinkdb.net.Result;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static com.rethinkdb.RethinkDB.r;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Some tests demonstrating querying data.
+ */
+public class QueryIntegrationTest extends TestBase {
+ /**
+ * Create a table for the tests.
+ */
+ @BeforeEach
+ public void createTable() {
+ r.db(DB_NAME).tableCreate(tableName).run(conn);
+
+ r.db(DB_NAME).table(tableName)
+ .insert(
+ r.hashMap()
+ .with("id", "article1")
+ .with("name", "String Interpolation in Java")
+ .with("url", "https://www.baeldung.com/java-string-interpolation")
+ ).run(conn);
+ r.db(DB_NAME).table(tableName)
+ .insert(
+ r.hashMap()
+ .with("id", "article2")
+ .with("name", "Access HTTPS REST Service Using Spring RestTemplate")
+ .with("url", "https://www.baeldung.com/spring-resttemplate-secure-https-service")
+ ).run(conn);
+ }
+
+ @Test
+ public void listAll() {
+ Result