diff --git a/README.md b/README.md
index d018783465..d20968b455 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
The "REST with Spring" Classes
==============================
-After 5 months of work, here's the Master Class of REST With Spring:
+Here's the Master Class of REST With Spring (price changes permanently next Friday):
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
And here's the Master Class of Learn Spring Security:
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java b/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java
new file mode 100644
index 0000000000..35d6c8b424
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java
@@ -0,0 +1,21 @@
+package com.baeldung.algorithms.linesintersection;
+
+import java.awt.Point;
+import java.util.Optional;
+
+public class LinesIntersectionService {
+
+ public Optional calculateIntersectionPoint(double m1, double b1, double m2, double b2) {
+
+ if (m1 == m2) {
+ return Optional.empty();
+ }
+
+ double x = (b2 - b1) / (m1 - m2);
+ double y = m1 * x + b1;
+
+ Point point = new Point();
+ point.setLocation(x, y);
+ return Optional.of(point);
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java
index d855f775a8..5d4b265500 100644
--- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java
@@ -87,7 +87,7 @@ public class State {
void randomPlay() {
List availablePositions = this.board.getEmptyPositions();
int totalPossibilities = availablePositions.size();
- int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1));
+ int selectRandom = (int) (Math.random() * totalPossibilities);
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java
index 20f9e992b5..0ad6510e50 100644
--- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java
@@ -65,7 +65,7 @@ public class Node {
public Node getRandomChildNode() {
int noOfPossibleMoves = this.childArray.size();
- int selectRandom = (int) (Math.random() * ((noOfPossibleMoves - 1) + 1));
+ int selectRandom = (int) (Math.random() * noOfPossibleMoves);
return this.childArray.get(selectRandom);
}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java b/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java
new file mode 100644
index 0000000000..2dd1fdcb75
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java
@@ -0,0 +1,35 @@
+package com.baeldung.algorithms.string;
+
+public class EnglishAlphabetLetters {
+
+ public static boolean checkStringForAllTheLetters(String input) {
+ boolean[] visited = new boolean[26];
+
+ int index = 0;
+
+ for (int id = 0; id < input.length(); id++) {
+ if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
+ index = input.charAt(id) - 'a';
+ } else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
+ index = input.charAt(id) - 'A';
+ }
+ visited[index] = true;
+ }
+
+ for (int id = 0; id < 26; id++) {
+ if (!visited[id]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public static boolean checkStringForAllLetterUsingStream(String input) {
+ long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count();
+ return c == 26;
+ }
+
+ public static void main(String[] args) {
+ checkStringForAllLetterUsingStream("intit");
+ }
+}
\ No newline at end of file
diff --git a/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java
similarity index 94%
rename from algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java
index b0218ae23e..2ac7adc3aa 100644
--- a/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
diff --git a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
similarity index 92%
rename from algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
index fa8ecdee77..e819da4b36 100644
--- a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
similarity index 98%
rename from algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
index 68386278fc..bbc4d4f398 100644
--- a/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import org.junit.Test;
diff --git a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java
similarity index 98%
rename from algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java
index e4746b521c..e817d195b3 100644
--- a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import com.baeldung.algorithms.hillclimbing.HillClimbing;
import com.baeldung.algorithms.hillclimbing.State;
diff --git a/algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java
similarity index 99%
rename from algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java
index 01f9ca2f76..2cda0ccb36 100644
--- a/algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup;
import com.baeldung.algorithms.middleelementlookup.Node;
diff --git a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
similarity index 98%
rename from algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
index 99e962773f..fddccfcd9f 100644
--- a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import com.baeldung.algorithms.automata.*;
import org.junit.Test;
diff --git a/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java
similarity index 90%
rename from algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java
index 6ee129ece9..2ce7d75e43 100644
--- a/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
diff --git a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java
similarity index 94%
rename from algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java
index c98a8a53f3..dfe015aad2 100755
--- a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import org.junit.Assert;
diff --git a/algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java
similarity index 95%
rename from algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java
index 74db4236b9..826682d373 100644
--- a/algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms.binarysearch;
+package com.baeldung.algorithms.binarysearch;
import java.util.Arrays;
import java.util.List;
diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java
new file mode 100644
index 0000000000..22371107f3
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java
@@ -0,0 +1,40 @@
+package com.baeldung.algorithms.linesintersection;
+
+import java.awt.Point;
+import java.util.Optional;
+
+import org.junit.Test;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+
+public class LinesIntersectionServiceUnitTest {
+ private LinesIntersectionService service = new LinesIntersectionService();
+
+ @Test
+ public void givenNotParallelLines_whenCalculatePoint_thenPresent() {
+
+ double m1 = 0;
+ double b1 = 0;
+ double m2 = 1;
+ double b2 = -1;
+
+ Optional point = service.calculateIntersectionPoint(m1, b1, m2, b2);
+
+ assertTrue(point.isPresent());
+ assertEquals(point.get().getX(), 1, 0.001);
+ assertEquals(point.get().getY(), 0, 0.001);
+ }
+
+ @Test
+ public void givenParallelLines_whenCalculatePoint_thenEmpty() {
+ double m1 = 1;
+ double b1 = 0;
+ double m2 = 1;
+ double b2 = -1;
+
+ Optional point = service.calculateIntersectionPoint(m1, b1, m2, b2);
+
+ assertFalse(point.isPresent());
+ }
+}
diff --git a/algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java
similarity index 98%
rename from algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java
index edbf21390d..59afed65de 100644
--- a/algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms.mcts;
+package com.baeldung.algorithms.mcts;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
diff --git a/algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java
similarity index 95%
rename from algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java
index c07975bca0..59f0fcf053 100644
--- a/algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms.minimax;
+package com.baeldung.algorithms.minimax;
import org.junit.Before;
import org.junit.Test;
diff --git a/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java
new file mode 100644
index 0000000000..54863cddc8
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.algorithms.string;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class EnglishAlphabetLettersUnitTest {
+
+ @Test
+ void givenString_whenContainsAllCharacter_thenTrue() {
+ String input = "Farmer jack realized that big yellow quilts were expensive";
+ Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(input));
+ }
+
+ @Test
+ void givenString_whenContainsAllCharacter_thenUsingStreamExpectTrue() {
+ String input = "Farmer jack realized that big yellow quilts were expensive";
+ Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllLetterUsingStream(input));
+ }
+
+}
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
index d2219a45f2..7d30c3d1ee 100644
--- a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
@@ -5,29 +5,37 @@ import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.io.IOException;
public class AvroDeSerealizer {
-public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data){
- DatumReader reader = new SpecificDatumReader<>(AvroHttpRequest.class);
- Decoder decoder = null;
- try {
- decoder = DecoderFactory.get().jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
- return reader.read(null, decoder);
- } catch (IOException e) {
- return null;
- }
-}
+ private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
-public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data){
- DatumReader employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
- Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);
- try {
- return employeeReader.read(null, decoder);
- } catch (IOException e) {
+ public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) {
+ DatumReader reader = new SpecificDatumReader<>(AvroHttpRequest.class);
+ Decoder decoder = null;
+ try {
+ decoder = DecoderFactory.get()
+ .jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
+ return reader.read(null, decoder);
+ } catch (IOException e) {
+ logger.error("Deserialization error" + e.getMessage());
+ }
+ return null;
+ }
+
+ public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data) {
+ DatumReader employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
+ Decoder decoder = DecoderFactory.get()
+ .binaryDecoder(data, null);
+ try {
+ return employeeReader.read(null, decoder);
+ } catch (IOException e) {
+ logger.error("Deserialization error" + e.getMessage());
+ }
return null;
}
}
-}
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
index f56c89e201..767b688dea 100644
--- a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
@@ -3,42 +3,48 @@ package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.*;
import org.apache.avro.specific.SpecificDatumWriter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class AvroSerealizer {
-public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request){
- DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
- byte[] data = new byte[0];
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- Encoder jsonEncoder = null;
- try {
- jsonEncoder = EncoderFactory.get().jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
- writer.write(request, jsonEncoder);
- jsonEncoder.flush();
- data = stream.toByteArray();
- } catch (IOException e) {
- data =null;
- }
- return data;
-}
+ private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class);
-public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request){
- DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
- byte[] data = new byte[0];
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- Encoder jsonEncoder = EncoderFactory.get().binaryEncoder(stream,null);
- try {
- writer.write(request, jsonEncoder);
- jsonEncoder.flush();
- data = stream.toByteArray();
- } catch (IOException e) {
- data = null;
+ public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request) {
+ DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
+ byte[] data = new byte[0];
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ Encoder jsonEncoder = null;
+ try {
+ jsonEncoder = EncoderFactory.get()
+ .jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
+ writer.write(request, jsonEncoder);
+ jsonEncoder.flush();
+ data = stream.toByteArray();
+ } catch (IOException e) {
+ logger.error("Serialization error " + e.getMessage());
+ }
+ return data;
}
- return data;
-}
+ public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request) {
+ DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
+ byte[] data = new byte[0];
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ Encoder jsonEncoder = EncoderFactory.get()
+ .binaryEncoder(stream, null);
+ try {
+ writer.write(request, jsonEncoder);
+ jsonEncoder.flush();
+ data = stream.toByteArray();
+ } catch (IOException e) {
+ logger.error("Serialization error " + e.getMessage());
+ }
+
+ return data;
+ }
}
diff --git a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java
index 937a4ae650..ecd15ccbbc 100644
--- a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java
+++ b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java
@@ -24,8 +24,10 @@ public class AvroSerealizerDeSerealizerTest {
serealizer = new AvroSerealizer();
deSerealizer = new AvroDeSerealizer();
- ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder().
- setHostName("localhost").setIpAddress("255.255.255.0").build();
+ ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder()
+ .setHostName("localhost")
+ .setIpAddress("255.255.255.0")
+ .build();
List employees = new ArrayList();
employees.add("James");
@@ -33,43 +35,49 @@ public class AvroSerealizerDeSerealizerTest {
employees.add("David");
employees.add("Han");
- request = AvroHttpRequest.newBuilder().setRequestTime(01l)
- .setActive(Active.YES).setClientIdentifier(clientIdentifier)
- .setEmployeeNames(employees).build();
+ request = AvroHttpRequest.newBuilder()
+ .setRequestTime(01l)
+ .setActive(Active.YES)
+ .setClientIdentifier(clientIdentifier)
+ .setEmployeeNames(employees)
+ .build();
}
@After
public void tearDown() throws Exception {
}
-@Test
-public void WhenSerialized_UsingJSONEncoder_ObjectGetsSerialized(){
- byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
- assertTrue(Objects.nonNull(data));
- assertTrue(data.length > 0);
-}
-
-@Test
-public void WhenSerialized_UsingBinaryEncoder_ObjectGetsSerialized(){
- byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
- assertTrue(Objects.nonNull(data));
- assertTrue(data.length > 0);
-}
-
-@Test
-public void WhenDeserialize_UsingJSONDecoder_ActualAndExpectedObjectsAreEqual(){
- byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
- AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
- assertEquals(actualRequest,request);
- assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
-}
-
-@Test
-public void WhenDeserialize_UsingBinaryecoder_ActualAndExpectedObjectsAreEqual(){
- byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
- AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
- assertEquals(actualRequest,request);
- assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
-}
+ @Test
+ public void WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() {
+ byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
+ assertTrue(Objects.nonNull(data));
+ assertTrue(data.length > 0);
+ }
+
+ @Test
+ public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() {
+ byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
+ assertTrue(Objects.nonNull(data));
+ assertTrue(data.length > 0);
+ }
+
+ @Test
+ public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() {
+ byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
+ AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
+ assertEquals(actualRequest, request);
+ assertTrue(actualRequest.getRequestTime()
+ .equals(request.getRequestTime()));
+ }
+
+ @Test
+ public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() {
+ byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
+ AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
+ assertEquals(actualRequest, request);
+ assertTrue(actualRequest.getRequestTime()
+ .equals(request.getRequestTime()));
+ }
+
}
diff --git a/apache-fop/src/main/resources/logback.xml b/apache-fop/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/apache-fop/src/main/resources/logback.xml
+++ b/apache-fop/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/apache-thrift/pom.xml b/apache-thrift/pom.xml
index 6947cc71bc..b22364cb19 100644
--- a/apache-thrift/pom.xml
+++ b/apache-thrift/pom.xml
@@ -39,6 +39,7 @@
org.codehaus.mojo
build-helper-maven-plugin
+ ${build-helper-maven-plugin.version}
generate-sources
@@ -60,6 +61,7 @@
0.10.0
0.1.11
1.7.12
+ 3.0.0
diff --git a/apache-velocity/src/main/resources/logback.xml b/apache-velocity/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/apache-velocity/src/main/resources/logback.xml
+++ b/apache-velocity/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/aws/pom.xml b/aws/pom.xml
index 176ecaa40d..26bc0c8037 100644
--- a/aws/pom.xml
+++ b/aws/pom.xml
@@ -137,7 +137,7 @@
1.1.0
2.8.0
1.11.290
- 2.8.9
+ 2.21.0
3.8.0
1.11.86
https://s3-us-west-2.amazonaws.com/dynamodb-local/release
diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java
index 8b5fa409c9..930e913109 100644
--- a/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java
+++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java
@@ -1,70 +1,91 @@
package com.baeldung.test.dependencyinjection;
-import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor;
-import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor;
-import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
-import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
-import com.baeldung.dependencyinjection.loggers.TimeLogger;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.within;
+
+import java.text.ParseException;
+import java.time.LocalTime;
+import java.time.temporal.ChronoUnit;
+
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.BeforeClass;
import org.junit.Test;
+import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
+import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
+import com.baeldung.dependencyinjection.loggers.TimeLogger;
+
public class ImageProcessorUnitTest {
-
+
private static ImageFileProcessor imageFileProcessor;
- private static SimpleDateFormat dateFormat;
- private static Calendar calendar;
-
-
+
@BeforeClass
public static void setImageProcessorInstance() {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
- imageFileProcessor = container.select(ImageFileProcessor.class).get();
+ imageFileProcessor = container.select(ImageFileProcessor.class)
+ .get();
container.shutdown();
}
-
- @BeforeClass
- public static void setSimpleDateFormatInstance() {
- dateFormat = new SimpleDateFormat("HH:mm");
- }
-
- @BeforeClass
- public static void setCalendarInstance() {
- calendar = Calendar.getInstance();
- }
-
+
@Test
public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() {
assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class);
assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class);
}
-
+
@Test
- public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() {
- String currentTime = dateFormat.format(calendar.getTime());
- assertThat(imageFileProcessor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png at: " + currentTime);
+ public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() throws ParseException {
+ LocalTime currentTime = LocalTime.now();
+
+ String openFileLog = imageFileProcessor.openFile("file1.png");
+ assertThat(openFileLog).contains("Opening PNG file file1.png at: ");
+
+ LocalTime loggedTime = getLoggedTime(openFileLog);
+ assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
}
-
+
@Test
- public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() {
- String currentTime = dateFormat.format(calendar.getTime());
- assertThat(imageFileProcessor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png at: " + currentTime);
+ public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() throws ParseException {
+ LocalTime currentTime = LocalTime.now();
+
+ String editFileLog = imageFileProcessor.editFile("file1.png");
+ assertThat(editFileLog).contains("Editing PNG file file1.png at: ");
+
+ LocalTime loggedTime = getLoggedTime(editFileLog);
+ assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
}
-
+
@Test
- public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() {
- String currentTime = dateFormat.format(calendar.getTime());
- assertThat(imageFileProcessor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png at: " + currentTime);
+ public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() throws ParseException {
+ LocalTime currentTime = LocalTime.now();
+
+ String writeFileLog = imageFileProcessor.writeFile("file1.png");
+ assertThat(writeFileLog).contains("Writing PNG file file1.png at: ");
+
+ LocalTime loggedTime = getLoggedTime(writeFileLog);
+ assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
}
-
+
@Test
- public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() {
- String currentTime = dateFormat.format(calendar.getTime());
- assertThat(imageFileProcessor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png at: " + currentTime);
+ public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() throws ParseException {
+ LocalTime currentTime = LocalTime.now();
+
+ String saveFileLog = imageFileProcessor.saveFile("file1.png");
+ assertThat(saveFileLog).contains("Saving PNG file file1.png at: ");
+
+ LocalTime loggedTime = getLoggedTime(saveFileLog);
+ assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
+ }
+
+ private LocalTime getLoggedTime(String log) throws ParseException {
+ String logTimeString = log.split("at: ")[1];
+
+ int hour = Integer.valueOf(logTimeString.split(":")[0]);
+ int minutes = Integer.valueOf(logTimeString.split(":")[1]);
+
+ LocalTime loggedTime = LocalTime.of(hour, minutes);
+ return loggedTime;
}
}
\ No newline at end of file
diff --git a/core-java-8/README.md b/core-java-8/README.md
index 6f31a8b886..e23a2a6d1e 100644
--- a/core-java-8/README.md
+++ b/core-java-8/README.md
@@ -9,54 +9,23 @@
- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
-- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
-- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
-- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams)
-- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
-- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany)
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
-- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element)
-- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
-- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api)
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
-- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8)
-- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster)
-- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
-- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
-- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
-- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
-- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
-- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
-- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
-- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
-- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
-- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
-- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
-- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
-- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
-- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
-- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
-- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
-- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
-- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
-- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
-- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
-- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)
diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml
index 7e3b8cb280..fa0d79e405 100644
--- a/core-java-8/pom.xml
+++ b/core-java-8/pom.xml
@@ -89,11 +89,6 @@
vavr
${vavr.version}
-
- one.util
- streamex
- ${streamex.version}
-
joda-time
joda-time
@@ -151,6 +146,7 @@
org.springframework.boot
spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
@@ -176,7 +172,6 @@
1.16.12
0.9.0
1.13
- 0.6.5
2.10
3.6.1
@@ -184,6 +179,6 @@
1.7.0
1.19
1.19
+ 2.0.4.RELEASE
-
-
\ No newline at end of file
+
diff --git a/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java b/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java
new file mode 100644
index 0000000000..46018faf80
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java
@@ -0,0 +1,9 @@
+package com.baeldung.optional;
+
+public class PersonRepository {
+
+ public String findNameById(String id) {
+ return id == null ? null : "Name";
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java b/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java
new file mode 100644
index 0000000000..2513ec0d03
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java
@@ -0,0 +1,23 @@
+package com.baeldung.primitive;
+
+public class BenchmarkRunner {
+
+ public static void main(String[] args) throws Exception {
+ new IntPrimitiveLookup().run();
+ new IntegerWrapperLookup().run();
+ new FloatPrimitiveLookup().run();
+ new FloatWrapperLookup().run();
+ new DoublePrimitiveLookup().run();
+ new DoubleWrapperLookup().run();
+ new ShortPrimitiveLookup().run();
+ new ShortWrapperLookup().run();
+ new BooleanPrimitiveLookup().run();
+ new BooleanWrapperLookup().run();
+ new CharPrimitiveLookup().run();
+ new CharacterWrapperLookup().run();
+ new BytePrimitiveLookup().run();
+ new ByteWrapperLookup().run();
+ new LongPrimitiveLookup().run();
+ new LongWrapperLookup().run();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java
new file mode 100644
index 0000000000..2ad698eba4
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class BooleanPrimitiveLookup extends Lookup {
+
+ private boolean[] elements;
+ private final boolean pivot = false;
+
+ @Setup
+ @Override
+ public void prepare() {
+ elements = new boolean[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = true;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return BooleanPrimitiveLookup.class.getSimpleName();
+ }
+
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java
new file mode 100644
index 0000000000..8d996739a8
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class BooleanWrapperLookup extends Lookup {
+ private Boolean[] elements;
+ private final boolean pivot = false;
+
+ @Override
+ @Setup
+ public void prepare() {
+ elements = new Boolean[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = true;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Boolean pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return BooleanWrapperLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java
new file mode 100644
index 0000000000..73eda5cf5b
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class BytePrimitiveLookup extends Lookup {
+
+ private byte[] elements;
+ private final byte pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ byte common = 1;
+ elements = new byte[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return BytePrimitiveLookup.class.getSimpleName();
+ }
+
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java
new file mode 100644
index 0000000000..23e02315a6
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class ByteWrapperLookup extends Lookup {
+ private Byte[] elements;
+ private final byte pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ byte common = 1;
+ elements = new Byte[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Byte pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return ByteWrapperLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java
new file mode 100644
index 0000000000..a6d4be6206
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class CharPrimitiveLookup extends Lookup {
+
+ private char[] elements;
+ private final char pivot = 'b';
+
+ @Setup
+ @Override
+ public void prepare() {
+ char common = 'a';
+ elements = new char[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return CharPrimitiveLookup.class.getSimpleName();
+ }
+
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java
new file mode 100644
index 0000000000..9509b4a156
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class CharacterWrapperLookup extends Lookup {
+ private Character[] elements;
+ private final char pivot = 'b';
+
+ @Override
+ @Setup
+ public void prepare() {
+ char common = 'a';
+ elements = new Character[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Character pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return CharacterWrapperLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java
new file mode 100644
index 0000000000..f95515a02d
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java
@@ -0,0 +1,42 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class DoublePrimitiveLookup extends Lookup {
+ private double[] elements;
+ private final double pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ double common = 1;
+ elements = new double[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return DoublePrimitiveLookup.class.getSimpleName();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java
new file mode 100644
index 0000000000..671c2ccc29
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class DoubleWrapperLookup extends Lookup {
+ private Double[] elements;
+ private final double pivot = 2d;
+
+ @Override
+ @Setup
+ public void prepare() {
+ double common = 1;
+ elements = new Double[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Double pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return DoubleWrapperLookup.class.getSimpleName();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java
new file mode 100644
index 0000000000..26b58f0053
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java
@@ -0,0 +1,42 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class FloatPrimitiveLookup extends Lookup {
+ private float[] elements;
+ private final float pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ int common = 1;
+ elements = new float[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return FloatPrimitiveLookup.class.getSimpleName();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java
new file mode 100644
index 0000000000..8e75eae3e3
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java
@@ -0,0 +1,43 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class FloatWrapperLookup extends Lookup {
+ private Float[] elements;
+ private final float pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ float common = 1;
+ elements = new Float[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Float pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return FloatWrapperLookup.class.getSimpleName();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java
new file mode 100644
index 0000000000..551163dba2
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class IntPrimitiveLookup extends Lookup {
+
+ private int[] elements;
+ private final int pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ int common = 1;
+ elements = new int[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return IntPrimitiveLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java
new file mode 100644
index 0000000000..f39fb80a0b
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class IntegerWrapperLookup extends Lookup {
+ private Integer[] elements;
+ private final int pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ int common = 1;
+ elements = new Integer[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Integer pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return IntegerWrapperLookup.class.getSimpleName();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java
new file mode 100644
index 0000000000..2f414577da
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java
@@ -0,0 +1,42 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class LongPrimitiveLookup extends Lookup {
+ private long[] elements;
+ private final long pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ long common = 1;
+ elements = new long[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return LongPrimitiveLookup.class.getSimpleName();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java
new file mode 100644
index 0000000000..692a9fd15c
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class LongWrapperLookup extends Lookup{
+ private Long[] elements;
+ private final long pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ long common = 1;
+ elements = new Long[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Long pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return LongWrapperLookup.class.getSimpleName();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java b/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java
new file mode 100644
index 0000000000..3dc7b7655e
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java
@@ -0,0 +1,56 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.results.RunResult;
+import org.openjdk.jmh.runner.Runner;
+import org.openjdk.jmh.runner.RunnerException;
+import org.openjdk.jmh.runner.options.Options;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+import java.util.Collection;
+
+/**
+ * An abstract class that is to be extended by the classes that
+ * perform lookup in the arrays either of Java primitive types or their wrappers.
+ */
+public abstract class Lookup {
+ /**
+ * the array size
+ */
+ final protected int s = 50000000;
+
+ /**
+ * Initialize the array: fill in the array with the same
+ * elements except for the last one.
+ */
+ abstract public void prepare();
+
+ /**
+ * Free the array's reference.
+ */
+ abstract public void clean();
+
+ /**
+ * Find the position of the element that is different from the others.
+ * By construction, it is the last array element.
+ *
+ * @return array's last element index
+ */
+ abstract public int findPosition();
+
+ /**
+ * Get the name of the class that extends this one. It is needed in order
+ * to set up the benchmark.
+ *
+ * @return
+ */
+ abstract public String getSimpleClassName();
+
+ Collection run() throws RunnerException {
+ Options opt = new OptionsBuilder()
+ .include(getSimpleClassName())
+ .forks(1)
+ .build();
+ return new Runner(opt).run();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java
new file mode 100644
index 0000000000..2d2ffbd67b
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class ShortPrimitiveLookup extends Lookup {
+
+ private short[] elements;
+ private final short pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ short common = 1;
+ elements = new short[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return ShortPrimitiveLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java
new file mode 100644
index 0000000000..1c1cd4a345
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class ShortWrapperLookup extends Lookup {
+ private Short[] elements;
+ private final short pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ short common = 1;
+ elements = new Short[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Short pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return ShortWrapperLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java
index 4df3482633..df6c72d346 100644
--- a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java
+++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java
@@ -5,25 +5,22 @@
*/
package com.baeldung.nullsafecollectionstreams;
+import static org.junit.Assert.assertEquals;
+
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
+
import org.junit.Test;
-import static org.junit.Assert.*;
/**
*
* @author Kwaje Anthony
*/
public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
-
- private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance =
- new NullSafeCollectionStreamsUsingJava8OptionalContainer();
+
+ private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = new NullSafeCollectionStreamsUsingJava8OptionalContainer();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
@@ -49,5 +46,5 @@ public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
-
+
}
diff --git a/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java b/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java
new file mode 100644
index 0000000000..4efa625ccd
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.optional;
+
+import org.junit.Test;
+
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertAll;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class PersonRepositoryUnitTest {
+
+ PersonRepository personRepository = new PersonRepository();
+
+ @Test
+ public void whenIdIsNull_thenExceptionIsThrown() {
+ assertThrows(IllegalArgumentException.class,
+ () ->
+ Optional
+ .ofNullable(personRepository.findNameById(null))
+ .orElseThrow(IllegalArgumentException::new));
+ }
+
+ @Test
+ public void whenIdIsNonNull_thenNoExceptionIsThrown() {
+ assertAll(
+ () ->
+ Optional
+ .ofNullable(personRepository.findNameById("id"))
+ .orElseThrow(RuntimeException::new));
+ }
+
+ @Test
+ public void whenIdNonNull_thenReturnsNameUpperCase() {
+ String name = Optional
+ .ofNullable(personRepository.findNameById("id"))
+ .map(String::toUpperCase)
+ .orElseThrow(RuntimeException::new);
+
+ assertEquals("NAME", name);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java
index 1689a5054d..ec20b7794b 100644
--- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java
+++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java
@@ -1,7 +1,6 @@
package com.baeldung.util;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import java.time.Clock;
import java.time.Instant;
@@ -10,8 +9,6 @@ import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
-import org.joda.time.DateTime;
-import org.joda.time.DateTimeUtils;
import org.junit.Test;
public class CurrentDateTimeUnitTest {
diff --git a/core-java-9/README.md b/core-java-9/README.md
index a76dcefc69..6fa2c24f9e 100644
--- a/core-java-9/README.md
+++ b/core-java-9/README.md
@@ -15,10 +15,7 @@
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
- [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional)
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
-- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
-- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
-- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client)
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
@@ -26,3 +23,4 @@
- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)
+- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java b/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java
new file mode 100644
index 0000000000..46c2e688ce
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java
@@ -0,0 +1,15 @@
+package com.baeldung.java9.process;
+
+import java.util.Scanner;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class ChildProcess {
+
+ public static void main(String[] args) {
+ @SuppressWarnings("resource")
+ Scanner input = new Scanner(System.in);
+ Logger log = Logger.getLogger(ChildProcess.class.getName());
+ log.log(Level.INFO, input.nextLine());
+ }
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java b/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java
new file mode 100644
index 0000000000..443847916a
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java
@@ -0,0 +1,16 @@
+package com.baeldung.java9.process;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class OutputStreamExample {
+
+ public static void main(String[] args) {
+ Logger log = Logger.getLogger(OutputStreamExample.class.getName());
+ log.log(Level.INFO, Integer.toString(sum(1,2)));
+ }
+
+ public static int sum(int a, int b) {
+ return a + b;
+ }
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java
new file mode 100644
index 0000000000..8b6ae0b441
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java
@@ -0,0 +1,7 @@
+package com.baeldung.java9.process;
+
+public class ProcessCompilationError {
+ //This method has been written to generate error to display
+ //how process errorStream() can consume error
+ public static void();
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java
new file mode 100644
index 0000000000..74101ba3da
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java
@@ -0,0 +1,110 @@
+package com.baeldung.java9.process;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.util.Optional;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class ProcessUnderstanding {
+
+ public static int compileAndRunJavaProgram() throws IOException {
+ Process process = Runtime.getRuntime()
+ .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
+ process = Runtime.getRuntime()
+ .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
+ BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ int value = Integer.parseInt(output.readLine());
+ return value;
+ }
+
+ public static String getErrorStreamExample() throws IOException {
+ Process process = Runtime.getRuntime()
+ .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
+ BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String errorString = error.readLine();
+ return errorString;
+ }
+
+ public static void creatingNewProcess() throws IOException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ }
+
+ public static int filterProcessWithStreamsInSpecificRangeReturnCount() {
+ return (int) ProcessHandle.allProcesses()
+ .filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
+ .count();
+ }
+
+ public static void destroyingProcessCreatedBySameProcess() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ Thread.sleep(10000);
+ process.destroy();
+ }
+
+ public static void destroyingProcessCreatedByDifferentProcess() {
+ // find out the process id of current running task by checking
+ // task manager in windows and enter the integer value
+ Optional optionalProcessHandle = ProcessHandle.of(5232);
+ ProcessHandle processHandle = optionalProcessHandle.get();
+ processHandle.destroy();
+ }
+
+ public static int waitForExample() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ return process.waitFor();
+ }
+
+ public static int exitValueExample() throws IOException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ process.destroy();
+ return process.exitValue();
+ }
+
+ public static void destroyExample() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ Thread.sleep(10000);
+ process.destroy();
+ }
+
+ public static void destroyForciblyExample() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ Thread.sleep(10000);
+ process.destroy();
+ if (process.isAlive()) {
+ process.destroyForcibly();
+ }
+ }
+
+ public static void outputStreamDemo() throws IOException, InterruptedException {
+ Logger log = Logger.getLogger(ProcessUnderstanding.class.getName());
+ Process pr = Runtime.getRuntime()
+ .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java");
+ final Process process = Runtime.getRuntime()
+ .exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess");
+ try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) {
+ w.write("send to child\n");
+ }
+ new Thread(() -> {
+ try {
+ int c;
+ while ((c = process.getInputStream()
+ .read()) != -1)
+ System.out.write((byte) c);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }).start();
+ // send to child
+ log.log(Level.INFO, "rc=" + process.waitFor());
+ }
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/rangedates/DatesCollectionIteration.java b/core-java-9/src/main/java/com/baeldung/java9/rangedates/DatesCollectionIteration.java
new file mode 100644
index 0000000000..f5ec5d29dc
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/rangedates/DatesCollectionIteration.java
@@ -0,0 +1,24 @@
+package com.baeldung.java9.rangedates;
+
+import java.util.Collection;
+import java.util.Date;
+
+public class DatesCollectionIteration {
+
+ public void iteratingRangeOfDatesJava7(Collection dates) {
+
+ for (Date date : dates) {
+ processDate(date);
+ }
+ }
+
+ public void iteratingRangeOfDatesJava8(Collection dates) {
+ dates.stream()
+ .forEach(this::processDate);
+ }
+
+ private void processDate(Date date) {
+ System.out.println(date);
+ }
+
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/rangedates/RangeDatesIteration.java b/core-java-9/src/main/java/com/baeldung/java9/rangedates/RangeDatesIteration.java
new file mode 100644
index 0000000000..4972036c91
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/rangedates/RangeDatesIteration.java
@@ -0,0 +1,43 @@
+package com.baeldung.java9.rangedates;
+
+import java.time.LocalDate;
+import java.util.Calendar;
+import java.util.Date;
+
+public class RangeDatesIteration {
+
+ public void iterateBetweenDatesJava9(LocalDate startDate, LocalDate endDate) {
+
+ startDate.datesUntil(endDate)
+ .forEach(this::processDate);
+ }
+
+ public void iterateBetweenDatesJava8(LocalDate start, LocalDate end) {
+ for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
+ processDate(date);
+ }
+ }
+
+ public void iterateBetweenDatesJava7(Date start, Date end) {
+ Date current = start;
+
+ while (current.before(end)) {
+ processDate(current);
+
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(current);
+
+ calendar.add(Calendar.DATE, 1);
+
+ current = calendar.getTime();
+ }
+ }
+
+ private void processDate(LocalDate date) {
+ System.out.println(date);
+ }
+
+ private void processDate(Date date) {
+ System.out.println(date);
+ }
+}
diff --git a/core-java-9/src/main/resources/logback.xml b/core-java-9/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/core-java-9/src/main/resources/logback.xml
+++ b/core-java-9/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java
new file mode 100644
index 0000000000..2f61846c1c
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java
@@ -0,0 +1,121 @@
+package com.baeldung.java9.process;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.lang.String;
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+import java.lang.Integer;
+
+import org.junit.jupiter.api.Test;
+
+class ProcessUnderstandingTest {
+
+ @Test
+ public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException {
+ Process process = Runtime.getRuntime()
+ .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
+ process = Runtime.getRuntime()
+ .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
+ BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ int value = Integer.parseInt(output.readLine());
+ assertEquals(3, value);
+ }
+
+ @Test
+ public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException {
+ Process process = Runtime.getRuntime()
+ .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
+ process = Runtime.getRuntime()
+ .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
+ BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ int value = Integer.parseInt(output.readLine());
+ assertEquals(3, value);
+ }
+
+ @Test
+ public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException {
+ Process process = Runtime.getRuntime()
+ .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
+ BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String errorString = error.readLine();
+ assertNotNull(errorString);
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_thenStartSuccessIsAlive() throws IOException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ assertTrue(builder.start().isAlive());
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_whenDestroying_thenProcessNotAlive() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ Thread.sleep(10000);
+ process.destroy();
+ assertFalse(process.isAlive());
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ Thread.sleep(10000);
+ process.destroy();
+ if (process.isAlive()) {
+ process.destroyForcibly();
+ }
+ assertFalse(process.isAlive());
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_checkAlive() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ Thread.sleep(10000);
+ process.destroy();
+ assertFalse(process.isAlive());
+ }
+
+ @Test
+ public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() {
+ Optional optionalProcessHandle = ProcessHandle.of(5232);
+ ProcessHandle processHandle = optionalProcessHandle.get();
+ processHandle.destroy();
+ assertFalse(processHandle.isAlive());
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ assertThat(process.waitFor() >= 0);
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_whenCurrentThreadWaitsAndSubProcessNotTerminated_thenProcessWaitForReturnsFalse() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ assertFalse(process.waitFor(1, TimeUnit.SECONDS));
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_whenCurrentThreadWillNotWaitIndefinitelyforSubProcessToEnd_thenProcessExitValueReturnsGrt0() throws IOException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ assertThat(process.exitValue() >= 0);
+ }
+
+ @Test
+ public void givenRunningProcesses_whenFilterOnProcessIdRange_thenGetSelectedProcessPid() {
+ assertThat(((int) ProcessHandle.allProcesses()
+ .filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
+ .count()) > 0);
+ }
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/rangedates/DatesCollectionIterationUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/rangedates/DatesCollectionIterationUnitTest.java
new file mode 100644
index 0000000000..522b00065e
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/rangedates/DatesCollectionIterationUnitTest.java
@@ -0,0 +1,61 @@
+package com.baeldung.java9.rangedates;
+
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.junit.Test;
+
+public class DatesCollectionIterationUnitTest {
+
+ private Collection localDates = LocalDate.now()
+ .datesUntil(LocalDate.now()
+ .plus(10L, ChronoUnit.DAYS))
+ .collect(Collectors.toList());
+
+ private Collection dates = localDates.stream()
+ .map(localDate -> Date.from(localDate.atStartOfDay(ZoneId.systemDefault())
+ .toInstant()))
+ .collect(Collectors.toList());
+
+ @Test
+ public void givenIteratingListOfDatesJava7_WhenStartTodayAndEnding10DaysAhead() {
+ DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration();
+ Calendar today = Calendar.getInstance();
+ Calendar next10Ahead = (Calendar) today.clone();
+ next10Ahead.add(Calendar.DATE, 10);
+
+ iterateInColleciton.iteratingRangeOfDatesJava7(createRangeDates(today.getTime(), next10Ahead.getTime()));
+ }
+
+ @Test
+ public void givenIteratingListOfDatesJava8_WhenStartTodayAndEnd10DaysAhead() {
+ DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration();
+
+ iterateInColleciton.iteratingRangeOfDatesJava8(dates);
+ }
+
+ private List createRangeDates(Date start, Date end) {
+
+ List dates = new ArrayList<>();
+ Date current = start;
+
+ while (current.before(end)) {
+ dates.add(current);
+
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(current);
+ calendar.add(Calendar.DATE, 1);
+
+ current = calendar.getTime();
+ }
+
+ return dates;
+ }
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/rangedates/RangeDatesIterationUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/rangedates/RangeDatesIterationUnitTest.java
new file mode 100644
index 0000000000..4f5cd17d98
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/rangedates/RangeDatesIterationUnitTest.java
@@ -0,0 +1,48 @@
+package com.baeldung.java9.rangedates;
+
+import java.time.LocalDate;
+import java.time.temporal.ChronoUnit;
+import java.util.Calendar;
+import java.util.Date;
+
+import org.junit.Test;
+
+public class RangeDatesIterationUnitTest {
+
+ @Test
+ public void givenIterateBetweenDatesJava9_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
+ LocalDate start = LocalDate.now();
+ LocalDate end = start.plus(10L, ChronoUnit.DAYS);
+
+ RangeDatesIteration iteration = new RangeDatesIteration();
+
+ iteration.iterateBetweenDatesJava9(start, end);
+ }
+
+ @Test
+ public void givenIterateBetweenDatesJava8_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
+ LocalDate start = LocalDate.now();
+ LocalDate end = start.plus(10L, ChronoUnit.DAYS);
+
+ RangeDatesIteration iteration = new RangeDatesIteration();
+
+ iteration.iterateBetweenDatesJava8(start, end);
+ }
+
+ @Test
+ public void givenIterateBetweenDatesJava7_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
+ Calendar today = Calendar.getInstance();
+ Calendar calendar = Calendar.getInstance();
+ calendar.clear();
+ calendar.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
+ Date start = calendar.getTime();
+
+ calendar.add(Calendar.DATE, 10);
+ Date end = calendar.getTime();
+
+ RangeDatesIteration iteration = new RangeDatesIteration();
+
+ iteration.iterateBetweenDatesJava7(start, end);
+ }
+
+}
diff --git a/core-java-collections/README.md b/core-java-collections/README.md
index 8f5dd137ed..ab13ba7c01 100644
--- a/core-java-collections/README.md
+++ b/core-java-collections/README.md
@@ -36,3 +36,10 @@
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
+- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
+- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
+- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
+- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
+- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
+- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
+- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
diff --git a/core-java-8/src/main/java/com/baeldung/findanelement/Customer.java b/core-java-collections/src/main/java/com/baeldung/findanelement/Customer.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/findanelement/Customer.java
rename to core-java-collections/src/main/java/com/baeldung/findanelement/Customer.java
diff --git a/core-java-8/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java b/core-java-collections/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java
rename to core-java-collections/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java
diff --git a/core-java-8/src/main/java/com/baeldung/hashtable/Word.java b/core-java-collections/src/main/java/com/baeldung/hashtable/Word.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/hashtable/Word.java
rename to core-java-collections/src/main/java/com/baeldung/hashtable/Word.java
diff --git a/core-java-8/src/main/java/com/baeldung/iterators/Iterators.java b/core-java-collections/src/main/java/com/baeldung/iterators/Iterators.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/iterators/Iterators.java
rename to core-java-collections/src/main/java/com/baeldung/iterators/Iterators.java
diff --git a/core-java-8/src/main/java/com/baeldung/list/CopyListService.java b/core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java
similarity index 98%
rename from core-java-8/src/main/java/com/baeldung/list/CopyListService.java
rename to core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java
index 55d5bb9379..5c92d856aa 100644
--- a/core-java-8/src/main/java/com/baeldung/list/CopyListService.java
+++ b/core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java
@@ -1,4 +1,4 @@
-package com.baeldung.list;
+package com.baeldung.java.list;
import java.util.ArrayList;
import java.util.Collections;
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Car.java b/core-java-collections/src/main/java/com/baeldung/java_8_features/Car.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/Car.java
rename to core-java-collections/src/main/java/com/baeldung/java_8_features/Car.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Person.java b/core-java-collections/src/main/java/com/baeldung/java_8_features/Person.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/Person.java
rename to core-java-collections/src/main/java/com/baeldung/java_8_features/Person.java
diff --git a/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java b/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java
new file mode 100644
index 0000000000..9f002c89a2
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java
@@ -0,0 +1,80 @@
+package com.baeldung.collection;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class StreamOperateAndRemoveUnitTest {
+
+ private List- itemList;
+
+ @Before
+ public void setup() {
+
+ itemList = new ArrayList<>();
+ for (int i = 0; i < 10; i++) {
+ itemList.add(new Item(i));
+ }
+ }
+
+ @Test
+ public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() {
+
+ final List
- filteredList = itemList.stream().filter(item -> item.isQualified())
+ .collect(Collectors.toList());
+
+ Assert.assertEquals(5, filteredList.size());
+ }
+
+ @Test
+ public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() {
+
+ final Predicate
- isQualified = item -> item.isQualified();
+ itemList.stream().filter(isQualified).forEach(item -> item.operate());
+ itemList.removeIf(isQualified);
+
+ Assert.assertEquals(5, itemList.size());
+ }
+
+ @Test
+ public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() {
+
+ final List
- operatedList = new ArrayList<>();
+ itemList.stream().filter(item -> item.isQualified()).forEach(item -> {
+ item.operate();
+ operatedList.add(item);
+ });
+ itemList.removeAll(operatedList);
+
+ Assert.assertEquals(5, itemList.size());
+ }
+
+ class Item {
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
+
+ private final int value;
+
+ public Item(final int value) {
+
+ this.value = value;
+ }
+
+ public boolean isQualified() {
+
+ return value % 2 == 0;
+ }
+
+ public void operate() {
+
+ logger.info("Even Number: " + this.value);
+ }
+ }
+}
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java b/core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java b/core-java-collections/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java
similarity index 95%
rename from core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java
index 348747111f..bc1611038c 100644
--- a/core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java
+++ b/core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java
@@ -1,13 +1,17 @@
-package com.baeldung.list;
+package com.baeldung.java.list;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.*;
+import org.junit.Before;
+import org.junit.Test;
public class CopyListServiceUnitTest {
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java
diff --git a/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java
index 09f0bb248c..f2b1bd9d88 100644
--- a/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java
+++ b/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java
@@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
@@ -48,4 +49,14 @@ public class RemoveFirstElementUnitTest {
assertThat(linkedList, not(contains("cat")));
}
+ @Test
+ public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() {
+ String[] stringArray = {"foo", "bar", "baz"};
+
+ String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);
+
+ assertThat(modifiedArray.length, is(2));
+ assertThat(modifiedArray[0], is("bar"));
+ }
+
}
diff --git a/core-java-8/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java
diff --git a/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java b/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java
new file mode 100644
index 0000000000..09ecebe47b
--- /dev/null
+++ b/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java
@@ -0,0 +1,26 @@
+package org.baeldung.java.collections;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import org.junit.Assert;
+import org.junit.Test;
+
+class CollectionsEmpty {
+
+ @Test
+ public void givenArrayList_whenAddingElement_addsNewElement() {
+ ArrayList mutableList = new ArrayList<>();
+ mutableList.add("test");
+
+ Assert.assertEquals(mutableList.size(), 1);
+ Assert.assertEquals(mutableList.get(0), "test");
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() {
+ List immutableList = Collections.emptyList();
+ immutableList.add("test");
+ }
+
+}
diff --git a/core-java-concurrency-collections/.gitignore b/core-java-concurrency-collections/.gitignore
new file mode 100644
index 0000000000..3de4cc647e
--- /dev/null
+++ b/core-java-concurrency-collections/.gitignore
@@ -0,0 +1,26 @@
+*.class
+
+0.*
+
+#folders#
+/target
+/neoDb*
+/data
+/src/main/webapp/WEB-INF/classes
+*/META-INF/*
+.resourceCache
+
+# Packaged files #
+*.jar
+*.war
+*.ear
+
+# Files generated by integration tests
+*.txt
+backup-pom.xml
+/bin/
+/temp
+
+#IntelliJ specific
+.idea/
+*.iml
\ No newline at end of file
diff --git a/core-java-concurrency-collections/README.md b/core-java-concurrency-collections/README.md
new file mode 100644
index 0000000000..b982a91861
--- /dev/null
+++ b/core-java-concurrency-collections/README.md
@@ -0,0 +1,15 @@
+=========
+
+## Core Java Concurrency Collections Examples
+
+### Relevant Articles:
+- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
+- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map)
+- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue)
+- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception)
+- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
+- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
+- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
+- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
+- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
+- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
diff --git a/core-java-concurrency-collections/pom.xml b/core-java-concurrency-collections/pom.xml
new file mode 100644
index 0000000000..5e0a80d33c
--- /dev/null
+++ b/core-java-concurrency-collections/pom.xml
@@ -0,0 +1,94 @@
+
+ 4.0.0
+ com.baeldung
+ core-java-concurrency-collections
+ 0.1.0-SNAPSHOT
+ jar
+ core-java-concurrency-collections
+
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-java
+
+
+
+
+ org.apache.commons
+ commons-collections4
+ ${commons-collections4.version}
+
+
+ commons-io
+ commons-io
+ ${commons-io.version}
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+ org.apache.commons
+ commons-math3
+ ${commons-math3.version}
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+ com.jayway.awaitility
+ awaitility
+ ${avaitility.version}
+ test
+
+
+
+
+ core-java-concurrency-collections
+
+
+ src/main/resources
+ true
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+
+
+ copy-dependencies
+ prepare-package
+
+ copy-dependencies
+
+
+ ${project.build.directory}/libs
+
+
+
+
+
+
+
+
+
+
+ 21.0
+ 3.5
+ 3.6.1
+ 4.1
+ 4.01
+
+ 3.6.1
+ 1.7.0
+
+
+
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java
similarity index 79%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java
index 052136bfe4..842d4e630e 100644
--- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java
+++ b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java
@@ -10,15 +10,18 @@ public class BlockingQueueUsage {
int N_CONSUMERS = Runtime.getRuntime().availableProcessors();
int poisonPill = Integer.MAX_VALUE;
int poisonPillPerProducer = N_CONSUMERS / N_PRODUCERS;
-
+ int mod = N_CONSUMERS % N_PRODUCERS;
BlockingQueue queue = new LinkedBlockingQueue<>(BOUND);
- for (int i = 0; i < N_PRODUCERS; i++) {
+ for (int i = 1; i < N_PRODUCERS; i++) {
new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer)).start();
}
for (int j = 0; j < N_CONSUMERS; j++) {
new Thread(new NumbersConsumer(queue, poisonPill)).start();
}
+
+ new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer+mod)).start();
+
}
}
\ No newline at end of file
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/Event.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/Event.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/Event.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/Event.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Consumer.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Consumer.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Producer.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Producer.java
diff --git a/core-java-concurrency-collections/src/main/resources/logback.xml b/core-java-concurrency-collections/src/main/resources/logback.xml
new file mode 100644
index 0000000000..ec0dc2469a
--- /dev/null
+++ b/core-java-concurrency-collections/src/main/resources/logback.xml
@@ -0,0 +1,19 @@
+
+
+
+
+ web - %date [%thread] %-5level %logger{36} - %message%n
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java
diff --git a/core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java b/core-java-concurrency-collections/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java
rename to core-java-concurrency-collections/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java
diff --git a/out/production/main122/.gitignore b/core-java-concurrency-collections/src/test/resources/.gitignore
similarity index 100%
rename from out/production/main122/.gitignore
rename to core-java-concurrency-collections/src/test/resources/.gitignore
diff --git a/core-java-concurrency/README.md b/core-java-concurrency/README.md
index a16d885b0c..d775d24dff 100644
--- a/core-java-concurrency/README.md
+++ b/core-java-concurrency/README.md
@@ -7,22 +7,12 @@
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future)
-- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch)
-- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map)
-- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue)
-- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception)
-- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
- [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks)
- [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal)
-- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
-- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
-- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
-- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
- [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers)
-- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
- [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables)
diff --git a/core-java-concurrency/src/main/resources/logback.xml b/core-java-concurrency/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/core-java-concurrency/src/main/resources/logback.xml
+++ b/core-java-concurrency/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/core-java-io/pom.xml b/core-java-io/pom.xml
index 35bc43921c..bc71fb8838 100644
--- a/core-java-io/pom.xml
+++ b/core-java-io/pom.xml
@@ -183,6 +183,7 @@
org.springframework.boot
spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
@@ -316,6 +317,7 @@
2.1.0.1
1.19
2.4.5
+ 2.0.4.RELEASE
\ No newline at end of file
diff --git a/core-java-io/src/main/resources/logback.xml b/core-java-io/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/core-java-io/src/main/resources/logback.xml
+++ b/core-java-io/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java
index 47a7973b34..f9a2ce972d 100644
--- a/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java
+++ b/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java
@@ -18,7 +18,7 @@ public class FilenameFilterManualTest {
@BeforeClass
public static void setupClass() {
directory = new File(FilenameFilterManualTest.class.getClassLoader()
- .getResource("testFolder")
+ .getResource("fileNameFilterManualTestFolder")
.getFile());
}
diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java
index 08a4c673cd..6604d75ed1 100644
--- a/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java
+++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java
@@ -1,10 +1,12 @@
package org.baeldung.java.io;
import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.SequenceInputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
@@ -74,6 +76,28 @@ public class JavaXToInputStreamUnitTest {
IOUtils.closeQuietly(targetStream);
}
+ @Test
+ public final void givenUsingPlainJava_whenConvertingFileToDataInputStream_thenCorrect() throws IOException {
+ final File initialFile = new File("src/test/resources/sample.txt");
+ final InputStream targetStream = new DataInputStream(new FileInputStream(initialFile));
+
+ IOUtils.closeQuietly(targetStream);
+ }
+
+ @Test
+ public final void givenUsingPlainJava_whenConvertingFileToSequenceInputStream_thenCorrect() throws IOException {
+ final File initialFile = new File("src/test/resources/sample.txt");
+ final File anotherFile = new File("src/test/resources/anothersample.txt");
+ final InputStream targetStream = new FileInputStream(initialFile);
+ final InputStream anotherTargetStream = new FileInputStream(anotherFile);
+
+ InputStream sequenceTargetStream = new SequenceInputStream(targetStream, anotherTargetStream);
+
+ IOUtils.closeQuietly(targetStream);
+ IOUtils.closeQuietly(anotherTargetStream);
+ IOUtils.closeQuietly(sequenceTargetStream);
+ }
+
@Test
public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
final File initialFile = new File("src/test/resources/sample.txt");
diff --git a/core-java-io/src/test/resources/anothersample.txt b/core-java-io/src/test/resources/anothersample.txt
new file mode 100644
index 0000000000..f06f18ce02
--- /dev/null
+++ b/core-java-io/src/test/resources/anothersample.txt
@@ -0,0 +1 @@
+...Continues
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/testFolder/people.json b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json
similarity index 100%
rename from core-java-io/src/test/resources/testFolder/people.json
rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json
diff --git a/core-java-io/src/test/resources/testFolder/students.json b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json
similarity index 100%
rename from core-java-io/src/test/resources/testFolder/students.json
rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json
diff --git a/core-java-io/src/test/resources/testFolder/teachers.xml b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml
similarity index 100%
rename from core-java-io/src/test/resources/testFolder/teachers.xml
rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml
diff --git a/core-java-io/src/test/resources/testFolder/workers.xml b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml
similarity index 100%
rename from core-java-io/src/test/resources/testFolder/workers.xml
rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml
diff --git a/core-java-persistence/README.md b/core-java-persistence/README.md
new file mode 100644
index 0000000000..08afcadb72
--- /dev/null
+++ b/core-java-persistence/README.md
@@ -0,0 +1,8 @@
+=========
+
+## Core Java Persistence Examples
+
+### Relevant Articles:
+- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
+- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
+- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
\ No newline at end of file
diff --git a/core-java-persistence/pom.xml b/core-java-persistence/pom.xml
index 0cb142c7b8..7279fd763b 100644
--- a/core-java-persistence/pom.xml
+++ b/core-java-persistence/pom.xml
@@ -39,6 +39,16 @@
c3p0
${c3p0.version}
+
+ org.springframework
+ spring-web
+ ${springframework.spring-web.version}
+
+
+ org.springframework.boot
+ spring-boot-starter
+ ${springframework.boot.spring-boot-starter.version}
+
core-java-persistence
@@ -55,5 +65,7 @@
2.4.0
3.2.0
0.9.5.2
+ 1.5.8.RELEASE
+ 4.3.4.RELEASE
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/jdbc/BatchProcessing.java b/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/jdbc/BatchProcessing.java
rename to core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java
diff --git a/core-java/src/main/java/com/baeldung/jdbc/Employee.java b/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/jdbc/Employee.java
rename to core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java
diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java
rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java
diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java
rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java
diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/FilterExample.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/FilterExample.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/jdbcrowset/FilterExample.java
rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/FilterExample.java
diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java
rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java
diff --git a/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java b/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java
similarity index 100%
rename from core-java/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java
rename to core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java
diff --git a/core-java/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java b/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java
similarity index 100%
rename from core-java/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java
rename to core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java
diff --git a/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java b/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java
similarity index 100%
rename from core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java
rename to core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java
diff --git a/core-java-sun/src/main/resources/logback.xml b/core-java-sun/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/core-java-sun/src/main/resources/logback.xml
+++ b/core-java-sun/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/core-java/README.md b/core-java/README.md
index f05b2625e8..e74f6cf815 100644
--- a/core-java/README.md
+++ b/core-java/README.md
@@ -3,18 +3,14 @@
## Core Java Cookbooks and Examples
### Relevant Articles:
-- [Java – Generate Random String](http://www.baeldung.com/java-random-string)
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
-- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
-- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
-- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions)
- [Introduction to Java Generics](http://www.baeldung.com/java-generics)
- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
@@ -37,8 +33,6 @@
- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng)
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
-- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
-- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
@@ -53,44 +47,33 @@
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
-- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
-- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
- [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string)
-- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
- [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error)
-- [Split a String in Java](http://www.baeldung.com/java-split-string)
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
-- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode)
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
-- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
-- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
-- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
-- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class)
- [A Guide to Java Initialization](http://www.baeldung.com/java-initialization)
- [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree)
- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
-- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions)
-- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
- [Nested Classes in Java](http://www.baeldung.com/java-nested-classes)
- [A Guide to Java Loops](http://www.baeldung.com/java-loops)
- [Varargs in Java](http://www.baeldung.com/java-varargs)
@@ -105,16 +88,12 @@
- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java)
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
- [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy)
-- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
-- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
-- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
-- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [The "final" Keyword in Java](http://www.baeldung.com/java-final)
@@ -128,7 +107,6 @@
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure)
-- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Sending Emails with Java](http://www.baeldung.com/java-email)
@@ -139,11 +117,9 @@
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
- [Using Java Assertions](http://www.baeldung.com/java-assert)
- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
-- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding)
- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers)
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
-- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords)
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
- [Singletons in Java](http://www.baeldung.com/java-singleton)
@@ -155,15 +131,11 @@
- [Guide to the this Java Keyword](http://www.baeldung.com/java-this)
- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
-- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day)
-- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time)
-- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case)
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
- [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object)
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
- [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays)
- [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception)
-- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar)
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
- [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream)
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
@@ -171,3 +143,5 @@
- [Guide to Java Instrumentation](http://www.baeldung.com/java-instrumentation)
- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
+- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods)
+- [Differences Between Final, Finally and Finalize in Java](https://www.baeldung.com/java-final-finally-finalize)
diff --git a/core-java/pom.xml b/core-java/pom.xml
index 3f44851f97..477a01375d 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -127,11 +127,6 @@
spring-web
${springframework.spring-web.version}
-
- org.springframework.boot
- spring-boot-starter
- ${springframework.boot.spring-boot-starter.version}
-
com.h2database
h2
@@ -142,11 +137,6 @@
mail
${javax.mail.version}
-
- com.ibm.icu
- icu4j
- ${icu4j.version}
-
org.apache.tika
@@ -532,7 +522,6 @@
2.21.0
4.3.4.RELEASE
- 1.5.8.RELEASE
1.1
1.4.197
diff --git a/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java b/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java
new file mode 100644
index 0000000000..26e5bf0c6b
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java
@@ -0,0 +1,21 @@
+package com.baeldung.classcastexception;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class ClassCastException {
+
+ public static void main(String[] args) {
+
+ String p1 = new String("John");
+ String p2 = new String("Snow");
+ String[] strArray = new String[] { p1, p2 };
+ ArrayList strList = (ArrayList) Arrays.asList(strArray);
+ // To fix the ClassCastException at above line, modify the code as:
+ // List strList = Arrays.asList(strArray);
+ System.out.println("String list: " + strList);
+
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java
new file mode 100644
index 0000000000..d19772072f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java
@@ -0,0 +1,12 @@
+package com.baeldung.constructorsstaticfactorymethods.application;
+
+import com.baeldung.constructorsstaticfactorymethods.entities.User;
+
+public class Application {
+
+ public static void main(String[] args) {
+ User user1 = User.createWithDefaultCountry("John", "john@domain.com");
+ User user2 = User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina");
+ User user3 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java
new file mode 100644
index 0000000000..4036b622c6
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java
@@ -0,0 +1,63 @@
+package com.baeldung.constructorsstaticfactorymethods.entities;
+
+import java.time.LocalTime;
+import java.util.logging.ConsoleHandler;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.logging.SimpleFormatter;
+
+public class User {
+
+ private static volatile User instance = null;
+ private static final Logger LOGGER = Logger.getLogger(User.class.getName());
+ private final String name;
+ private final String email;
+ private final String country;
+
+ public static User createWithDefaultCountry(String name, String email) {
+ return new User(name, email, "Argentina");
+ }
+
+ public static User createWithLoggedInstantiationTime(String name, String email, String country) {
+ setLoggerProperties();
+ LOGGER.log(Level.INFO, "Creating User instance at : {0}", LocalTime.now());
+ return new User(name, email, country);
+ }
+
+ public static User getSingletonInstance(String name, String email, String country) {
+ if (instance == null) {
+ synchronized (User.class) {
+ if (instance == null) {
+ instance = new User(name, email, country);
+ }
+ }
+ }
+ return instance;
+
+ }
+
+ private User(String name, String email, String country) {
+ this.name = name;
+ this.email = email;
+ this.country = country;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public String getCountry() {
+ return country;
+ }
+
+ private static void setLoggerProperties() {
+ ConsoleHandler handler = new ConsoleHandler();
+ handler.setLevel(Level.INFO);
+ handler.setFormatter(new SimpleFormatter());
+ LOGGER.addHandler(handler);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java b/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java
index eb8b733f82..9690648386 100644
--- a/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java
+++ b/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java
@@ -163,7 +163,7 @@ public class Exceptions {
}
}
- public void throwAsGotoAntiPattern() {
+ public void throwAsGotoAntiPattern() throws MyException {
try {
// bunch of code
throw new MyException();
diff --git a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java
index c46c3de65a..524f176e6b 100644
--- a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java
+++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java
@@ -25,7 +25,7 @@ public class User {
if (this.getClass() != o.getClass())
return false;
User user = (User) o;
- return id != user.id && (!name.equals(user.name) && !email.equals(user.email));
+ return id == user.id && (name.equals(user.name) && email.equals(user.email));
}
@Override
@@ -38,4 +38,5 @@ public class User {
return hash;
}
// getters and setters here
+
}
diff --git a/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java b/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java
new file mode 100644
index 0000000000..bebffe52f1
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java
@@ -0,0 +1,45 @@
+/**
+ *
+ */
+package com.baeldung.string;
+
+/**
+ * @author swpraman
+ *
+ */
+public class AppendCharAtPositionX {
+
+ public String addCharUsingCharArray(String str, char ch, int position) {
+ validate(str, position);
+ int len = str.length();
+ char[] updatedArr = new char[len + 1];
+ str.getChars(0, position, updatedArr, 0);
+ updatedArr[position] = ch;
+ str.getChars(position, len, updatedArr, position + 1);
+ return new String(updatedArr);
+ }
+
+ public String addCharUsingSubstring(String str, char ch, int position) {
+ validate(str, position);
+ return str.substring(0, position) + ch + str.substring(position);
+ }
+
+ public String addCharUsingStringBuilder(String str, char ch, int position) {
+ validate(str, position);
+ StringBuilder sb = new StringBuilder(str);
+ sb.insert(position, ch);
+ return sb.toString();
+ }
+
+ private void validate(String str, int position) {
+ if (str == null) {
+ throw new IllegalArgumentException("Str should not be null");
+ }
+ int len = str.length();
+ if (position < 0 || position > len) {
+ throw new IllegalArgumentException("position[" + position + "] should be "
+ + "in the range 0.." + len + " for string " + str);
+ }
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java b/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java
new file mode 100644
index 0000000000..50dbc9c774
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java
@@ -0,0 +1,15 @@
+package com.baeldung.throwsexception;
+
+public class Calculator {
+
+ public double divide(double a, double b) {
+ if (b == 0) {
+ throw new DivideByZeroException("Divider cannot be equal to zero!");
+ }
+ return a/b;
+ }
+
+}
+
+
+
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java b/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java
new file mode 100644
index 0000000000..0b371dcedb
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java
@@ -0,0 +1,9 @@
+package com.baeldung.throwsexception;
+
+public class DataAccessException extends RuntimeException {
+
+ public DataAccessException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java b/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java
new file mode 100644
index 0000000000..4413374c99
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java
@@ -0,0 +1,9 @@
+package com.baeldung.throwsexception;
+
+public class DivideByZeroException extends RuntimeException {
+
+ public DivideByZeroException(String message) {
+ super(message);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/Main.java b/core-java/src/main/java/com/baeldung/throwsexception/Main.java
new file mode 100644
index 0000000000..17fbf5a582
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/Main.java
@@ -0,0 +1,41 @@
+package com.baeldung.throwsexception;
+
+import com.sun.mail.iap.ConnectionException;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.net.SocketException;
+
+public class Main {
+
+ public static void main(String[] args) throws FileNotFoundException {
+ TryCatch tryCatch = new TryCatch();
+
+ try {
+ tryCatch.execute();
+ } catch (ConnectionException | SocketException ex) {
+ System.out.println("IOException");
+ } catch (Exception ex) {
+ System.out.println("General exception");
+ }
+
+ checkedException();
+ checkedExceptionWithThrows();
+ }
+
+ private static void checkedExceptionWithThrows() throws FileNotFoundException {
+ File file = new File("not_existing_file.txt");
+ FileInputStream stream = new FileInputStream(file);
+ }
+
+ private static void checkedException() {
+ File file = new File("not_existing_file.txt");
+ try {
+ FileInputStream stream = new FileInputStream(file);
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java b/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java
new file mode 100644
index 0000000000..7d8345c3c1
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java
@@ -0,0 +1,12 @@
+package com.baeldung.throwsexception;
+
+import java.sql.SQLException;
+import java.util.List;
+
+public class PersonRepository {
+
+ public List findAll() throws SQLException {
+ throw new SQLException();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java b/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java
new file mode 100644
index 0000000000..6bb8b90bf1
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java
@@ -0,0 +1,22 @@
+package com.baeldung.throwsexception;
+
+import java.sql.SQLException;
+
+public class SimpleService {
+
+ private PersonRepository personRepository = new PersonRepository();
+
+ public void wrappingException() {
+ try {
+ personRepository.findAll();
+ } catch (SQLException e) {
+ throw new DataAccessException("SQL Exception", e);
+ }
+ }
+
+ public void runtimeNullPointerException() {
+ String a = null;
+ a.length();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java b/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java
new file mode 100644
index 0000000000..2fd87f124d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java
@@ -0,0 +1,13 @@
+package com.baeldung.throwsexception;
+
+import com.sun.mail.iap.ConnectionException;
+
+import java.net.SocketException;
+
+public class TryCatch {
+
+ public void execute() throws SocketException, ConnectionException, Exception {
+ //code that would throw any of: SocketException, ConnectionException, Exception
+ }
+
+}
diff --git a/core-java/src/main/resources/logback.xml b/core-java/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/core-java/src/main/resources/logback.xml
+++ b/core-java/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/core-java/src/test/java/com/baeldung/array/RemoveFirstElementUnitTest.java b/core-java/src/test/java/com/baeldung/array/RemoveFirstElementUnitTest.java
deleted file mode 100644
index 7d11016d7f..0000000000
--- a/core-java/src/test/java/com/baeldung/array/RemoveFirstElementUnitTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.baeldung.array;
-
-import org.junit.Test;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.LinkedList;
-import java.util.List;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class RemoveFirstElementUnitTest {
-
- @Test
- public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() {
- String[] stringArray = {"foo", "bar", "baz"};
-
- String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);
-
- assertThat(modifiedArray.length).isEqualTo(2);
- assertThat(modifiedArray[0]).isEqualTo("bar");
- }
-
- @Test
- public void givenArrayList_whenRemovingFirstElement_thenListSmallerAndElementRemoved() {
- List stringList = new ArrayList<>(Arrays.asList("foo", "bar", "baz"));
- stringList.remove(0);
-
- assertThat(stringList.size()).isEqualTo(2);
- assertThat(stringList.get(0)).isEqualTo("bar");
- }
-
- @Test
- public void givenLinkedList_whenRemovingFirstElement_thenListSmallerAndElementRemoved() {
- List stringList = new LinkedList<>(Arrays.asList("foo", "bar", "baz"));
- stringList.remove(0);
-
- assertThat(stringList.size()).isEqualTo(2);
- assertThat(stringList.get(0)).isEqualTo("bar");
- }
-
-}
diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java
index 238990f2b4..a34640b58a 100644
--- a/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java
@@ -16,8 +16,11 @@ import org.slf4j.LoggerFactory;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import java.util.List;
+
/**
* Created by madhumita.g on 01-08-2018.
*/
@@ -66,20 +69,18 @@ public class AnimalUnitTest {
int testValue = 3;
animal.makeNoise(testValue);
- verify(mockAppender).doAppend(captorLoggingEvent.capture());
+ verify(mockAppender,times(3)).doAppend(captorLoggingEvent.capture());
- final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+ final List loggingEvents = captorLoggingEvent.getAllValues();
- while (testValue != 0) {
+ for(LoggingEvent loggingEvent : loggingEvents)
+ {
assertThat(loggingEvent.getLevel(), is(Level.INFO));
assertThat(loggingEvent.getFormattedMessage(),
- is("generic animal noise countdown 3\n"
- + "generic animal noise countdown 2\n"
- + "generic animal noise countdown 1\n"));
-
- testValue-=1;
+ is("generic animal noise countdown "+testValue));
+ testValue--;
}
}
diff --git a/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java b/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java
new file mode 100644
index 0000000000..0c0266a111
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.constructorsstaticfactorymethods;
+
+import com.baeldung.constructorsstaticfactorymethods.entities.User;
+import static org.assertj.core.api.Assertions.assertThat;
+import org.junit.Test;
+
+public class UserUnitTest {
+
+ @Test
+ public void givenUserClass_whenCalledcreateWithDefaultCountry_thenCorrect() {
+ assertThat(User.createWithDefaultCountry("John", "john@domain.com")).isInstanceOf(User.class);
+ }
+
+ @Test
+ public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetName_thenCorrect() {
+ User user = User.createWithDefaultCountry("John", "john@domain.com");
+ assertThat(user.getName()).isEqualTo("John");
+ }
+
+ @Test
+ public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetEmail_thenCorrect() {
+ User user = User.createWithDefaultCountry("John", "john@domain.com");
+ assertThat(user.getEmail()).isEqualTo("john@domain.com");
+ }
+
+ @Test
+ public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetCountry_thenCorrect() {
+ User user = User.createWithDefaultCountry("John", "john@domain.com");
+ assertThat(user.getCountry()).isEqualTo("Argentina");
+ }
+
+ @Test
+ public void givenUserInstanceCreatedWithcreateWithInstantiationTime_whenCalledcreateWithInstantiationTime_thenCorrect() {
+ assertThat(User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina")).isInstanceOf(User.class);
+ }
+
+ @Test
+ public void givenUserInstanceCreatedWithgetSingletonIntance_whenCalledgetSingletonInstance_thenCorrect() {
+ User user1 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
+ User user2 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
+ assertThat(user1).isEqualTo(user2);
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
index 35aa07821c..70bfe168dd 100644
--- a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
@@ -75,26 +75,5 @@ public class PizzaUnitTest {
pz.setStatus(Pizza.PizzaStatusEnum.READY);
pz.deliver();
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
- }
-
- @Test
- public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() {
- String pizzaEnumValue = "READY";
- PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
- assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void whenConvertedIntoEnum_thenThrowsException() {
- String pizzaEnumValue = "rEAdY";
- PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() {
- String pizzaEnumValue = "invalid";
- PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
- }
-
-
+ }
}
diff --git a/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java b/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java
index 1e86132116..b3f585cfe4 100644
--- a/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java
@@ -21,7 +21,7 @@ public class ExceptionsUnitTest {
@Test
public void loadAllPlayers() {
assertThatThrownBy(() -> exceptions.loadAllPlayers(""))
- .isInstanceOf(IOException.class);
+ .isInstanceOf(IllegalStateException.class);
}
@Test
@@ -72,12 +72,6 @@ public class ExceptionsUnitTest {
.isInstanceOf(NullPointerException.class);
}
- @Test
- public void throwAsGotoAntiPattern() {
- assertThatThrownBy(() -> exceptions.throwAsGotoAntiPattern())
- .isInstanceOf(MyException.class);
- }
-
@Test
public void getPlayerScoreSwallowingExceptionAntiPatternAlternative2() {
assertThatThrownBy(() -> exceptions.getPlayerScoreSwallowingExceptionAntiPatternAlternative2(""))
diff --git a/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java b/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java
new file mode 100644
index 0000000000..2cdf6145d3
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java
@@ -0,0 +1,110 @@
+/**
+ *
+ */
+package com.baeldung.string;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+/**
+ * @author swpraman
+ *
+ */
+public class AppendCharAtPositionXUnitTest {
+
+ private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX();
+ private String word = "Titanc";
+ private char letter = 'i';
+
+ @Test
+ public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() {
+ assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0));
+ }
+
+ @Test
+ public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() {
+ assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0));
+ }
+
+ @Test
+ public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() {
+ assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0));
+ }
+
+ @Test
+ public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() {
+ assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3));
+ }
+
+ @Test
+ public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() {
+ assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3));
+ }
+
+ @Test
+ public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() {
+ assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3));
+ }
+
+ @Test
+ public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() {
+ assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length()));
+ }
+
+ @Test
+ public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() {
+ assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length()));
+ }
+
+ @Test
+ public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() {
+ assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length()));
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java
new file mode 100644
index 0000000000..ef838ed304
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java
@@ -0,0 +1,17 @@
+package com.baeldung.throwsexception;
+
+import org.junit.Test;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class CalculatorUnitTest {
+
+ @Test
+ public void whenDividerIsZero_thenDivideByZeroExceptionIsThrown() {
+ Calculator calculator = new Calculator();
+
+ assertThrows(DivideByZeroException.class,
+ () -> calculator.divide(10, 0));
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java b/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java
new file mode 100644
index 0000000000..b9a658a960
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.throwsexception;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class SimpleServiceUnitTest {
+
+ SimpleService simpleService = new SimpleService();
+
+ @Test
+ void whenSQLExceptionIsThrown_thenShouldBeRethrownWithWrappedException() {
+ assertThrows(DataAccessException.class,
+ () -> simpleService.wrappingException());
+ }
+
+ @Test
+ void whenCalled_thenNullPointerExceptionIsThrown() {
+ assertThrows(NullPointerException.class,
+ () -> simpleService.runtimeNullPointerException());
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java b/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java
index 6aa59e68d0..22fe0f5e57 100644
--- a/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java
@@ -1,6 +1,7 @@
package com.baeldung.unsafe;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import sun.misc.Unsafe;
@@ -56,6 +57,7 @@ public class UnsafeUnitTest {
}
@Test
+ @Ignore // Uncomment for local
public void givenArrayBiggerThatMaxInt_whenAllocateItOffHeapMemory_thenSuccess() throws NoSuchFieldException, IllegalAccessException {
//given
long SUPER_SIZE = (long) Integer.MAX_VALUE * 2;
diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java
deleted file mode 100644
index bb3abff28d..0000000000
--- a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package org.baeldung.java.enums;
-
-import static junit.framework.TestCase.assertTrue;
-
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.List;
-
-import org.junit.Test;
-
-import com.baeldung.enums.Pizza;
-
-public class PizzaUnitTest {
-
- @Test
- public void givenPizaOrder_whenReady_thenDeliverable() {
- Pizza testPz = new Pizza();
- testPz.setStatus(Pizza.PizzaStatusEnum.READY);
- assertTrue(testPz.isDeliverable());
- }
-
- @Test
- public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
- List pzList = new ArrayList<>();
- Pizza pz1 = new Pizza();
- pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
-
- Pizza pz2 = new Pizza();
- pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
-
- Pizza pz3 = new Pizza();
- pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
-
- Pizza pz4 = new Pizza();
- pz4.setStatus(Pizza.PizzaStatusEnum.READY);
-
- pzList.add(pz1);
- pzList.add(pz2);
- pzList.add(pz3);
- pzList.add(pz4);
-
- List undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
- assertTrue(undeliveredPzs.size() == 3);
- }
-
- @Test
- public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
-
- List pzList = new ArrayList<>();
- Pizza pz1 = new Pizza();
- pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
-
- Pizza pz2 = new Pizza();
- pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
-
- Pizza pz3 = new Pizza();
- pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
-
- Pizza pz4 = new Pizza();
- pz4.setStatus(Pizza.PizzaStatusEnum.READY);
-
- pzList.add(pz1);
- pzList.add(pz2);
- pzList.add(pz3);
- pzList.add(pz4);
-
- EnumMap> map = Pizza.groupPizzaByStatus(pzList);
- assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
- assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
- assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
- }
-
- @Test
- public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
- Pizza pz = new Pizza();
- pz.setStatus(Pizza.PizzaStatusEnum.READY);
- pz.deliver();
- assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
- }
-
-}
diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml
index a86359c02f..6fdc7c7c1a 100644
--- a/core-kotlin/pom.xml
+++ b/core-kotlin/pom.xml
@@ -3,69 +3,24 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-kotlin
- 1.0-SNAPSHOT
jar
com.baeldung
- parent-modules
+ parent-kotlin
1.0.0-SNAPSHOT
+ ../parent-kotlin
- jcenter
- http://jcenter.bintray.com
-
-
- kotlin-ktor
- https://dl.bintray.com/kotlin/ktor/
+ exposed
+ exposed
+ https://dl.bintray.com/kotlin/exposed
-
- org.apache.commons
- commons-math3
- ${commons-math3.version}
-
-
- org.junit.platform
- junit-platform-runner
- ${junit.platform.version}
- test
-
-
- org.jetbrains.kotlin
- kotlin-stdlib
- ${kotlin-stdlib.version}
-
-
- org.jetbrains.kotlin
- kotlin-stdlib-jdk8
- ${kotlin-stdlib.version}
-
-
- khttp
- khttp
- ${khttp.version}
-
-
- org.jetbrains.kotlin
- kotlin-test-junit
- ${kotlin-test-junit.version}
- test
-
-
- org.jetbrains.kotlin
- kotlin-reflect
- ${kotlin-reflect.version}
-
-
- org.jetbrains.kotlinx
- kotlinx-coroutines-core
- ${kotlinx.version}
-
org.jetbrains.spek
spek-api
@@ -84,6 +39,22 @@
1.1.5
test
+
+ org.apache.commons
+ commons-math3
+ ${commons-math3.version}
+
+
+ org.junit.platform
+ junit-platform-runner
+ ${junit.platform.version}
+ test
+
+
+ khttp
+ khttp
+ ${khttp.version}
+
com.nhaarman
mockito-kotlin
@@ -107,129 +78,18 @@
${klaxon.version}
- io.ktor
- ktor-server-netty
- ${ktor.io.version}
+ org.jetbrains.exposed
+ exposed
+ ${exposed.version}
- io.ktor
- ktor-gson
- ${ktor.io.version}
-
-
- ch.qos.logback
- logback-classic
- 1.2.1
- test
+ com.h2database
+ h2
+ ${h2database.version}
-
-
-
- org.jetbrains.kotlin
- kotlin-maven-plugin
- ${kotlin-maven-plugin.version}
-
-
- compile
-
- compile
-
-
-
- ${project.basedir}/src/main/kotlin
- ${project.basedir}/src/main/java
-
-
-
-
- test-compile
-
- test-compile
-
-
-
- ${project.basedir}/src/test/kotlin
- ${project.basedir}/src/test/java
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
-
- ${java.version}
-
-
-
-
- default-compile
- none
-
-
-
- default-testCompile
- none
-
-
- java-compile
- compile
-
- compile
-
-
-
- java-test-compile
- test-compile
-
- testCompile
-
-
-
-
-
- maven-failsafe-plugin
- ${maven-failsafe-plugin.version}
-
-
- org.junit.platform
- junit-platform-surefire-provider
- ${junit.platform.version}
-
-
-
-
- junit5
-
- integration-test
- verify
-
-
-
- **/*Test5.java
-
-
-
-
-
-
-
-
- UTF-8
- 1.2.60
- 1.2.60
- 1.2.60
- 1.2.60
- 0.22.5
- 0.9.2
1.5.0
4.1.0
3.0.4
@@ -238,6 +98,8 @@
1.1.1
5.2.0
3.10.0
+ 1.4.197
+ 0.10.4
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt
index 7d10d849b9..1384cd9937 100644
--- a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt
+++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt
@@ -1,39 +1,22 @@
package com.baeldung.builder
-class FoodOrder private constructor(builder: FoodOrder.Builder) {
-
- val bread: String?
- val condiments: String?
- val meat: String?
- val fish: String?
-
- init {
- this.bread = builder.bread
- this.condiments = builder.condiments
- this.meat = builder.meat
- this.fish = builder.fish
- }
-
- class Builder {
-
- var bread: String? = null
- private set
- var condiments: String? = null
- private set
- var meat: String? = null
- private set
- var fish: String? = null
- private set
+class FoodOrder(
+ val bread: String?,
+ val condiments: String?,
+ val meat: String?,
+ val fish: String?
+) {
+ data class Builder(
+ var bread: String? = null,
+ var condiments: String? = null,
+ var meat: String? = null,
+ var fish: String? = null) {
fun bread(bread: String) = apply { this.bread = bread }
-
fun condiments(condiments: String) = apply { this.condiments = condiments }
-
fun meat(meat: String) = apply { this.meat = meat }
-
fun fish(fish: String) = apply { this.fish = fish }
-
- fun build() = FoodOrder(this)
-
+ fun build() = FoodOrder(bread, condiments, meat, fish)
}
}
+
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt
index 6e20cf51b9..0e4219b40e 100644
--- a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt
+++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt
@@ -1,7 +1,7 @@
package com.baeldung.builder
data class FoodOrderNamed(
- val bread: String? = null,
- val condiments: String? = null,
- val meat: String? = null,
- val fish: String? = null)
+ val bread: String? = null,
+ val condiments: String? = null,
+ val meat: String? = null,
+ val fish: String? = null)
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt
new file mode 100644
index 0000000000..cc348e3fbf
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt
@@ -0,0 +1,9 @@
+package com.baeldung.builder
+
+fun main(args: Array) {
+ FoodOrder.Builder()
+ .bread("bread")
+ .condiments("condiments")
+ .meat("meat")
+ .fish("bread").let { println(it) }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt
index 54fafdb3e1..d724933654 100644
--- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt
@@ -103,7 +103,7 @@ class CoroutinesTest {
//given
val job = launch(CommonPool) {
while (isActive) {
- println("is working")
+ //println("is working")
}
}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt
new file mode 100644
index 0000000000..29fa18ef7a
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt
@@ -0,0 +1,333 @@
+package com.baeldung.kotlin.exposed
+
+import org.jetbrains.exposed.dao.*
+import org.jetbrains.exposed.sql.*
+import org.jetbrains.exposed.sql.transactions.TransactionManager
+import org.jetbrains.exposed.sql.transactions.transaction
+import org.junit.Test
+import java.sql.DriverManager
+import kotlin.test.*
+
+class ExposedTest {
+
+ @Test
+ fun whenH2Database_thenConnectionSuccessful() {
+ val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ transaction {
+ assertEquals(1.4.toBigDecimal(), database.version)
+ assertEquals("h2", database.vendor)
+ }
+ }
+
+ @Test
+ fun whenH2DatabaseWithCredentials_thenConnectionSuccessful() {
+ Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver", user = "myself", password = "secret")
+ }
+
+ @Test
+ fun whenH2DatabaseWithManualConnection_thenConnectionSuccessful() {
+ var connected = false
+ Database.connect({ connected = true; DriverManager.getConnection("jdbc:h2:mem:test;MODE=MySQL") })
+ assertEquals(false, connected)
+ transaction {
+ addLogger(StdOutSqlLogger)
+ assertEquals(false, connected)
+ SchemaUtils.create(Cities)
+ assertEquals(true, connected)
+ }
+ }
+
+ @Test
+ fun whenManualCommit_thenOk() {
+ Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ transaction {
+ assertTrue(this is Transaction)
+ commit()
+ commit()
+ commit()
+ }
+ }
+
+ @Test
+ fun whenInsert_thenGeneratedKeys() {
+ Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ transaction {
+ SchemaUtils.create(StarWarsFilms)
+ val id = StarWarsFilms.insertAndGetId {
+ it[name] = "The Last Jedi"
+ it[sequelId] = 8
+ it[director] = "Rian Johnson"
+ }
+ assertEquals(1, id.value)
+ val insert = StarWarsFilms.insert {
+ it[name] = "The Force Awakens"
+ it[sequelId] = 7
+ it[director] = "J.J. Abrams"
+ }
+ assertEquals(2, insert[StarWarsFilms.id]?.value)
+ val selectAll = StarWarsFilms.selectAll()
+ selectAll.forEach {
+ assertTrue { it[StarWarsFilms.sequelId] >= 7 }
+ }
+ StarWarsFilms.slice(StarWarsFilms.name, StarWarsFilms.director).selectAll()
+ .forEach {
+ assertTrue { it[StarWarsFilms.name].startsWith("The") }
+ }
+ val select = StarWarsFilms.select { (StarWarsFilms.director like "J.J.%") and (StarWarsFilms.sequelId eq 7) }
+ assertEquals(1, select.count())
+ StarWarsFilms.update ({ StarWarsFilms.sequelId eq 8 }) {
+ it[name] = "Episode VIII – The Last Jedi"
+ with(SqlExpressionBuilder) {
+ it.update(StarWarsFilms.sequelId, StarWarsFilms.sequelId + 1)
+ }
+ }
+ }
+ }
+
+ @Test
+ fun whenForeignKey_thenAutoJoin() {
+ Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ transaction {
+ addLogger(StdOutSqlLogger)
+ SchemaUtils.create(StarWarsFilms, Players)
+ StarWarsFilms.insert {
+ it[name] = "The Last Jedi"
+ it[sequelId] = 8
+ it[director] = "Rian Johnson"
+ }
+ StarWarsFilms.insert {
+ it[name] = "The Force Awakens"
+ it[sequelId] = 7
+ it[director] = "J.J. Abrams"
+ }
+ Players.insert {
+ it[name] = "Mark Hamill"
+ it[sequelId] = 7
+ }
+ Players.insert {
+ it[name] = "Mark Hamill"
+ it[sequelId] = 8
+ }
+ val simpleInnerJoin = (StarWarsFilms innerJoin Players).selectAll()
+ assertEquals(2, simpleInnerJoin.count())
+ simpleInnerJoin.forEach {
+ assertNotNull(it[StarWarsFilms.name])
+ assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
+ assertEquals("Mark Hamill", it[Players.name])
+ }
+ val innerJoinWithCondition = (StarWarsFilms innerJoin Players)
+ .select { StarWarsFilms.sequelId eq Players.sequelId }
+ assertEquals(2, innerJoinWithCondition.count())
+ innerJoinWithCondition.forEach {
+ assertNotNull(it[StarWarsFilms.name])
+ assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
+ assertEquals("Mark Hamill", it[Players.name])
+ }
+ val complexInnerJoin = Join(StarWarsFilms, Players, joinType = JoinType.INNER, onColumn = StarWarsFilms.sequelId, otherColumn = Players.sequelId, additionalConstraint = {
+ StarWarsFilms.sequelId eq 8
+ }).selectAll()
+ assertEquals(1, complexInnerJoin.count())
+ complexInnerJoin.forEach {
+ assertNotNull(it[StarWarsFilms.name])
+ assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
+ assertEquals("Mark Hamill", it[Players.name])
+ }
+
+ }
+ }
+
+ @Test
+ fun whenJoinWithAlias_thenFun() {
+ Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ transaction {
+ addLogger(StdOutSqlLogger)
+ SchemaUtils.create(StarWarsFilms, Players)
+ StarWarsFilms.insert {
+ it[name] = "The Last Jedi"
+ it[sequelId] = 8
+ it[director] = "Rian Johnson"
+ }
+ StarWarsFilms.insert {
+ it[name] = "The Force Awakens"
+ it[sequelId] = 7
+ it[director] = "J.J. Abrams"
+ }
+ val sequel = StarWarsFilms.alias("sequel")
+ Join(StarWarsFilms, sequel,
+ additionalConstraint = { sequel[StarWarsFilms.sequelId] eq StarWarsFilms.sequelId + 1 })
+ .selectAll().forEach {
+ assertEquals(it[sequel[StarWarsFilms.sequelId]], it[StarWarsFilms.sequelId] + 1)
+ }
+ }
+ }
+
+ @Test
+ fun whenEntity_thenDAO() {
+ val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ val connection = database.connector.invoke() //Keep a connection open so the DB is not destroyed after the first transaction
+ val inserted = transaction {
+ addLogger(StdOutSqlLogger)
+ SchemaUtils.create(StarWarsFilms, Players)
+ val theLastJedi = StarWarsFilm.new {
+ name = "The Last Jedi"
+ sequelId = 8
+ director = "Rian Johnson"
+ }
+ assertFalse(TransactionManager.current().entityCache.inserts.isEmpty())
+ assertEquals(1, theLastJedi.id.value) //Reading this causes a flush
+ assertTrue(TransactionManager.current().entityCache.inserts.isEmpty())
+ theLastJedi
+ }
+ transaction {
+ val theLastJedi = StarWarsFilm.findById(1)
+ assertNotNull(theLastJedi)
+ assertEquals(inserted.id, theLastJedi?.id)
+ }
+ connection.close()
+ }
+
+ @Test
+ fun whenManyToOne_thenNavigation() {
+ val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ val connection = database.connector.invoke()
+ transaction {
+ addLogger(StdOutSqlLogger)
+ SchemaUtils.create(StarWarsFilms, Players, Users, UserRatings)
+ val theLastJedi = StarWarsFilm.new {
+ name = "The Last Jedi"
+ sequelId = 8
+ director = "Rian Johnson"
+ }
+ val someUser = User.new {
+ name = "Some User"
+ }
+ val rating = UserRating.new {
+ value = 9
+ user = someUser
+ film = theLastJedi
+ }
+ assertEquals(theLastJedi, rating.film)
+ assertEquals(someUser, rating.user)
+ assertEquals(rating, theLastJedi.ratings.first())
+ }
+ transaction {
+ val theLastJedi = StarWarsFilm.find { StarWarsFilms.sequelId eq 8 }.first()
+ val ratings = UserRating.find { UserRatings.film eq theLastJedi.id }
+ assertEquals(1, ratings.count())
+ val rating = ratings.first()
+ assertEquals("Some User", rating.user.name)
+ assertEquals(rating, theLastJedi.ratings.first())
+ UserRating.new {
+ value = 8
+ user = rating.user
+ film = theLastJedi
+ }
+ assertEquals(2, theLastJedi.ratings.count())
+ }
+ connection.close()
+ }
+
+ @Test
+ fun whenManyToMany_thenAssociation() {
+ val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ val connection = database.connector.invoke()
+ val film = transaction {
+ SchemaUtils.create(StarWarsFilms)
+ StarWarsFilm.new {
+ name = "The Last Jedi"
+ sequelId = 8
+ director = "Rian Johnson"
+ }
+ }
+
+ val actor = transaction {
+ SchemaUtils.create(Actors)
+ Actor.new {
+ firstname = "Daisy"
+ lastname = "Ridley"
+ }
+ }
+
+ transaction {
+ SchemaUtils.create(StarWarsFilmActors)
+ film.actors = SizedCollection(listOf(actor))
+ }
+ connection.close()
+ }
+
+}
+
+object Cities: IntIdTable() {
+ val name = varchar("name", 50)
+}
+
+object StarWarsFilms_Simple : Table() {
+ val id = integer("id").autoIncrement().primaryKey()
+ val sequelId = integer("sequel_id").uniqueIndex()
+ val name = varchar("name", 50)
+ val director = varchar("director", 50)
+}
+
+object StarWarsFilms : IntIdTable() {
+ val sequelId = integer("sequel_id").uniqueIndex()
+ val name = varchar("name", 50)
+ val director = varchar("director", 50)
+}
+
+object Players : Table() {
+ //val sequelId = integer("sequel_id").uniqueIndex().references(StarWarsFilms.sequelId)
+ val sequelId = reference("sequel_id", StarWarsFilms.sequelId).uniqueIndex()
+ //val filmId = reference("film_id", StarWarsFilms).nullable()
+ val name = varchar("name", 50)
+}
+
+class StarWarsFilm(id: EntityID) : Entity(id) {
+ companion object : EntityClass(StarWarsFilms)
+
+ var sequelId by StarWarsFilms.sequelId
+ var name by StarWarsFilms.name
+ var director by StarWarsFilms.director
+ var actors by Actor via StarWarsFilmActors
+ val ratings by UserRating referrersOn UserRatings.film
+}
+
+object Users: IntIdTable() {
+ val name = varchar("name", 50)
+}
+
+object UserRatings: IntIdTable() {
+ val value = long("value")
+ val film = reference("film", StarWarsFilms)
+ val user = reference("user", Users)
+}
+
+class User(id: EntityID): IntEntity(id) {
+ companion object : IntEntityClass(Users)
+
+ var name by Users.name
+}
+
+class UserRating(id: EntityID): IntEntity(id) {
+ companion object : IntEntityClass(UserRatings)
+
+ var value by UserRatings.value
+ var film by StarWarsFilm referencedOn UserRatings.film
+ var user by User referencedOn UserRatings.user
+}
+
+object Actors: IntIdTable() {
+ val firstname = varchar("firstname", 50)
+ val lastname = varchar("lastname", 50)
+}
+
+class Actor(id: EntityID): IntEntity(id) {
+ companion object : IntEntityClass(Actors)
+
+ var firstname by Actors.firstname
+ var lastname by Actors.lastname
+}
+
+object StarWarsFilmActors : Table() {
+ val starWarsFilm = reference("starWarsFilm", StarWarsFilms).primaryKey(0)
+ val actor = reference("actor", Actors).primaryKey(1)
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt
new file mode 100644
index 0000000000..2956a35f8a
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt
@@ -0,0 +1,55 @@
+
+import org.junit.jupiter.api.Test
+import java.util.concurrent.ThreadLocalRandom
+import kotlin.test.assertTrue
+
+class RandomNumberTest {
+
+ @Test
+ fun whenRandomNumberWithJavaUtilMath_thenResultIsBetween0And1() {
+ val randomNumber = Math.random()
+ assertTrue { randomNumber >=0 }
+ assertTrue { randomNumber <= 1 }
+ }
+
+ @Test
+ fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInDefaultRanges() {
+ val randomDouble = ThreadLocalRandom.current().nextDouble()
+ val randomInteger = ThreadLocalRandom.current().nextInt()
+ val randomLong = ThreadLocalRandom.current().nextLong()
+ assertTrue { randomDouble >= 0 }
+ assertTrue { randomDouble <= 1 }
+ assertTrue { randomInteger >= Integer.MIN_VALUE }
+ assertTrue { randomInteger <= Integer.MAX_VALUE }
+ assertTrue { randomLong >= Long.MIN_VALUE }
+ assertTrue { randomLong <= Long.MAX_VALUE }
+ }
+
+ @Test
+ fun whenRandomNumberWithKotlinJSMath_thenResultIsBetween0And1() {
+ val randomDouble = Math.random()
+ assertTrue { randomDouble >=0 }
+ assertTrue { randomDouble <= 1 }
+ }
+
+ @Test
+ fun whenRandomNumberWithKotlinNumberRange_thenResultInGivenRange() {
+ val randomInteger = (1..12).shuffled().first()
+ assertTrue { randomInteger >= 1 }
+ assertTrue { randomInteger <= 12 }
+ }
+
+ @Test
+ fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInGivenRanges() {
+ val randomDouble = ThreadLocalRandom.current().nextDouble(1.0, 10.0)
+ val randomInteger = ThreadLocalRandom.current().nextInt(1, 10)
+ val randomLong = ThreadLocalRandom.current().nextLong(1, 10)
+ assertTrue { randomDouble >= 1 }
+ assertTrue { randomDouble <= 10 }
+ assertTrue { randomInteger >= 1 }
+ assertTrue { randomInteger <= 10 }
+ assertTrue { randomLong >= 1 }
+ assertTrue { randomLong <= 10 }
+ }
+
+}
\ No newline at end of file
diff --git a/couchbase/src/main/resources/logback.xml b/couchbase/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/couchbase/src/main/resources/logback.xml
+++ b/couchbase/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/couchbase/src/test/resources/logback.xml b/couchbase/src/test/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/couchbase/src/test/resources/logback.xml
+++ b/couchbase/src/test/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
index e3179dca32..f435e41afa 100644
--- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
+++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
@@ -57,7 +57,7 @@ public class BinaryTree {
}
public void delete(int value) {
- deleteRecursive(root, value);
+ root = deleteRecursive(root, value);
}
private Node deleteRecursive(Node current, int value) {
diff --git a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
similarity index 90%
rename from data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java
rename to data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
index 99e656fe28..f81247b74d 100644
--- a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java
+++ b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
@@ -6,7 +6,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
-public class BinaryTreeTest {
+public class BinaryTreeUnitTest {
@Test
public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() {
@@ -70,6 +70,17 @@ public class BinaryTreeTest {
assertEquals(initialSize, bt.getSize());
}
+ @Test
+ public void it_deletes_the_root() {
+ int value = 12;
+ BinaryTree bt = new BinaryTree();
+ bt.add(value);
+
+ assertTrue(bt.containsNode(value));
+ bt.delete(value);
+ assertFalse(bt.containsNode(value));
+ }
+
@Test
public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() {
diff --git a/data-structures/src/test/java/com/baeldung/trie/TrieTest.java b/data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java
similarity index 98%
rename from data-structures/src/test/java/com/baeldung/trie/TrieTest.java
rename to data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java
index 6f7073651e..bf9555315c 100644
--- a/data-structures/src/test/java/com/baeldung/trie/TrieTest.java
+++ b/data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java
@@ -6,7 +6,7 @@ import org.junit.jupiter.api.Assertions;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-public class TrieTest {
+public class TrieUnitTest {
@Test
public void whenEmptyTrie_thenNoElements() {
diff --git a/disruptor/pom.xml b/disruptor/pom.xml
index 6f3a8d9bfd..d3cef3bd9b 100644
--- a/disruptor/pom.xml
+++ b/disruptor/pom.xml
@@ -112,6 +112,7 @@
com.jolira
onejar-maven-plugin
+ ${onejar-maven-plugin.version}
@@ -138,6 +139,7 @@
2.4.3
3.0.2
+ 1.4.4
\ No newline at end of file
diff --git a/ethereum/pom.xml b/ethereum/pom.xml
index f07ed2c6a0..bd1bacb221 100644
--- a/ethereum/pom.xml
+++ b/ethereum/pom.xml
@@ -184,6 +184,7 @@
org.springframework.boot
spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
org.apache.maven.plugins
@@ -213,7 +214,7 @@
3.3.1
5.0.5.RELEASE
1.5.6.RELEASE
- 1.10.19
+ 2.21.0
2.5.0
1.3
2.9.3
@@ -224,6 +225,7 @@
4.12
1.2.3
1.7.25
+ 2.0.4.RELEASE
diff --git a/flyway/src/main/resources/logback.xml b/flyway/src/main/resources/logback.xml
index 7f4aa46e0d..56af2d397e 100644
--- a/flyway/src/main/resources/logback.xml
+++ b/flyway/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/gson/src/main/java/org/baeldung/gson/entities/User.java b/gson/src/main/java/org/baeldung/gson/entities/User.java
new file mode 100644
index 0000000000..b413f3300e
--- /dev/null
+++ b/gson/src/main/java/org/baeldung/gson/entities/User.java
@@ -0,0 +1,19 @@
+package org.baeldung.gson.entities;
+
+public class User {
+
+ private int id;
+ private String name;
+ private transient String nationality;
+
+ public User(int id, String name, String nationality) {
+ this.id = id;
+ this.name = name;
+ this.nationality = nationality;
+ }
+
+ public User(int id, String name) {
+ this(id, name, null);
+ }
+
+}
diff --git a/gson/src/main/resources/logback.xml b/gson/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/gson/src/main/resources/logback.xml
+++ b/gson/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java b/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java
new file mode 100644
index 0000000000..f6a8de080c
--- /dev/null
+++ b/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java
@@ -0,0 +1,43 @@
+package org.baeldung.gson.serialization.test;
+
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.Writer;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
+import org.baeldung.gson.entities.User;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+@RunWith(Parameterized.class)
+public class JsonFileUnitTest {
+
+ @Parameter
+ public Object object;
+
+ @Parameters
+ public static Object[] data() {
+ return new Object[] { 123.45, new User(1, "Tom", "American") };
+ }
+
+ @Test
+ public void givenProperData_whenStoredInFile_shouldSaveJsonSuccessfully() {
+ String filePath = "target/output.json";
+ try (Writer writer = new FileWriter(filePath)) {
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ gson.toJson(object, writer);
+ Assert.assertTrue(Files.exists(Paths.get(filePath)));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/guava/src/main/resources/logback.xml b/guava/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/guava/src/main/resources/logback.xml
+++ b/guava/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/guest/core-kotlin/.gitignore b/guest/core-kotlin/.gitignore
new file mode 100644
index 0000000000..0c017e8f8c
--- /dev/null
+++ b/guest/core-kotlin/.gitignore
@@ -0,0 +1,14 @@
+/bin/
+
+#ignore gradle
+.gradle/
+
+
+#ignore build and generated files
+build/
+node/
+out/
+
+#ignore installed node modules and package lock file
+node_modules/
+package-lock.json
diff --git a/guest/core-kotlin/pom.xml b/guest/core-kotlin/pom.xml
new file mode 100644
index 0000000000..6b189143a4
--- /dev/null
+++ b/guest/core-kotlin/pom.xml
@@ -0,0 +1,199 @@
+
+
+ 4.0.0
+ core-kotlin
+ 1.0-SNAPSHOT
+ com.stackify
+ jar
+
+
+
+ jcenter
+ http://jcenter.bintray.com
+
+
+
+
+
+ org.junit.platform
+ junit-platform-runner
+ ${junit.platform.version}
+ test
+
+
+ org.jetbrains.kotlin
+ kotlin-stdlib
+ ${kotlin-stdlib.version}
+
+
+ org.jetbrains.kotlin
+ kotlin-stdlib-jdk8
+ ${kotlin-stdlib.version}
+
+
+ org.jetbrains.kotlin
+ kotlin-test-junit
+ ${kotlin-test-junit.version}
+ test
+
+
+ org.jetbrains.kotlin
+ kotlin-reflect
+ ${kotlin-reflect.version}
+
+
+ org.jetbrains.spek
+ spek-api
+ 1.1.5
+ test
+
+
+ org.jetbrains.spek
+ spek-subject-extension
+ 1.1.5
+ test
+
+
+ org.jetbrains.spek
+ spek-junit-platform-engine
+ 1.1.5
+ test
+
+
+ com.nhaarman
+ mockito-kotlin
+ ${mockito-kotlin.version}
+ test
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+ ${maven-failsafe-plugin.version}
+ test
+
+
+ org.jetbrains.kotlin
+ kotlin-maven-plugin
+ ${kotlin-maven-plugin.version}
+ provided
+
+
+
+
+
+
+ org.jetbrains.kotlin
+ kotlin-maven-plugin
+ ${kotlin-maven-plugin.version}
+
+
+ compile
+
+ compile
+
+
+
+ ${project.basedir}/src/main/kotlin
+
+
+
+
+ test-compile
+
+ test-compile
+
+
+
+ ${project.basedir}/src/test/kotlin
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ ${java.version}
+
+
+
+
+ default-compile
+ none
+
+
+
+ default-testCompile
+ none
+
+
+ java-compile
+ compile
+
+ compile
+
+
+
+
+
+ maven-failsafe-plugin
+ ${maven-failsafe-plugin.version}
+
+
+ org.junit.platform
+ junit-platform-surefire-provider
+ ${junit.platform.version}
+
+
+
+
+ junit5
+
+ integration-test
+ verify
+
+
+
+ **/*Test5.java
+
+
+
+
+
+
+
+
+
+ 2.22.0
+ UTF-8
+ 1.2.60
+ 1.2.51
+ 1.2.51
+ 1.2.51
+ 0.22.5
+ 1.5.0
+ 3.6.1
+ 1.0.0
+ 5.2.0
+ 3.10.0
+ 3.7.0
+
+
+
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt
similarity index 100%
rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt
rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt
similarity index 100%
rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt
rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt
similarity index 100%
rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt
rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt
similarity index 100%
rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt
rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt
similarity index 88%
rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt
rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt
index d1b3390544..073c4dd890 100644
--- a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt
+++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt
@@ -24,7 +24,7 @@ class ExceptionsTest {
fun givenANullString_whenUsingElvisOperator_thenExceptionIsThrown() {
val sampleString: String? = null
- val length: Int = sampleString?.length ?: throw IllegalArgumentException("String must not be null")
+ sampleString?.length ?: throw IllegalArgumentException("String must not be null")
}
private fun funThrowingException(): Nothing {
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt
similarity index 100%
rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt
rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt
similarity index 100%
rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt
rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt
similarity index 100%
rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt
rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt
similarity index 100%
rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt
rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt
similarity index 100%
rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt
rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt
similarity index 100%
rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt
rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt
diff --git a/hazelcast/src/main/resources/logback.xml b/hazelcast/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/hazelcast/src/main/resources/logback.xml
+++ b/hazelcast/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java
new file mode 100644
index 0000000000..8b0a51858d
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java
@@ -0,0 +1,34 @@
+package com.baeldung.hibernate.joincolumn;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+@Entity
+public class Address {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+ @Column(name = "ZIP")
+ private String zipCode;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getZipCode() {
+ return zipCode;
+ }
+
+ public void setZipCode(String zipCode) {
+ this.zipCode = zipCode;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java
new file mode 100644
index 0000000000..a91fb3b4c9
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java
@@ -0,0 +1,47 @@
+package com.baeldung.hibernate.joincolumn;
+
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+@Entity
+public class Email {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+ private String address;
+
+ @ManyToOne(fetch = FetchType.LAZY)
+ @JoinColumn(name = "employee_id")
+ private Employee employee;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getAddress() {
+ return address;
+ }
+
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+ public Employee getEmployee() {
+ return employee;
+ }
+
+ public void setEmployee(Employee employee) {
+ this.employee = employee;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java
new file mode 100644
index 0000000000..3fbdb3820e
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java
@@ -0,0 +1,36 @@
+package com.baeldung.hibernate.joincolumn;
+
+import java.util.List;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+@Entity
+public class Employee {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "employee")
+ private List emails;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public List getEmails() {
+ return emails;
+ }
+
+ public void setEmails(List emails) {
+ this.emails = emails;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java
new file mode 100644
index 0000000000..e5b9dc06bc
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java
@@ -0,0 +1,41 @@
+package com.baeldung.hibernate.joincolumn;
+
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+
+@Entity
+public class Office {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+ @ManyToOne(fetch = FetchType.LAZY)
+ @JoinColumns({
+ @JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
+ @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
+ })
+ private Address address;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Address getAddress() {
+ return address;
+ }
+
+ public void setAddress(Address address) {
+ this.address = address;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java
new file mode 100644
index 0000000000..4e00be2b5c
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java
@@ -0,0 +1,26 @@
+package com.baeldung.hibernate.lifecycle;
+
+import org.hibernate.EmptyInterceptor;
+import org.hibernate.type.Type;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+public class DirtyDataInspector extends EmptyInterceptor {
+ private static final ArrayList dirtyEntities = new ArrayList<>();
+
+ @Override
+ public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
+ dirtyEntities.add((FootballPlayer) entity);
+ return true;
+ }
+
+ public static List getDirtyEntities() {
+ return dirtyEntities;
+ }
+
+ public static void clearDirtyEntitites() {
+ dirtyEntities.clear();
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java
new file mode 100644
index 0000000000..49799a5292
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java
@@ -0,0 +1,35 @@
+package com.baeldung.hibernate.lifecycle;
+
+import javax.persistence.*;
+
+@Entity
+@Table(name = "Football_Player")
+public class FootballPlayer {
+ @Id
+ @GeneratedValue
+ private long id;
+
+ @Column
+ private String name;
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return "FootballPlayer{" + "id=" + id + ", name='" + name + '\'' + '}';
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java
new file mode 100644
index 0000000000..a06685fb9c
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java
@@ -0,0 +1,96 @@
+package com.baeldung.hibernate.lifecycle;
+
+import org.h2.tools.RunScript;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.hibernate.boot.Metadata;
+import org.hibernate.boot.MetadataSources;
+import org.hibernate.boot.SessionFactoryBuilder;
+import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.engine.spi.EntityEntry;
+import org.hibernate.engine.spi.SessionImplementor;
+import org.hibernate.service.ServiceRegistry;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.stream.Collectors;
+
+public class HibernateLifecycleUtil {
+ private static SessionFactory sessionFactory;
+ private static Connection connection;
+
+ public static void init() throws Exception {
+ Properties hbConfigProp = getHibernateProperties();
+ Class.forName(hbConfigProp.getProperty("hibernate.connection.driver_class"));
+ connection = DriverManager.getConnection(hbConfigProp.getProperty("hibernate.connection.url"), hbConfigProp.getProperty("hibernate.connection.username"), hbConfigProp.getProperty("hibernate.connection.password"));
+
+ try (InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lifecycle-init.sql");
+ InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) {
+ RunScript.execute(connection, h2InitReader);
+ }
+
+ ServiceRegistry serviceRegistry = configureServiceRegistry();
+ sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(new DirtyDataInspector()).build();
+ }
+
+ public static void tearDown() throws Exception {
+ sessionFactory.close();
+ connection.close();
+ }
+
+ public static SessionFactory getSessionFactory() {
+ return sessionFactory;
+ }
+
+ private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
+ MetadataSources metadataSources = new MetadataSources(serviceRegistry);
+ metadataSources.addAnnotatedClass(FootballPlayer.class);
+
+ Metadata metadata = metadataSources.buildMetadata();
+ return metadata.getSessionFactoryBuilder();
+
+ }
+
+ private static ServiceRegistry configureServiceRegistry() throws IOException {
+ Properties properties = getHibernateProperties();
+ return new StandardServiceRegistryBuilder().applySettings(properties).build();
+ }
+
+ private static Properties getHibernateProperties() throws IOException {
+ Properties properties = new Properties();
+ URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate-lifecycle.properties");
+ try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
+ properties.load(inputStream);
+ }
+ return properties;
+ }
+
+ public static List getManagedEntities(Session session) {
+ Map.Entry
io.dropwizard.metrics
metrics-core
@@ -99,18 +95,15 @@
io.dropwizard.metrics
metrics-json
- ${dropwizard-metrics.version}
-
+
io.dropwizard.metrics
metrics-jvm
- ${dropwizard-metrics.version}
-
+
io.dropwizard.metrics
metrics-servlet
- ${dropwizard-metrics.version}
-
+
io.dropwizard.metrics
metrics-servlets
@@ -494,18 +487,6 @@
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- alphabetical
-
- **/*IntTest.java
-
-
-
-
org.jacoco
jacoco-maven-plugin
@@ -538,7 +519,7 @@
org.liquibase
liquibase-maven-plugin
- ${liquibase.version}
+ ${liquibase-maven-plugin.version}
javax.validation
@@ -922,6 +903,7 @@
1.1.3
3.6
2.0.0
+ 3.6.2
4.8
jdt_apt
1.1.0.Final
diff --git a/jpa-storedprocedure/README.md b/jpa-storedprocedure/README.md
deleted file mode 100644
index 39d6784d8b..0000000000
--- a/jpa-storedprocedure/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-### Relevant Articles:
-- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)
diff --git a/jpa-storedprocedure/pom.xml b/jpa-storedprocedure/pom.xml
deleted file mode 100644
index 79fa637cb6..0000000000
--- a/jpa-storedprocedure/pom.xml
+++ /dev/null
@@ -1,65 +0,0 @@
-
-
- 4.0.0
- com.baeldung
- jpa-storedprocedure
- 1.0
- jar
-
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
-
-
-
-
- javax
- javaee-api
- ${jee.version}
- provided
-
-
- org.hibernate
- hibernate-entitymanager
- ${hibernate.version}
-
-
-
- mysql
- mysql-connector-java
- ${mysql.version}
-
-
- commons-io
- commons-io
- ${commons-io.version}
-
-
-
-
- JpaStoredProcedure
-
-
- maven-assembly-plugin
-
- ${project.basedir}
-
-
- jar-with-dependencies
-
-
-
-
-
-
-
- 7.0
- 5.2.5.Final
- 6.0.5
- 2.5
-
-
-
\ No newline at end of file
diff --git a/jpa-storedprocedure/src/main/resources/META-INF/persistence.xml b/jpa-storedprocedure/src/main/resources/META-INF/persistence.xml
deleted file mode 100644
index 4c443cb7cf..0000000000
--- a/jpa-storedprocedure/src/main/resources/META-INF/persistence.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
- org.hibernate.jpa.HibernatePersistenceProvider
- com.baeldung.jpa.model.Car
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/jsf/src/main/resources/logback.xml b/jsf/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/jsf/src/main/resources/logback.xml
+++ b/jsf/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/json-path/src/test/resources/logback.xml b/json-path/src/test/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/json-path/src/test/resources/logback.xml
+++ b/json-path/src/test/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/json/README.md b/json/README.md
index 1317ada8be..8c2abc3e47 100644
--- a/json/README.md
+++ b/json/README.md
@@ -8,3 +8,4 @@
- [Introduction to JSONForms](http://www.baeldung.com/introduction-to-jsonforms)
- [Introduction to JsonPath](http://www.baeldung.com/guide-to-jayway-jsonpath)
- [Introduction to JSON-Java (org.json)](http://www.baeldung.com/java-org-json)
+- [Overview of JSON Pointer](https://www.baeldung.com/json-pointer)
diff --git a/libraries-data/README.md b/libraries-data/README.md
index fbe49e9f74..32d34f63be 100644
--- a/libraries-data/README.md
+++ b/libraries-data/README.md
@@ -9,4 +9,5 @@
- [Introduction to JCache](http://www.baeldung.com/jcache)
- [A Guide to Apache Ignite](http://www.baeldung.com/apache-ignite)
- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data)
-- [Guide to JMapper](https://github.com/eugenp/tutorials/tree/master/libraries-data)
+- [Guide to JMapper](https://www.baeldung.com/jmapper)
+- [A Guide to Apache Crunch](https://www.baeldung.com/crunch)
diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml
index e5e8fd5551..2b83328295 100644
--- a/libraries-data/pom.xml
+++ b/libraries-data/pom.xml
@@ -147,6 +147,44 @@
jmapper-core
${jmapper.version}
+
+
+
+ org.apache.crunch
+ crunch-core
+ ${org.apache.crunch.crunch-core.version}
+
+
+ org.apache.hadoop
+ hadoop-client
+ ${org.apache.hadoop.hadoop-client}
+ provided
+
+
+
+ commons-cli
+ commons-cli
+ 1.2
+ provided
+
+
+ commons-io
+ commons-io
+ 2.1
+ provided
+
+
+ commons-httpclient
+ commons-httpclient
+ 3.0.1
+ provided
+
+
+ commons-codec
+ commons-codec
+
+
+
@@ -252,6 +290,31 @@
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+ 2.3
+
+
+ src/main/assembly/hadoop-job.xml
+
+
+
+ com.baeldung.crunch.WordCount
+
+
+
+
+
+ make-assembly
+ package
+
+ single
+
+
+
+
+
@@ -282,7 +345,9 @@
5.0.2
5.0.0-release
5.0.4
- 1.6.0.1
+ 1.6.0.1
+ 0.15.0
+ 2.2.0
diff --git a/libraries-data/src/main/assembly/hadoop-job.xml b/libraries-data/src/main/assembly/hadoop-job.xml
new file mode 100644
index 0000000000..1917e1e5a3
--- /dev/null
+++ b/libraries-data/src/main/assembly/hadoop-job.xml
@@ -0,0 +1,28 @@
+
+
+
+
+ job
+
+ jar
+
+ false
+
+
+ false
+ runtime
+ lib
+
+ ${groupId}:${artifactId}
+
+
+
+ true
+
+ ${groupId}:${artifactId}
+
+
+
+
diff --git a/libraries-data/src/main/java/com/baeldung/crunch/StopWordFilter.java b/libraries-data/src/main/java/com/baeldung/crunch/StopWordFilter.java
new file mode 100644
index 0000000000..bdd606e179
--- /dev/null
+++ b/libraries-data/src/main/java/com/baeldung/crunch/StopWordFilter.java
@@ -0,0 +1,25 @@
+package com.baeldung.crunch;
+
+import java.util.Set;
+
+import org.apache.crunch.FilterFn;
+
+import com.google.common.collect.ImmutableSet;
+
+/**
+ * A filter that removes known stop words.
+ */
+public class StopWordFilter extends FilterFn {
+
+ // English stop words, borrowed from Lucene.
+ private static final Set STOP_WORDS = ImmutableSet
+ .copyOf(new String[] { "a", "and", "are", "as", "at", "be", "but", "by",
+ "for", "if", "in", "into", "is", "it", "no", "not", "of", "on",
+ "or", "s", "such", "t", "that", "the", "their", "then", "there",
+ "these", "they", "this", "to", "was", "will", "with" });
+
+ @Override
+ public boolean accept(String word) {
+ return !STOP_WORDS.contains(word);
+ }
+}
diff --git a/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseFn.java b/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseFn.java
new file mode 100644
index 0000000000..a277883ad3
--- /dev/null
+++ b/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseFn.java
@@ -0,0 +1,11 @@
+package com.baeldung.crunch;
+
+import org.apache.crunch.MapFn;
+
+public class ToUpperCaseFn extends MapFn {
+
+ @Override
+ public String map(String input) {
+ return input != null ? input.toUpperCase() : input;
+ }
+}
diff --git a/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseWithCounterFn.java b/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseWithCounterFn.java
new file mode 100644
index 0000000000..f753f98866
--- /dev/null
+++ b/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseWithCounterFn.java
@@ -0,0 +1,20 @@
+package com.baeldung.crunch;
+
+import org.apache.crunch.MapFn;
+
+@SuppressWarnings("serial")
+public class ToUpperCaseWithCounterFn extends MapFn {
+
+ @Override
+ public String map(String input) {
+ if (input == null) {
+ return input;
+ } else {
+ String output = input.toUpperCase();
+ if (!input.equals(output)) {
+ increment("UpperCase", "modified");
+ }
+ return output;
+ }
+ }
+}
diff --git a/libraries-data/src/main/java/com/baeldung/crunch/Tokenizer.java b/libraries-data/src/main/java/com/baeldung/crunch/Tokenizer.java
new file mode 100644
index 0000000000..9523634be1
--- /dev/null
+++ b/libraries-data/src/main/java/com/baeldung/crunch/Tokenizer.java
@@ -0,0 +1,23 @@
+package com.baeldung.crunch;
+
+import org.apache.crunch.DoFn;
+import org.apache.crunch.Emitter;
+
+import com.google.common.base.Splitter;
+
+/**
+ * Splits a line of text, filtering known stop words.
+ */
+public class Tokenizer extends DoFn {
+ private static final Splitter SPLITTER = Splitter
+ .onPattern("\\s+")
+ .omitEmptyStrings();
+
+ @Override
+ public void process(String line,
+ Emitter emitter) {
+ for (String word : SPLITTER.split(line)) {
+ emitter.emit(word);
+ }
+ }
+}
diff --git a/libraries-data/src/main/java/com/baeldung/crunch/WordCount.java b/libraries-data/src/main/java/com/baeldung/crunch/WordCount.java
new file mode 100644
index 0000000000..c49abec68a
--- /dev/null
+++ b/libraries-data/src/main/java/com/baeldung/crunch/WordCount.java
@@ -0,0 +1,62 @@
+package com.baeldung.crunch;
+
+import org.apache.crunch.PCollection;
+import org.apache.crunch.PTable;
+import org.apache.crunch.Pipeline;
+import org.apache.crunch.PipelineResult;
+import org.apache.crunch.impl.mr.MRPipeline;
+import org.apache.crunch.types.writable.Writables;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.util.GenericOptionsParser;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+
+/**
+ * A word count example for Apache Crunch, based on Crunch's example projects.
+ */
+public class WordCount extends Configured implements Tool {
+
+ public static void main(String[] args) throws Exception {
+ ToolRunner.run(new Configuration(), new WordCount(), args);
+ }
+
+ public int run(String[] args) throws Exception {
+
+ if (args.length != 2) {
+ System.err.println("Usage: hadoop jar crunch-1.0.0-SNAPSHOT-job.jar" + " [generic options] input output");
+ System.err.println();
+ GenericOptionsParser.printGenericCommandUsage(System.err);
+ return 1;
+ }
+
+ String inputPath = args[0];
+ String outputPath = args[1];
+
+ // Create an object to coordinate pipeline creation and execution.
+ Pipeline pipeline = new MRPipeline(WordCount.class, getConf());
+
+ // Reference a given text file as a collection of Strings.
+ PCollection lines = pipeline.readTextFile(inputPath);
+
+ // Define a function that splits each line in a PCollection of Strings into
+ // a PCollection made up of the individual words in the file.
+ // The second argument sets the serialization format.
+ PCollection words = lines.parallelDo(new Tokenizer(), Writables.strings());
+
+ // Take the collection of words and remove known stop words.
+ PCollection noStopWords = words.filter(new StopWordFilter());
+
+ // The count method applies a series of Crunch primitives and returns
+ // a map of the unique words in the input PCollection to their counts.
+ PTable counts = noStopWords.count();
+
+ // Instruct the pipeline to write the resulting counts to a text file.
+ pipeline.writeTextFile(counts, outputPath);
+
+ // Execute the pipeline as a MapReduce.
+ PipelineResult result = pipeline.done();
+
+ return result.succeeded() ? 0 : 1;
+ }
+}
diff --git a/libraries-data/src/test/java/com/baeldung/crunch/MemPipelineUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/MemPipelineUnitTest.java
new file mode 100644
index 0000000000..3ee2bb6836
--- /dev/null
+++ b/libraries-data/src/test/java/com/baeldung/crunch/MemPipelineUnitTest.java
@@ -0,0 +1,89 @@
+package com.baeldung.crunch;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertIterableEquals;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Calendar;
+
+import org.apache.crunch.PCollection;
+import org.apache.crunch.Pipeline;
+import org.apache.crunch.Source;
+import org.apache.crunch.Target;
+import org.apache.crunch.impl.mem.MemPipeline;
+import org.apache.crunch.io.From;
+import org.apache.crunch.io.To;
+import org.junit.Ignore;
+import org.junit.Test;
+
+public class MemPipelineUnitTest {
+
+ private static final String INPUT_FILE_PATH = "src/test/resources/crunch/input.txt";
+
+ @Test
+ public void givenPipeLineAndSource_whenSourceRead_thenExpectedNumberOfRecordsRead() {
+ Pipeline pipeline = MemPipeline.getInstance();
+ Source source = From.textFile(INPUT_FILE_PATH);
+
+ PCollection lines = pipeline.read(source);
+
+ assertEquals(21, lines.asCollection()
+ .getValue()
+ .size());
+ }
+
+ @Test
+ public void givenPipeLine_whenTextFileRead_thenExpectedNumberOfRecordsRead() {
+ Pipeline pipeline = MemPipeline.getInstance();
+
+ PCollection lines = pipeline.readTextFile(INPUT_FILE_PATH);
+
+ assertEquals(21, lines.asCollection()
+ .getValue()
+ .size());
+ }
+
+ private String createOutputPath() throws IOException {
+ Path path = Files.createTempDirectory("test");
+ final String outputFilePath = path.toString() + File.separatorChar
+ + "output.text";
+ return outputFilePath;
+ }
+
+ @Test
+ @Ignore("Requires Hadoop binaries")
+ public void givenCollection_whenWriteCalled_fileWrittenSuccessfully()
+ throws IOException {
+ PCollection inputStrings = MemPipeline.collectionOf("Hello",
+ "Apache", "Crunch", Calendar.getInstance()
+ .toString());
+ final String outputFilePath = createOutputPath();
+ Target target = To.textFile(outputFilePath);
+
+ inputStrings.write(target);
+
+ Pipeline pipeline = MemPipeline.getInstance();
+ PCollection lines = pipeline.readTextFile(outputFilePath);
+ assertIterableEquals(inputStrings.materialize(), lines.materialize());
+ }
+
+ @Test
+ @Ignore("Requires Hadoop binaries")
+ public void givenPipeLine_whenWriteTextFileCalled_fileWrittenSuccessfully()
+ throws IOException {
+ Pipeline pipeline = MemPipeline.getInstance();
+ PCollection inputStrings = MemPipeline.collectionOf("Hello",
+ "Apache", "Crunch", Calendar.getInstance()
+ .toString());
+ final String outputFilePath = createOutputPath();
+
+ pipeline.writeTextFile(inputStrings, outputFilePath);
+
+ PCollection lines = pipeline.readTextFile(outputFilePath);
+ assertIterableEquals(inputStrings.materialize(), lines.materialize());
+ }
+
+}
diff --git a/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java
new file mode 100644
index 0000000000..fffefc2bfb
--- /dev/null
+++ b/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.crunch;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.apache.crunch.FilterFn;
+import org.apache.crunch.PCollection;
+import org.apache.crunch.impl.mem.MemPipeline;
+import org.junit.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+public class StopWordFilterUnitTest {
+
+ @Test
+ public void givenFilter_whenStopWordPassed_thenFalseReturned() {
+ FilterFn filter = new StopWordFilter();
+
+ assertFalse(filter.accept("the"));
+ }
+
+ @Test
+ public void givenFilter_whenNonStopWordPassed_thenTrueReturned() {
+ FilterFn filter = new StopWordFilter();
+
+ assertTrue(filter.accept("Hello"));
+ }
+
+ @Test
+ public void givenWordCollection_whenFiltered_thenStopWordsRemoved() {
+ PCollection words = MemPipeline.collectionOf("This", "is", "a",
+ "test", "sentence");
+
+ PCollection noStopWords = words.filter(new StopWordFilter());
+
+ assertEquals(ImmutableList.of("This", "test", "sentence"),
+ Lists.newArrayList(noStopWords.materialize()));
+ }
+}
diff --git a/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseFnUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseFnUnitTest.java
new file mode 100644
index 0000000000..09fb9fba85
--- /dev/null
+++ b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseFnUnitTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.crunch;
+
+import static org.junit.Assert.assertEquals;
+
+import org.apache.crunch.impl.mem.emit.InMemoryEmitter;
+import org.junit.Test;
+
+import com.google.common.collect.ImmutableList;
+
+public class ToUpperCaseFnUnitTest {
+
+ @Test
+ public void givenString_whenToUpperCaseFnCalled_UpperCaseStringReturned() {
+ InMemoryEmitter emitter = new InMemoryEmitter();
+
+ new ToUpperCaseFn().process("input", emitter);
+
+ assertEquals(ImmutableList.of("INPUT"), emitter.getOutput());
+ }
+
+}
diff --git a/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java
new file mode 100644
index 0000000000..76294d273d
--- /dev/null
+++ b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.crunch;
+
+import static org.junit.Assert.assertEquals;
+
+import org.apache.crunch.PCollection;
+import org.apache.crunch.impl.mem.MemPipeline;
+import org.apache.crunch.types.writable.Writables;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+public class ToUpperCaseWithCounterFnUnitTest {
+
+ @Before
+ public void setUp() throws Exception {
+ MemPipeline.clearCounters();
+ }
+
+ @Test
+ public void whenFunctionCalled_counterIncementendForChangedValues() {
+ PCollection inputStrings = MemPipeline.collectionOf("This", "is", "a", "TEST", "string");
+ PCollection upperCaseStrings = inputStrings.parallelDo(new ToUpperCaseWithCounterFn(), Writables.strings());
+
+ assertEquals(ImmutableList.of("THIS", "IS", "A", "TEST", "STRING"), Lists.newArrayList(upperCaseStrings.materialize()));
+ assertEquals(4L, MemPipeline.getCounters()
+ .findCounter("UpperCase", "modified")
+ .getValue());
+ }
+}
diff --git a/libraries-data/src/test/java/com/baeldung/crunch/TokenizerUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/TokenizerUnitTest.java
new file mode 100644
index 0000000000..1e85826d17
--- /dev/null
+++ b/libraries-data/src/test/java/com/baeldung/crunch/TokenizerUnitTest.java
@@ -0,0 +1,27 @@
+package com.baeldung.crunch;
+
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+
+import org.apache.crunch.Emitter;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class TokenizerUnitTest {
+ @Mock
+ private Emitter emitter;
+
+ @Test
+ public void givenTokenizer_whenLineProcessed_thenOnlyExpectedWordsEmitted() {
+ Tokenizer splitter = new Tokenizer();
+
+ splitter.process(" hello world ", emitter);
+
+ verify(emitter).emit("hello");
+ verify(emitter).emit("world");
+ verifyNoMoreInteractions(emitter);
+ }
+}
diff --git a/libraries-data/src/test/resources/crunch/input.txt b/libraries-data/src/test/resources/crunch/input.txt
new file mode 100644
index 0000000000..cb78ea5351
--- /dev/null
+++ b/libraries-data/src/test/resources/crunch/input.txt
@@ -0,0 +1,21 @@
+An an valley indeed so no wonder future nature vanity. Debating all she mistaken indulged believed provided declared. He many kept on draw lain song as same. Whether at dearest certain spirits is entered in to. Rich fine bred real use too many good. She compliment unaffected expression favourable any. Unknown chiefly showing to conduct no. Hung as love evil able to post at as.
+
+
+
+Is he staying arrival address earnest. To preference considered it themselves inquietude collecting estimating. View park for why gay knew face. Next than near to four so hand. Times so do he downs me would. Witty abode party her found quiet law. They door four bed fail now have.
+
+Tolerably earnestly middleton extremely distrusts she boy now not. Add and offered prepare how cordial two promise. Greatly who affixed suppose but enquire compact prepare all put. Added forth chief trees but rooms think may. Wicket do manner others seemed enable rather in. Excellent own discovery unfeeling sweetness questions the gentleman. Chapter shyness matters mr parlors if mention thought.
+
+Extended kindness trifling remember he confined outlived if. Assistance sentiments yet unpleasing say. Open they an busy they my such high. An active dinner wishes at unable hardly no talked on. Immediate him her resolving his favourite. Wished denote abroad at branch at.
+
+Village did removed enjoyed explain nor ham saw calling talking. Securing as informed declared or margaret. Joy horrible moreover man feelings own shy. Request norland neither mistake for yet. Between the for morning assured country believe. On even feet time have an no at. Relation so in confined smallest children unpacked delicate. Why sir end believe uncivil respect. Always get adieus nature day course for common. My little garret repair to desire he esteem.
+
+You vexed shy mirth now noise. Talked him people valley add use her depend letter. Allowance too applauded now way something recommend. Mrs age men and trees jokes fancy. Gay pretended engrossed eagerness continued ten. Admitting day him contained unfeeling attention mrs out.
+
+Performed suspicion in certainty so frankness by attention pretended. Newspaper or in tolerably education enjoyment. Extremity excellent certainty discourse sincerity no he so resembled. Joy house worse arise total boy but. Elderly up chicken do at feeling is. Like seen drew no make fond at on rent. Behaviour extremely her explained situation yet september gentleman are who. Is thought or pointed hearing he.
+
+If wandered relation no surprise of screened doubtful. Overcame no insisted ye of trifling husbands. Might am order hours on found. Or dissimilar companions friendship impossible at diminution. Did yourself carriage learning she man its replying. Sister piqued living her you enable mrs off spirit really. Parish oppose repair is me misery. Quick may saw style after money mrs.
+
+Effects present letters inquiry no an removed or friends. Desire behind latter me though in. Supposing shameless am he engrossed up additions. My possible peculiar together to. Desire so better am cannot he up before points. Remember mistaken opinions it pleasure of debating. Court front maids forty if aware their at. Chicken use are pressed removed.
+
+To sorry world an at do spoil along. Incommode he depending do frankness remainder to. Edward day almost active him friend thirty piqued. People as period twenty my extent as. Set was better abroad ham plenty secure had horses. Admiration has sir decisively excellence say everything inhabiting acceptance. Sooner settle add put you sudden him.
diff --git a/libraries-server/README.md b/libraries-server/README.md
new file mode 100644
index 0000000000..c25e9a10ab
--- /dev/null
+++ b/libraries-server/README.md
@@ -0,0 +1,9 @@
+### Relevant articles
+
+- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded)
+- [Introduction to Netty](http://www.baeldung.com/netty)
+- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling)
+- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup)
+- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic)
+- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel)
+
diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml
index 517cf6a07c..6fca09faf4 100644
--- a/libraries-server/pom.xml
+++ b/libraries-server/pom.xml
@@ -14,6 +14,73 @@
org.eclipse.paho
org.eclipse.paho.client.mqttv3
1.2.0
-
+
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+
+
+ org.eclipse.jetty
+ jetty-server
+ ${jetty.version}
+
+
+ org.eclipse.jetty
+ jetty-servlet
+ ${jetty.version}
+
+
+ org.eclipse.jetty
+ jetty-webapp
+ ${jetty.version}
+
+
+ org.apache.httpcomponents
+ httpclient
+ ${httpclient.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ commons-io
+ commons-io
+ ${commons.io.version}
+
+
+ io.netty
+ netty-all
+ ${netty.version}
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+
+
+ org.apache.tomcat
+ tomcat-catalina
+ ${tomcat.version}
+
-
\ No newline at end of file
+
+
+ 3.6.2
+ 4.5.3
+ 2.5
+ 9.4.8.v20171121
+ 4.1.20.Final
+ 4.1
+ 4.12
+ 8.5.24
+
+
+
\ No newline at end of file
diff --git a/libraries/src/main/java/com/baeldung/jetty/AsyncServlet.java b/libraries-server/src/main/java/com/baeldung/jetty/AsyncServlet.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/jetty/AsyncServlet.java
rename to libraries-server/src/main/java/com/baeldung/jetty/AsyncServlet.java
diff --git a/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java b/libraries-server/src/main/java/com/baeldung/jetty/BlockingServlet.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java
rename to libraries-server/src/main/java/com/baeldung/jetty/BlockingServlet.java
diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java b/libraries-server/src/main/java/com/baeldung/jetty/JettyServer.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/jetty/JettyServer.java
rename to libraries-server/src/main/java/com/baeldung/jetty/JettyServer.java
diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java b/libraries-server/src/main/java/com/baeldung/jetty/JettyServerFactory.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java
rename to libraries-server/src/main/java/com/baeldung/jetty/JettyServerFactory.java
diff --git a/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java b/libraries-server/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java
rename to libraries-server/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java
diff --git a/libraries/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java b/libraries-server/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java
rename to libraries-server/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java
diff --git a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerA.java b/libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerA.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/ChannelHandlerA.java
rename to libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerA.java
diff --git a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java b/libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerB.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java
rename to libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerB.java
diff --git a/libraries/src/main/java/com/baeldung/netty/ClientHandler.java b/libraries-server/src/main/java/com/baeldung/netty/ClientHandler.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/ClientHandler.java
rename to libraries-server/src/main/java/com/baeldung/netty/ClientHandler.java
diff --git a/libraries/src/main/java/com/baeldung/netty/HttpMessageHandler.java b/libraries-server/src/main/java/com/baeldung/netty/HttpMessageHandler.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/HttpMessageHandler.java
rename to libraries-server/src/main/java/com/baeldung/netty/HttpMessageHandler.java
diff --git a/libraries/src/main/java/com/baeldung/netty/NettyClient.java b/libraries-server/src/main/java/com/baeldung/netty/NettyClient.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/NettyClient.java
rename to libraries-server/src/main/java/com/baeldung/netty/NettyClient.java
diff --git a/libraries/src/main/java/com/baeldung/netty/NettyServer.java b/libraries-server/src/main/java/com/baeldung/netty/NettyServer.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/NettyServer.java
rename to libraries-server/src/main/java/com/baeldung/netty/NettyServer.java
diff --git a/libraries/src/main/java/com/baeldung/netty/NettyServerB.java b/libraries-server/src/main/java/com/baeldung/netty/NettyServerB.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/NettyServerB.java
rename to libraries-server/src/main/java/com/baeldung/netty/NettyServerB.java
diff --git a/libraries/src/main/java/com/baeldung/netty/Operation.java b/libraries-server/src/main/java/com/baeldung/netty/Operation.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/Operation.java
rename to libraries-server/src/main/java/com/baeldung/netty/Operation.java
diff --git a/libraries/src/main/java/com/baeldung/netty/ProcessingHandler.java b/libraries-server/src/main/java/com/baeldung/netty/ProcessingHandler.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/ProcessingHandler.java
rename to libraries-server/src/main/java/com/baeldung/netty/ProcessingHandler.java
diff --git a/libraries/src/main/java/com/baeldung/netty/RequestData.java b/libraries-server/src/main/java/com/baeldung/netty/RequestData.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/RequestData.java
rename to libraries-server/src/main/java/com/baeldung/netty/RequestData.java
diff --git a/libraries/src/main/java/com/baeldung/netty/RequestDataEncoder.java b/libraries-server/src/main/java/com/baeldung/netty/RequestDataEncoder.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/RequestDataEncoder.java
rename to libraries-server/src/main/java/com/baeldung/netty/RequestDataEncoder.java
diff --git a/libraries/src/main/java/com/baeldung/netty/RequestDecoder.java b/libraries-server/src/main/java/com/baeldung/netty/RequestDecoder.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/RequestDecoder.java
rename to libraries-server/src/main/java/com/baeldung/netty/RequestDecoder.java
diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseData.java b/libraries-server/src/main/java/com/baeldung/netty/ResponseData.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/ResponseData.java
rename to libraries-server/src/main/java/com/baeldung/netty/ResponseData.java
diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseDataDecoder.java b/libraries-server/src/main/java/com/baeldung/netty/ResponseDataDecoder.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/ResponseDataDecoder.java
rename to libraries-server/src/main/java/com/baeldung/netty/ResponseDataDecoder.java
diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseDataEncoder.java b/libraries-server/src/main/java/com/baeldung/netty/ResponseDataEncoder.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/ResponseDataEncoder.java
rename to libraries-server/src/main/java/com/baeldung/netty/ResponseDataEncoder.java
diff --git a/libraries/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java b/libraries-server/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java
rename to libraries-server/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java
diff --git a/libraries/src/main/java/com/baeldung/tomcat/MyFilter.java b/libraries-server/src/main/java/com/baeldung/tomcat/MyFilter.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/tomcat/MyFilter.java
rename to libraries-server/src/main/java/com/baeldung/tomcat/MyFilter.java
diff --git a/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java b/libraries-server/src/main/java/com/baeldung/tomcat/MyServlet.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/tomcat/MyServlet.java
rename to libraries-server/src/main/java/com/baeldung/tomcat/MyServlet.java
diff --git a/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java b/libraries-server/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java
similarity index 100%
rename from libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java
rename to libraries-server/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java
diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java b/libraries-server/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java
similarity index 100%
rename from libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java
rename to libraries-server/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java
diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java b/libraries-server/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java
similarity index 100%
rename from libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java
rename to libraries-server/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java
diff --git a/libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java b/libraries-server/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java
similarity index 100%
rename from libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java
rename to libraries-server/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java
diff --git a/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java b/libraries-server/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java
similarity index 100%
rename from libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java
rename to libraries-server/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java
diff --git a/libraries/src/test/resources/jetty-embedded-demo-app.war b/libraries-server/src/test/resources/jetty-embedded-demo-app.war
similarity index 100%
rename from libraries/src/test/resources/jetty-embedded-demo-app.war
rename to libraries-server/src/test/resources/jetty-embedded-demo-app.war
diff --git a/libraries/README.md b/libraries/README.md
index aed808420e..c2c4b2718a 100644
--- a/libraries/README.md
+++ b/libraries/README.md
@@ -5,13 +5,11 @@
- [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang)
- [Introduction to Javatuples](http://www.baeldung.com/java-tuples)
- [Introduction to Javassist](http://www.baeldung.com/javassist)
-- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded)
- [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink)
- [Introduction to JSONassert](http://www.baeldung.com/jsonassert)
- [Intro to JaVers](http://www.baeldung.com/javers)
- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math)
- [Intro to Serenity BDD](http://www.baeldung.com/serenity-bdd)
-- [Introduction to Netty](http://www.baeldung.com/netty)
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
- [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay)
- [Introduction to Quartz](http://www.baeldung.com/quartz)
@@ -35,7 +33,6 @@
- [Introduction to Eclipse Collections](http://www.baeldung.com/eclipse-collections)
- [DistinctBy in Java Stream API](http://www.baeldung.com/java-streams-distinct-by)
- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv)
-- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference)
- [Introduction to NoException](http://www.baeldung.com/no-exception)
- [Apache Commons IO](http://www.baeldung.com/apache-commons-io)
- [Introduction to Conflict-Free Replicated Data Types](http://www.baeldung.com/java-conflict-free-replicated-data-types)
@@ -55,10 +52,7 @@
- [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle)
- [Guide to google-http-client](http://www.baeldung.com/google-http-client)
- [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client)
-- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup)
- [A Docker Guide for Java](http://www.baeldung.com/docker-java-api)
-- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling)
-- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic)
- [Introduction To OpenCSV](http://www.baeldung.com/opencsv)
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client)
@@ -78,7 +72,6 @@
- [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client)
- [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools)
- [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils)
-- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel)
- [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices)
- [Introduction to JavaPoet](http://www.baeldung.com/java-poet)
- [Introduction to Joda-Time](http://www.baeldung.com/joda-time)
diff --git a/libraries/pom.xml b/libraries/pom.xml
index 7402d88ef3..80e3303ba5 100644
--- a/libraries/pom.xml
+++ b/libraries/pom.xml
@@ -106,21 +106,6 @@
javers-core
${javers.version}
-
- org.eclipse.jetty
- jetty-server
- ${jetty.version}
-
-
- org.eclipse.jetty
- jetty-servlet
- ${jetty.version}
-
-
- org.eclipse.jetty
- jetty-webapp
- ${jetty.version}
-
io.nats
@@ -379,11 +364,6 @@
jmh-generator-annprocess
${jmh.version}
-
- io.netty
- netty-all
- ${netty.version}
-
junit
junit
@@ -481,17 +461,6 @@
logging-interceptor
${logging-interceptor.version}
-
- com.darwinsys
- hirondelle-date4j
- RELEASE
- test
-
-
- joda-time
- joda-time
- ${joda-time.version}
-
com.darwinsys
hirondelle-date4j
@@ -669,13 +638,7 @@
test
test
-
-
-
- org.apache.tomcat
- tomcat-catalina
- ${tomcat.version}
-
+
org.milyn
milyn-smooks-all
@@ -935,7 +898,6 @@
2.5
1.6
1.4.196
- 9.4.8.v20171121
1.0
4.5.3
@@ -948,7 +910,6 @@
1.9.0
1.9.27
1.1.0
- 4.1.20.Final
4.1
4.12
0.10
@@ -977,7 +938,6 @@
1.0.0
1.7.0
3.0.14
- 8.5.24
2.2.0
9.1.5.Final
4.1
diff --git a/lucene/pom.xml b/lucene/pom.xml
index a3960f6059..f427cfd8a7 100644
--- a/lucene/pom.xml
+++ b/lucene/pom.xml
@@ -23,6 +23,12 @@
lucene-queryparser
${lucene.version}
+
+ org.apache.lucene
+ lucene-analyzers-common
+ ${lucene.version}
+
+
@@ -32,7 +38,7 @@
1.0.0.Final
1.16.10.0
- 7.1.0
+ 7.4.0
\ No newline at end of file
diff --git a/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java b/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java
index 97b1ec7b5d..8a31d3cb5b 100644
--- a/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java
+++ b/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java
@@ -4,7 +4,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.SortedDocValuesField;
@@ -27,9 +27,9 @@ import org.apache.lucene.util.BytesRef;
public class InMemoryLuceneIndex {
private Directory memoryIndex;
- private StandardAnalyzer analyzer;
+ private Analyzer analyzer;
- public InMemoryLuceneIndex(Directory memoryIndex, StandardAnalyzer analyzer) {
+ public InMemoryLuceneIndex(Directory memoryIndex, Analyzer analyzer) {
super();
this.memoryIndex = memoryIndex;
this.analyzer = analyzer;
diff --git a/lucene/src/main/java/com/baeldung/lucene/MyCustomAnalyzer.java b/lucene/src/main/java/com/baeldung/lucene/MyCustomAnalyzer.java
new file mode 100644
index 0000000000..609e2d09d3
--- /dev/null
+++ b/lucene/src/main/java/com/baeldung/lucene/MyCustomAnalyzer.java
@@ -0,0 +1,26 @@
+package com.baeldung.lucene;
+
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.LowerCaseFilter;
+import org.apache.lucene.analysis.StopFilter;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.en.PorterStemFilter;
+import org.apache.lucene.analysis.miscellaneous.CapitalizationFilter;
+import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.lucene.analysis.standard.StandardFilter;
+import org.apache.lucene.analysis.standard.StandardTokenizer;
+
+public class MyCustomAnalyzer extends Analyzer{
+
+ @Override
+ protected TokenStreamComponents createComponents(String fieldName) {
+ final StandardTokenizer src = new StandardTokenizer();
+ TokenStream result = new StandardFilter(src);
+ result = new LowerCaseFilter(result);
+ result = new StopFilter(result, StandardAnalyzer.STOP_WORDS_SET);
+ result = new PorterStemFilter(result);
+ result = new CapitalizationFilter(result);
+ return new TokenStreamComponents(src, result);
+ }
+
+}
diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneAnalyzerIntegrationTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneAnalyzerIntegrationTest.java
new file mode 100644
index 0000000000..28a87bba8c
--- /dev/null
+++ b/lucene/src/test/java/com/baeldung/lucene/LuceneAnalyzerIntegrationTest.java
@@ -0,0 +1,147 @@
+package com.baeldung.lucene;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.core.KeywordAnalyzer;
+import org.apache.lucene.analysis.core.SimpleAnalyzer;
+import org.apache.lucene.analysis.core.StopAnalyzer;
+import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
+import org.apache.lucene.analysis.custom.CustomAnalyzer;
+import org.apache.lucene.analysis.en.EnglishAnalyzer;
+import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
+import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.TermQuery;
+import org.apache.lucene.store.RAMDirectory;
+import org.junit.Test;
+
+public class LuceneAnalyzerIntegrationTest {
+
+ private static final String SAMPLE_TEXT = "This is baeldung.com Lucene Analyzers test";
+ private static final String FIELD_NAME = "sampleName";
+
+ @Test
+ public void whenUseStandardAnalyzer_thenAnalyzed() throws IOException {
+ List result = analyze(SAMPLE_TEXT, new StandardAnalyzer());
+
+ assertThat(result, contains("baeldung.com", "lucene", "analyzers", "test"));
+ }
+
+ @Test
+ public void whenUseStopAnalyzer_thenAnalyzed() throws IOException {
+ List result = analyze(SAMPLE_TEXT, new StopAnalyzer());
+
+ assertThat(result, contains("baeldung", "com", "lucene", "analyzers", "test"));
+ }
+
+ @Test
+ public void whenUseSimpleAnalyzer_thenAnalyzed() throws IOException {
+ List result = analyze(SAMPLE_TEXT, new SimpleAnalyzer());
+
+ assertThat(result, contains("this", "is", "baeldung", "com", "lucene", "analyzers", "test"));
+ }
+
+ @Test
+ public void whenUseWhiteSpaceAnalyzer_thenAnalyzed() throws IOException {
+ List result = analyze(SAMPLE_TEXT, new WhitespaceAnalyzer());
+
+ assertThat(result, contains("This", "is", "baeldung.com", "Lucene", "Analyzers", "test"));
+ }
+
+ @Test
+ public void whenUseKeywordAnalyzer_thenAnalyzed() throws IOException {
+ List result = analyze(SAMPLE_TEXT, new KeywordAnalyzer());
+
+ assertThat(result, contains("This is baeldung.com Lucene Analyzers test"));
+ }
+
+ @Test
+ public void whenUseEnglishAnalyzer_thenAnalyzed() throws IOException {
+ List result = analyze(SAMPLE_TEXT, new EnglishAnalyzer());
+
+ assertThat(result, contains("baeldung.com", "lucen", "analyz", "test"));
+ }
+
+ @Test
+ public void whenUseCustomAnalyzerBuilder_thenAnalyzed() throws IOException {
+ Analyzer analyzer = CustomAnalyzer.builder()
+ .withTokenizer("standard")
+ .addTokenFilter("lowercase")
+ .addTokenFilter("stop")
+ .addTokenFilter("porterstem")
+ .addTokenFilter("capitalization")
+ .build();
+ List result = analyze(SAMPLE_TEXT, analyzer);
+
+ assertThat(result, contains("Baeldung.com", "Lucen", "Analyz", "Test"));
+ }
+
+ @Test
+ public void whenUseCustomAnalyzer_thenAnalyzed() throws IOException {
+ List result = analyze(SAMPLE_TEXT, new MyCustomAnalyzer());
+
+ assertThat(result, contains("Baeldung.com", "Lucen", "Analyz", "Test"));
+ }
+
+ // ================= usage example
+
+ @Test
+ public void givenTermQuery_whenUseCustomAnalyzer_thenCorrect() {
+ InMemoryLuceneIndex luceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new MyCustomAnalyzer());
+ luceneIndex.indexDocument("introduction", "introduction to lucene");
+ luceneIndex.indexDocument("analyzers", "guide to lucene analyzers");
+ Query query = new TermQuery(new Term("body", "Introduct"));
+
+ List documents = luceneIndex.searchIndex(query);
+ assertEquals(1, documents.size());
+ }
+
+ @Test
+ public void givenTermQuery_whenUsePerFieldAnalyzerWrapper_thenCorrect() {
+ Map analyzerMap = new HashMap<>();
+ analyzerMap.put("title", new MyCustomAnalyzer());
+ analyzerMap.put("body", new EnglishAnalyzer());
+
+ PerFieldAnalyzerWrapper wrapper =
+ new PerFieldAnalyzerWrapper(new StandardAnalyzer(), analyzerMap);
+ InMemoryLuceneIndex luceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), wrapper);
+ luceneIndex.indexDocument("introduction", "introduction to lucene");
+ luceneIndex.indexDocument("analyzers", "guide to lucene analyzers");
+
+ Query query = new TermQuery(new Term("body", "introduct"));
+ List documents = luceneIndex.searchIndex(query);
+ assertEquals(1, documents.size());
+
+ query = new TermQuery(new Term("title", "Introduct"));
+
+ documents = luceneIndex.searchIndex(query);
+ assertEquals(1, documents.size());
+ }
+
+ // ===================================================================
+
+ public List analyze(String text, Analyzer analyzer) throws IOException {
+ List result = new ArrayList();
+ TokenStream tokenStream = analyzer.tokenStream(FIELD_NAME, text);
+ CharTermAttribute attr = tokenStream.addAttribute(CharTermAttribute.class);
+ tokenStream.reset();
+ while (tokenStream.incrementToken()) {
+ result.add(attr.toString());
+ }
+ return result;
+ }
+
+}
diff --git a/maven/pom.xml b/maven/pom.xml
index 4f91e8717c..4bec533226 100644
--- a/maven/pom.xml
+++ b/maven/pom.xml
@@ -1,18 +1,60 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.baeldung
maven
0.0.1-SNAPSHOT
+ war
-
- parent-modules
- com.baeldung
- 1.0.0-SNAPSHOT
-
+
+
+ org.glassfish.jersey.containers
+ jersey-container-servlet-core
+ ${jersey.version}
+
+
+ org.glassfish.jersey.inject
+ jersey-hk2
+ ${jersey.version}
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+
+ org.eclipse.jetty
+ jetty-maven-plugin
+ ${jetty.version}
+
+
+ 8999
+
+ quit
+ 9000
+
+
+
+ start-jetty
+ pre-integration-test
+
+ start
+
+
+
+ stop-jetty
+ post-integration-test
+
+ stop
+
+
+
+
maven-resources-plugin
${maven.resources.version}
@@ -31,7 +73,7 @@
maven-compiler-plugin
- ${maven-compiler-plugin.version}
+ ${maven.compiler.version}
${java.version}
@@ -42,11 +84,13 @@
maven-surefire-plugin
- ${maven-surefire-plugin.version}
+ ${maven.surefire.version}
DataTest.java
+ **/*IntegrationTest
+ com.baeldung.maven.it.Integration
TestFail.java
DataCheck.java
@@ -110,18 +154,150 @@
+
+ add-integration-test-source
+ generate-test-sources
+
+ add-test-source
+
+
+
+
+
+
+
+
+ add-integration-test-resource
+ generate-test-resources
+
+ add-test-resource
+
+
+
+
+ src/integration-test/resources
+
+
+
+
+
+
+ default
+
+
+
+ maven-surefire-plugin
+ ${maven.surefire.version}
+
+
+ DataTest.java
+
+
+ TestFail.java
+ DataCheck.java
+
+ true
+
+
+
+
+
+
+ failsafe
+
+
+
+ maven-failsafe-plugin
+ ${maven.failsafe.version}
+
+
+ **/*RestIT
+ **/RestITCase
+
+
+
+
+
+ integration-test
+ verify
+
+
+
+
+
+
+
+
+ surefire
+
+
+
+ maven-surefire-plugin
+ ${maven.surefire.version}
+
+
+ integration-test
+
+ test
+
+
+
+ none
+
+
+ **/*IntegrationTest
+
+
+
+
+
+
+
+
+
+ category
+
+
+
+ maven-failsafe-plugin
+ ${maven.failsafe.version}
+
+
+ **/*
+
+ com.baeldung.maven.it.Integration
+
+
+
+
+ integration-test
+ verify
+
+
+
+
+
+
+
+
+
+ 1.8
3.0.2
- 2.21.0
+ 3.8.0
+ 2.22.0
+ 2.22.0
1.1
3.0.0
3.0.0
Baeldung
+ 9.4.11.v20180605
+ 2.27
+ 4.12
-
\ No newline at end of file
diff --git a/maven/src/integration-test/java/com/baeldung/maven/it/RestITCase.java b/maven/src/integration-test/java/com/baeldung/maven/it/RestITCase.java
new file mode 100644
index 0000000000..aaeeedb661
--- /dev/null
+++ b/maven/src/integration-test/java/com/baeldung/maven/it/RestITCase.java
@@ -0,0 +1,24 @@
+package com.baeldung.maven.it;
+
+import org.junit.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Scanner;
+
+import static org.junit.Assert.assertEquals;
+
+public class RestITCase {
+ @Test
+ public void whenSendingGet_thenMessageIsReturned() throws IOException {
+ String url = "http://localhost:8999";
+ URLConnection connection = new URL(url).openConnection();
+ try (InputStream response = connection.getInputStream();
+ Scanner scanner = new Scanner(response)) {
+ String responseBody = scanner.nextLine();
+ assertEquals("Welcome to Baeldung!", responseBody);
+ }
+ }
+}
diff --git a/maven/src/main/java/com/baeldung/maven/it/EndpointConfig.java b/maven/src/main/java/com/baeldung/maven/it/EndpointConfig.java
new file mode 100644
index 0000000000..919210ccff
--- /dev/null
+++ b/maven/src/main/java/com/baeldung/maven/it/EndpointConfig.java
@@ -0,0 +1,9 @@
+package com.baeldung.maven.it;
+
+import org.glassfish.jersey.server.ResourceConfig;
+
+public class EndpointConfig extends ResourceConfig {
+ public EndpointConfig() {
+ register(RestEndpoint.class);
+ }
+}
diff --git a/maven/src/main/java/com/baeldung/maven/it/RestEndpoint.java b/maven/src/main/java/com/baeldung/maven/it/RestEndpoint.java
new file mode 100644
index 0000000000..c234891865
--- /dev/null
+++ b/maven/src/main/java/com/baeldung/maven/it/RestEndpoint.java
@@ -0,0 +1,12 @@
+package com.baeldung.maven.it;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+
+@Path("/")
+public class RestEndpoint {
+ @GET
+ public String hello() {
+ return "Welcome to Baeldung!";
+ }
+}
diff --git a/maven/src/main/webapp/WEB-INF/web.xml b/maven/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000..1751ad17a5
--- /dev/null
+++ b/maven/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,17 @@
+
+
+ rest-servlet
+ org.glassfish.jersey.servlet.ServletContainer
+
+ javax.ws.rs.Application
+ com.baeldung.maven.it.EndpointConfig
+
+
+
+ rest-servlet
+ /*
+
+
\ No newline at end of file
diff --git a/maven/src/test/java/com/baeldung/maven/it/Integration.java b/maven/src/test/java/com/baeldung/maven/it/Integration.java
new file mode 100644
index 0000000000..112ce178ce
--- /dev/null
+++ b/maven/src/test/java/com/baeldung/maven/it/Integration.java
@@ -0,0 +1,4 @@
+package com.baeldung.maven.it;
+
+public interface Integration {
+}
diff --git a/maven/src/test/java/com/baeldung/maven/it/RestIT.java b/maven/src/test/java/com/baeldung/maven/it/RestIT.java
new file mode 100644
index 0000000000..0115d34f1e
--- /dev/null
+++ b/maven/src/test/java/com/baeldung/maven/it/RestIT.java
@@ -0,0 +1,24 @@
+package com.baeldung.maven.it;
+
+import org.junit.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Scanner;
+
+import static org.junit.Assert.assertEquals;
+
+public class RestIT {
+ @Test
+ public void whenSendingGet_thenMessageIsReturned() throws IOException {
+ String url = "http://localhost:8999";
+ URLConnection connection = new URL(url).openConnection();
+ try (InputStream response = connection.getInputStream();
+ Scanner scanner = new Scanner(response)) {
+ String responseBody = scanner.nextLine();
+ assertEquals("Welcome to Baeldung!", responseBody);
+ }
+ }
+}
diff --git a/maven/src/test/java/com/baeldung/maven/it/RestIntegrationTest.java b/maven/src/test/java/com/baeldung/maven/it/RestIntegrationTest.java
new file mode 100644
index 0000000000..2f913c8429
--- /dev/null
+++ b/maven/src/test/java/com/baeldung/maven/it/RestIntegrationTest.java
@@ -0,0 +1,24 @@
+package com.baeldung.maven.it;
+
+import org.junit.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Scanner;
+
+import static org.junit.Assert.assertEquals;
+
+public class RestIntegrationTest {
+ @Test
+ public void whenSendingGet_thenMessageIsReturned() throws IOException {
+ String url = "http://localhost:8999";
+ URLConnection connection = new URL(url).openConnection();
+ try (InputStream response = connection.getInputStream();
+ Scanner scanner = new Scanner(response)) {
+ String responseBody = scanner.nextLine();
+ assertEquals("Welcome to Baeldung!", responseBody);
+ }
+ }
+}
diff --git a/maven/src/test/java/com/baeldung/maven/it/RestJUnitTest.java b/maven/src/test/java/com/baeldung/maven/it/RestJUnitTest.java
new file mode 100644
index 0000000000..60995d75bd
--- /dev/null
+++ b/maven/src/test/java/com/baeldung/maven/it/RestJUnitTest.java
@@ -0,0 +1,26 @@
+package com.baeldung.maven.it;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Scanner;
+
+import static org.junit.Assert.assertEquals;
+
+@Category(Integration.class)
+public class RestJUnitTest {
+ @Test
+ public void whenSendingGet_thenMessageIsReturned() throws IOException {
+ String url = "http://localhost:8999";
+ URLConnection connection = new URL(url).openConnection();
+ try (InputStream response = connection.getInputStream();
+ Scanner scanner = new Scanner(response)) {
+ String responseBody = scanner.nextLine();
+ assertEquals("Welcome to Baeldung!", responseBody);
+ }
+ }
+}
diff --git a/maven/src/test/java/testfail/TestFail.java b/maven/src/test/java/testfail/TestFail.java
index 16f1619db4..3febd21031 100644
--- a/maven/src/test/java/testfail/TestFail.java
+++ b/maven/src/test/java/testfail/TestFail.java
@@ -1,10 +1,13 @@
package testfail;
import org.junit.Test;
+import org.junit.Ignore;
import static org.junit.Assert.assertNotNull;
public class TestFail {
+
+ @Ignore //ignored so the entire tutorials build passes
@Test
public void whenMessageAssigned_thenItIsNotNull() {
String message = "hello there";
diff --git a/optaplanner/pom.xml b/optaplanner/pom.xml
new file mode 100644
index 0000000000..22abbedc8c
--- /dev/null
+++ b/optaplanner/pom.xml
@@ -0,0 +1,27 @@
+
+
+
+ parent-modules
+ com.baeldung
+ 1.0.0-SNAPSHOT
+
+ 4.0.0
+
+ optaplanner
+
+
+
+ org.optaplanner
+ optaplanner-core
+ 7.9.0.Final
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/optaplanner/src/main/java/com/baeldung/optaplanner/CourseSchedule.java b/optaplanner/src/main/java/com/baeldung/optaplanner/CourseSchedule.java
new file mode 100644
index 0000000000..8a820ab56e
--- /dev/null
+++ b/optaplanner/src/main/java/com/baeldung/optaplanner/CourseSchedule.java
@@ -0,0 +1,63 @@
+package com.baeldung.optaplanner;
+
+import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty;
+import org.optaplanner.core.api.domain.solution.PlanningScore;
+import org.optaplanner.core.api.domain.solution.PlanningSolution;
+import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty;
+import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider;
+import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@PlanningSolution
+public class CourseSchedule {
+
+ Logger logger = LoggerFactory.getLogger("CourseSchedule");
+
+ private List roomList;
+ private List periodList;
+ private List lectureList;
+ private HardSoftScore score;
+
+ public CourseSchedule(){
+ roomList = new ArrayList<>();
+ periodList = new ArrayList<>();
+ lectureList = new ArrayList<>();
+ }
+
+ @ValueRangeProvider(id = "availableRooms")
+ @ProblemFactCollectionProperty
+ public List getRoomList() {
+ return roomList;
+ }
+
+ @ValueRangeProvider(id = "availablePeriods")
+ @ProblemFactCollectionProperty
+ public List getPeriodList() {
+ return periodList;
+ }
+
+ @PlanningEntityCollectionProperty
+ public List getLectureList() {
+ return lectureList;
+ }
+
+ @PlanningScore
+ public HardSoftScore getScore() {
+ return score;
+ }
+
+ public void setScore(HardSoftScore score) {
+ this.score = score;
+ }
+
+ public void printCourseSchedule() {
+ lectureList.stream()
+ .map(c -> "Lecture in Room " + c.getRoomNumber().toString() + " during Period " + c.getPeriod().toString())
+ .forEach(k -> logger.info(k));
+ }
+
+}
diff --git a/optaplanner/src/main/java/com/baeldung/optaplanner/Lecture.java b/optaplanner/src/main/java/com/baeldung/optaplanner/Lecture.java
new file mode 100644
index 0000000000..48af4e89d1
--- /dev/null
+++ b/optaplanner/src/main/java/com/baeldung/optaplanner/Lecture.java
@@ -0,0 +1,30 @@
+package com.baeldung.optaplanner;
+
+import org.optaplanner.core.api.domain.entity.PlanningEntity;
+import org.optaplanner.core.api.domain.variable.PlanningVariable;
+
+@PlanningEntity
+public class Lecture {
+
+ private Integer roomNumber;
+ private Integer period;
+
+ @PlanningVariable(valueRangeProviderRefs = {"availablePeriods"})
+ public Integer getPeriod() {
+ return period;
+ }
+
+ @PlanningVariable(valueRangeProviderRefs = {"availableRooms"})
+ public Integer getRoomNumber() {
+ return roomNumber;
+ }
+
+ public void setPeriod(Integer period) {
+ this.period = period;
+ }
+
+ public void setRoomNumber(Integer roomNumber) {
+ this.roomNumber = roomNumber;
+ }
+
+}
diff --git a/optaplanner/src/main/java/com/baeldung/optaplanner/ScoreCalculator.java b/optaplanner/src/main/java/com/baeldung/optaplanner/ScoreCalculator.java
new file mode 100644
index 0000000000..11e5e4a5be
--- /dev/null
+++ b/optaplanner/src/main/java/com/baeldung/optaplanner/ScoreCalculator.java
@@ -0,0 +1,32 @@
+package com.baeldung.optaplanner;
+
+import org.optaplanner.core.api.score.Score;
+import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
+import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator;
+
+import java.util.HashSet;
+
+public class ScoreCalculator implements EasyScoreCalculator {
+
+ @Override
+ public Score calculateScore(CourseSchedule courseSchedule) {
+ int hardScore = 0;
+ int softScore = 0;
+
+ HashSet occupiedRooms = new HashSet<>();
+ for (Lecture lecture : courseSchedule.getLectureList()) {
+ if(lecture.getPeriod() != null && lecture.getRoomNumber() != null) {
+ String roomInUse = lecture.getPeriod().toString() + ":" + lecture.getRoomNumber().toString();
+ if (occupiedRooms.contains(roomInUse)) {
+ hardScore += -1;
+ } else {
+ occupiedRooms.add(roomInUse);
+ }
+ } else {
+ hardScore += -1;
+ }
+ }
+
+ return HardSoftScore.valueOf(hardScore, softScore);
+ }
+}
diff --git a/optaplanner/src/main/resources/courseSchedule.drl b/optaplanner/src/main/resources/courseSchedule.drl
new file mode 100644
index 0000000000..9372a24976
--- /dev/null
+++ b/optaplanner/src/main/resources/courseSchedule.drl
@@ -0,0 +1,14 @@
+package com.baeldung.optaplanner
+
+import com.baeldung.optaplanner.Lecture;
+import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder;
+
+global HardSoftScoreHolder scoreHolder;
+
+rule "noNullRoomPeriod"
+ when
+ Lecture( roomNumber == null );
+ Lecture( period == null );
+ then
+ scoreHolder.addHardConstraintMatch(kcontext, -1);
+end
\ No newline at end of file
diff --git a/optaplanner/src/main/resources/courseScheduleSolverConfigDrools.xml b/optaplanner/src/main/resources/courseScheduleSolverConfigDrools.xml
new file mode 100644
index 0000000000..7cf95fdcd3
--- /dev/null
+++ b/optaplanner/src/main/resources/courseScheduleSolverConfigDrools.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+ courseSchedule.drl
+
+
+
+ 10
+
+
\ No newline at end of file
diff --git a/optaplanner/src/main/resources/courseScheduleSolverConfiguration.xml b/optaplanner/src/main/resources/courseScheduleSolverConfiguration.xml
new file mode 100644
index 0000000000..0ad2264dcd
--- /dev/null
+++ b/optaplanner/src/main/resources/courseScheduleSolverConfiguration.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+ com.baeldung.optaplanner.ScoreCalculator
+
+
+
+ 10
+
+
\ No newline at end of file
diff --git a/optaplanner/src/main/resources/logback.xml b/optaplanner/src/main/resources/logback.xml
new file mode 100644
index 0000000000..c109aa19e2
--- /dev/null
+++ b/optaplanner/src/main/resources/logback.xml
@@ -0,0 +1,3 @@
+
+
+
\ No newline at end of file
diff --git a/optaplanner/src/test/java/com/baeldung/optaplanner/test/OptaPlannerUnitTest.java b/optaplanner/src/test/java/com/baeldung/optaplanner/test/OptaPlannerUnitTest.java
new file mode 100644
index 0000000000..2847a233a5
--- /dev/null
+++ b/optaplanner/src/test/java/com/baeldung/optaplanner/test/OptaPlannerUnitTest.java
@@ -0,0 +1,50 @@
+package com.baeldung.optaplanner.test;
+
+import com.baeldung.optaplanner.CourseSchedule;
+import com.baeldung.optaplanner.Lecture;
+import org.junit.Assert;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.optaplanner.core.api.solver.Solver;
+import org.optaplanner.core.api.solver.SolverFactory;
+import java.util.Arrays;
+
+public class OptaPlannerUnitTest {
+
+ static CourseSchedule unsolvedCourseSchedule;
+
+ @BeforeAll
+ public static void setUp() {
+
+ unsolvedCourseSchedule = new CourseSchedule();
+
+ for(int i = 0; i < 10; i++){
+ unsolvedCourseSchedule.getLectureList().add(new Lecture());
+ }
+
+ unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(new Integer[] { 1, 2, 3 }));
+ unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(new Integer[] { 1, 2 }));
+ }
+
+ @Test
+ public void test_whenCustomJavaSolver() {
+
+ SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfiguration.xml");
+ Solver solver = solverFactory.buildSolver();
+ CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule);
+
+ Assert.assertNotNull(solvedCourseSchedule.getScore());
+ Assert.assertEquals(-4, solvedCourseSchedule.getScore().getHardScore());
+ }
+
+ @Test
+ public void test_whenDroolsSolver() {
+
+ SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfigDrools.xml");
+ Solver solver = solverFactory.buildSolver();
+ CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule);
+
+ Assert.assertNotNull(solvedCourseSchedule.getScore());
+ Assert.assertEquals(0, solvedCourseSchedule.getScore().getHardScore());
+ }
+}
diff --git a/orika/src/main/resources/logback.xml b/orika/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/orika/src/main/resources/logback.xml
+++ b/orika/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/out/production/generated-sources8/src.main.resources.reladomo.ReladomoClassList.xml.log b/out/production/generated-sources8/src.main.resources.reladomo.ReladomoClassList.xml.log
deleted file mode 100644
index 0bd4e29a45..0000000000
--- a/out/production/generated-sources8/src.main.resources.reladomo.ReladomoClassList.xml.log
+++ /dev/null
@@ -1,2 +0,0 @@
-f5a6ba3b942a82fcbfb72e61502d5c30
-9201deea
diff --git a/out/production/introduction/views/index.scala.html b/out/production/introduction/views/index.scala.html
deleted file mode 100644
index 4539f5a10b..0000000000
--- a/out/production/introduction/views/index.scala.html
+++ /dev/null
@@ -1,20 +0,0 @@
-@*
- * This template takes a single argument, a String containing a
- * message to display.
- *@
-@(message: String)
-
-@*
- * Call the `main` template with two arguments. The first
- * argument is a `String` with the title of the page, the second
- * argument is an `Html` object containing the body of the page.
- *@
-@main("Welcome to Play") {
-
- @*
- * Get an `Html` object by calling the built-in Play welcome
- * template and passing a `String` message.
- *@
- @play20.welcome(message, style = "Java")
-
-}
diff --git a/out/production/introduction/views/main.scala.html b/out/production/introduction/views/main.scala.html
deleted file mode 100644
index 9414f4be6e..0000000000
--- a/out/production/introduction/views/main.scala.html
+++ /dev/null
@@ -1,23 +0,0 @@
-@*
- * This template is called from the `index` template. This template
- * handles the rendering of the page header and body tags. It takes
- * two arguments, a `String` for the title of the page and an `Html`
- * object to insert into the body of the page.
- *@
-@(title: String)(content: Html)
-
-
-
-
- @* Here's where we render the page title `String`. *@
- @title
-
-
-
-
-
- @* And here's where we render the `Html` object containing
- * the page content. *@
- @content
-
-
diff --git a/out/production/main/com/baeldung/.gitignore b/out/production/main/com/baeldung/.gitignore
new file mode 100644
index 0000000000..83c05e60c8
--- /dev/null
+++ b/out/production/main/com/baeldung/.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/out/production/main151/com/baeldung/README.md b/out/production/main/com/baeldung/README.md
similarity index 100%
rename from out/production/main151/com/baeldung/README.md
rename to out/production/main/com/baeldung/README.md
diff --git a/out/production/main330/com/baeldung/enums/README.md b/out/production/main/com/baeldung/enums/README.md
similarity index 100%
rename from out/production/main330/com/baeldung/enums/README.md
rename to out/production/main/com/baeldung/enums/README.md
diff --git a/out/production/main330/com/baeldung/networking/README.md b/out/production/main/com/baeldung/networking/README.md
similarity index 100%
rename from out/production/main330/com/baeldung/networking/README.md
rename to out/production/main/com/baeldung/networking/README.md
diff --git a/out/production/main/com/baeldung/objectsize/MANIFEST.MF b/out/production/main/com/baeldung/objectsize/MANIFEST.MF
new file mode 100644
index 0000000000..b814f624d0
--- /dev/null
+++ b/out/production/main/com/baeldung/objectsize/MANIFEST.MF
@@ -0,0 +1 @@
+Premain-class: com.baeldung.objectsize.InstrumentationAgent
diff --git a/out/production/main330/com/baeldung/printscreen/README.md b/out/production/main/com/baeldung/printscreen/README.md
similarity index 100%
rename from out/production/main330/com/baeldung/printscreen/README.md
rename to out/production/main/com/baeldung/printscreen/README.md
diff --git a/out/production/main/javac-args/arguments b/out/production/main/javac-args/arguments
new file mode 100644
index 0000000000..51639800a7
--- /dev/null
+++ b/out/production/main/javac-args/arguments
@@ -0,0 +1,2 @@
+-d javac-target -verbose
+com/baeldung/javac/Data.java
\ No newline at end of file
diff --git a/out/production/main/javac-args/options b/out/production/main/javac-args/options
new file mode 100644
index 0000000000..f02f2344ff
--- /dev/null
+++ b/out/production/main/javac-args/options
@@ -0,0 +1,2 @@
+-d javac-target
+-verbose
\ No newline at end of file
diff --git a/out/production/main/javac-args/types b/out/production/main/javac-args/types
new file mode 100644
index 0000000000..ef2d861f84
--- /dev/null
+++ b/out/production/main/javac-args/types
@@ -0,0 +1 @@
+com/baeldung/javac/Data.java
\ No newline at end of file
diff --git a/out/production/main/javac-args/xlint-ops b/out/production/main/javac-args/xlint-ops
new file mode 100644
index 0000000000..cdccbc0cce
--- /dev/null
+++ b/out/production/main/javac-args/xlint-ops
@@ -0,0 +1,3 @@
+-d javac-target
+-Xlint:rawtypes,unchecked,static,cast,serial,fallthrough
+com/baeldung/javac/Data.java
\ No newline at end of file
diff --git a/out/production/main173/log4j.properties b/out/production/main/log4j.properties
similarity index 100%
rename from out/production/main173/log4j.properties
rename to out/production/main/log4j.properties
diff --git a/out/production/main237/com/baeldung/datetime/README.md b/out/production/main1/com/baeldung/datetime/README.md
similarity index 100%
rename from out/production/main237/com/baeldung/datetime/README.md
rename to out/production/main1/com/baeldung/datetime/README.md
diff --git a/out/production/main155/com/baeldung/git/README.md b/out/production/main155/com/baeldung/git/README.md
deleted file mode 100644
index 7e6a597c28..0000000000
--- a/out/production/main155/com/baeldung/git/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-### Relevant Articles:
-- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information)
diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt
deleted file mode 100644
index bffe24e485..0000000000
--- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt
+++ /dev/null
@@ -1,76 +0,0 @@
-About the application
----------------------
-This application demonstrates the usage of JavaEE Web Annotations.
-
-
-Contents of the application
----------------------------
-1. AccountServlet.java - Demonstrates the @WebServlet and @ServletSecurity annotation.
-
-NOTES: @WebServlet annotation designates the AccountServlet class as a Servlet component.
- The usage of its parameters 'urlPatterns' & 'initParams' can be observed.
- An initialization parameter 'type' is being set to denote the type of the bank account.
-
- @ServletSecurity annotation imposes security constraints on the AccountServlet based on
- the tomcat-users.xml.
-
- This code assumes that your tomcat-users.xml looks as follows:
-
-
-
-
-
-
-
-
-N.B : To see @ServletSecurity annotation in action, please uncomment the annotation code
- for @ServletSecurity.
-
-
-2. BankAppServletContextListener.java - Demonstrates the @WebListener annotation for denoting a class as a ServletContextListener.
-
-NOTES: Sets a Servlet context attribute ATTR_DEFAULT_LANGUAGE to 'english' on web application start up,
- which can then be used throughout the application.
-
-
-3. LogInFilter.java - Demonstrates the @WebFilter annotation.
-
-NOTES: @WebFilter annotation designates the LogInFilter class as a Filter component.
- It filters all requests to the bank account servlet and redirects them to
- the login page.
-
-N.B : To see @WebFilter annotation in action, please uncomment the annotation code for @WebFilter.
-
-
-4. UploadCustomerDocumentsServlet.java - Demonstrates the @MultipartConfig annotation.
-
-NOTES: @MultipartConfig anotation designates the UploadCustomerDocumentsServlet Servlet component,
- to handle multipart/form-data requests.
- To see it in action, deploy the web application an access the url: http://:/JavaEEAnnotationsSample/upload.jsp
- Once you upload a file from here, it will get uploaded to D:/custDocs (assuming such a folder exists).
-
-
-5. index.jsp - This is the welcome page.
-
-NOTES: You can enter a deposit amount here and click on the 'Deposit' button to see the AccountServlet in action.
-
-6. login.jsp - All requests to the AccountServlet are redirected to this page, if the LogInFilter is imposed.
-
-7. upload.jsp - Demonstrates the usage of handling multipart/form-data requests by the UploadCustomerDocumentsServlet.
-
-
-Building and Running the application
-------------------------------------
-To build the application:
-
-1. Open the project in eclipse
-2. Right click on it in eclispe and choose Run As > Maven build
-3. Give 'clean install' under Goals
-4. This should build the WAR file of the application
-
-To run the application:
-
-1. Right click on the project
-2. Run as > Run on Server
-3. This will start you Tomcat server and deploy the application (Provided that you have configured Tomcat in your eclipse)
-4. You should now be able to access the url : http://:/JavaEEAnnotationsSample
diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml
deleted file mode 100644
index 25f901459c..0000000000
--- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml
+++ /dev/null
@@ -1,57 +0,0 @@
-
- 4.0.0
- com.baeldung.javaeeannotations
- JavaEEAnnotationsSample
- 0.0.1-SNAPSHOT
- war
- JavaEEAnnotationsSample
- JavaEEAnnotationsSample
-
-
-
-
- javax.annotation
- javax.annotation-api
- ${annotation-api.version}
-
-
-
- javax.servlet
- javax.servlet-api
- ${servlet.version}
-
-
-
- javax.servlet.jsp
- jsp-api
- ${jsp.version}
-
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-war-plugin
- ${maven-war-plugin.version}
-
- src/main/webapp
- SpringFieldConstructorInjection
- false
-
-
-
-
- JavaEEAnnotationsSample
-
-
-
- 1.3
- 3.1.0
- 2.1
- 2.4
-
-
\ No newline at end of file
diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index a92885ec11..0000000000
--- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
- BASIC
- default
-
-
diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp
deleted file mode 100644
index c49dec859e..0000000000
--- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp
+++ /dev/null
@@ -1,16 +0,0 @@
-<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
- pageEncoding="ISO-8859-1"%>
-
-
-
-
-My Account
-
-
-
-
-
\ No newline at end of file
diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp
deleted file mode 100644
index 6892cb0420..0000000000
--- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp
+++ /dev/null
@@ -1,12 +0,0 @@
-<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
- pageEncoding="ISO-8859-1"%>
-
-
-
-
-Login
-
-
-Login Here...
-
-
\ No newline at end of file
diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp
deleted file mode 100644
index 3601322ef0..0000000000
--- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp
+++ /dev/null
@@ -1,16 +0,0 @@
-<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
- pageEncoding="ISO-8859-1"%>
-
-
-
-
-Insert title here
-
-
-
-
-
\ No newline at end of file
diff --git a/out/production/main180/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl b/out/production/main180/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl
deleted file mode 100644
index 426717f90e..0000000000
--- a/out/production/main180/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl
+++ /dev/null
@@ -1,42 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/out/production/main195/com/baeldung/java/nio/selector/README.md b/out/production/main195/com/baeldung/java/nio/selector/README.md
deleted file mode 100644
index b28aae1397..0000000000
--- a/out/production/main195/com/baeldung/java/nio/selector/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-###Relevant Articles:
-- [Introduction to the Java NIO Selector](http://www.baeldung.com/java-nio-selector)
diff --git a/out/production/main216/com/baeldung/googlehttpclientguide/logging.properties b/out/production/main216/com/baeldung/googlehttpclientguide/logging.properties
deleted file mode 100644
index 02489378df..0000000000
--- a/out/production/main216/com/baeldung/googlehttpclientguide/logging.properties
+++ /dev/null
@@ -1,10 +0,0 @@
-# Properties file which configures the operation of the JDK logging facility.
-# The system will look for this config file to be specified as a system property:
-# -Djava.util.logging.config.file=${project_loc:dailymotion-simple-cmdline-sample}/logging.properties
-
-# Set up the console handler (uncomment "level" to show more fine-grained messages)
-handlers = java.util.logging.ConsoleHandler
-java.util.logging.ConsoleHandler.level = ALL
-
-# Set up logging of HTTP requests and responses (uncomment "level" to show)
-com.google.api.client.http.level = ALL
diff --git a/out/production/main231/com/baeldung/wicket/examples/HelloWorld.html b/out/production/main231/com/baeldung/wicket/examples/HelloWorld.html
deleted file mode 100644
index 497e98e01a..0000000000
--- a/out/production/main231/com/baeldung/wicket/examples/HelloWorld.html
+++ /dev/null
@@ -1,52 +0,0 @@
-
-
-
-
-Wicket Intro Examples
-
-
-
-
-
-
diff --git a/out/production/main231/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html b/out/production/main231/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html
deleted file mode 100644
index c5ada2323d..0000000000
--- a/out/production/main231/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
-
-
-Cafes
-
-
-
-
-
- Address: address
-
-
-
-
diff --git a/out/production/main231/com/baeldung/wicket/examples/helloworld/HelloWorld.html b/out/production/main231/com/baeldung/wicket/examples/helloworld/HelloWorld.html
deleted file mode 100644
index c56d07fc10..0000000000
--- a/out/production/main231/com/baeldung/wicket/examples/helloworld/HelloWorld.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/out/production/main234/com/baeldung/activiti/security.rar b/out/production/main234/com/baeldung/activiti/security.rar
deleted file mode 100644
index 38c4946168..0000000000
Binary files a/out/production/main234/com/baeldung/activiti/security.rar and /dev/null differ
diff --git a/out/production/main291/xml-bean-config.xml b/out/production/main291/xml-bean-config.xml
deleted file mode 100644
index 3b880bbd70..0000000000
--- a/out/production/main291/xml-bean-config.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/out/production/main30/com/baeldung/factorybean/README.md b/out/production/main30/com/baeldung/factorybean/README.md
deleted file mode 100644
index 13f9f379e0..0000000000
--- a/out/production/main30/com/baeldung/factorybean/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-### Relevant Articles:
-- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)
diff --git a/out/production/main330/com/baeldung/README.md b/out/production/main330/com/baeldung/README.md
deleted file mode 100644
index 51809b2882..0000000000
--- a/out/production/main330/com/baeldung/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-### Relevant Articles:
-- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java)
diff --git a/out/production/main330/log4j.properties b/out/production/main330/log4j.properties
deleted file mode 100644
index 5fe42d854c..0000000000
--- a/out/production/main330/log4j.properties
+++ /dev/null
@@ -1,9 +0,0 @@
-# Set root logger level to DEBUG and its only appender to A1.
-log4j.rootLogger=DEBUG, A1
-
-# A1 is set to be a ConsoleAppender.
-log4j.appender.A1=org.apache.log4j.ConsoleAppender
-
-# A1 uses PatternLayout.
-log4j.appender.A1.layout=org.apache.log4j.PatternLayout
-log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
diff --git a/out/production/main351/com/baeldung/produceimage/README.md b/out/production/main351/com/baeldung/produceimage/README.md
deleted file mode 100644
index acd546598d..0000000000
--- a/out/production/main351/com/baeldung/produceimage/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-### Relevant articles
-
-- [Returning an Image or a File with Spring](http://www.baeldung.com/spring-controller-return-image-file)
diff --git a/out/production/main96/com/baeldung/git/README.md b/out/production/main96/com/baeldung/git/README.md
deleted file mode 100644
index 7e6a597c28..0000000000
--- a/out/production/main96/com/baeldung/git/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-### Relevant Articles:
-- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information)
diff --git a/out/production/routing-in-play/views/index.scala.html b/out/production/routing-in-play/views/index.scala.html
deleted file mode 100644
index 4539f5a10b..0000000000
--- a/out/production/routing-in-play/views/index.scala.html
+++ /dev/null
@@ -1,20 +0,0 @@
-@*
- * This template takes a single argument, a String containing a
- * message to display.
- *@
-@(message: String)
-
-@*
- * Call the `main` template with two arguments. The first
- * argument is a `String` with the title of the page, the second
- * argument is an `Html` object containing the body of the page.
- *@
-@main("Welcome to Play") {
-
- @*
- * Get an `Html` object by calling the built-in Play welcome
- * template and passing a `String` message.
- *@
- @play20.welcome(message, style = "Java")
-
-}
diff --git a/out/production/routing-in-play/views/main.scala.html b/out/production/routing-in-play/views/main.scala.html
deleted file mode 100644
index 9414f4be6e..0000000000
--- a/out/production/routing-in-play/views/main.scala.html
+++ /dev/null
@@ -1,23 +0,0 @@
-@*
- * This template is called from the `index` template. This template
- * handles the rendering of the page header and body tags. It takes
- * two arguments, a `String` for the title of the page and an `Html`
- * object to insert into the body of the page.
- *@
-@(title: String)(content: Html)
-
-
-
-
- @* Here's where we render the page title `String`. *@
- @title
-
-
-
-
-
- @* And here's where we render the `Html` object containing
- * the page content. *@
- @content
-
-
diff --git a/out/test/test95/com/baeldung/hexToAscii/README.md b/out/test/test/com/baeldung/hexToAscii/README.md
similarity index 100%
rename from out/test/test95/com/baeldung/hexToAscii/README.md
rename to out/test/test/com/baeldung/hexToAscii/README.md
diff --git a/out/test/test95/com/baeldung/java/conversion/README.md b/out/test/test/com/baeldung/java/conversion/README.md
similarity index 100%
rename from out/test/test95/com/baeldung/java/conversion/README.md
rename to out/test/test/com/baeldung/java/conversion/README.md
diff --git a/out/test/test/com/baeldung/stringisnumeric.zip b/out/test/test/com/baeldung/stringisnumeric.zip
new file mode 100644
index 0000000000..b8a7b9b35a
Binary files /dev/null and b/out/test/test/com/baeldung/stringisnumeric.zip differ
diff --git a/out/test/test105/com/baeldung/cglib/proxy/README.md b/out/test/test105/com/baeldung/cglib/proxy/README.md
deleted file mode 100644
index abeabc6162..0000000000
--- a/out/test/test105/com/baeldung/cglib/proxy/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-### Relevant articles
-
-- [Introduction to cglib](http://www.baeldung.com/cglib)
diff --git a/out/test/test143/com/baeldung/java9/README.MD b/out/test/test143/com/baeldung/java9/README.MD
deleted file mode 100644
index 2f44a2336b..0000000000
--- a/out/test/test143/com/baeldung/java9/README.MD
+++ /dev/null
@@ -1,2 +0,0 @@
-### Relevant Artiles:
-- [Filtering a Stream of Optionals in Java](http://www.baeldung.com/java-filter-stream-of-optional)
diff --git a/out/test/test174/org/baeldung/hamcrest/README.md b/out/test/test174/org/baeldung/hamcrest/README.md
deleted file mode 100644
index 7266ecda3a..0000000000
--- a/out/test/test174/org/baeldung/hamcrest/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-### Relevant Articles:
-- [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide)
diff --git a/out/test/test191/com/baeldung/web/controller/README.md b/out/test/test191/com/baeldung/web/controller/README.md
deleted file mode 100644
index 9923962dde..0000000000
--- a/out/test/test191/com/baeldung/web/controller/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-### Relevant Articles:
-- [WebAppConfiguration in Spring Tests](http://www.baeldung.com/spring-webappconfiguration)
diff --git a/out/test/test197/com/baeldung/java/nio2/README.md b/out/test/test197/com/baeldung/java/nio2/README.md
deleted file mode 100644
index 569be82d27..0000000000
--- a/out/test/test197/com/baeldung/java/nio2/README.md
+++ /dev/null
@@ -1,11 +0,0 @@
-### Relevant Articles:
-- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
-- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
-- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel)
-- [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng)
-- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
-- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor)
-- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute)
-- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)
-- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice)
-- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)
diff --git a/out/test/test237/META-INF/persistence.xml b/out/test/test237/META-INF/persistence.xml
deleted file mode 100644
index 922aedbc39..0000000000
--- a/out/test/test237/META-INF/persistence.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
- org.baeldung.persistence.model.Foo
- org.baeldung.persistence.model.Bar
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/out/test/test95/org/baeldung/java/collections/README.md b/out/test/test95/org/baeldung/java/collections/README.md
deleted file mode 100644
index 317d81fae7..0000000000
--- a/out/test/test95/org/baeldung/java/collections/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-### Relevant Articles:
-- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
-- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets)
diff --git a/out/test/test95/org/baeldung/java/lists/README.md b/out/test/test95/org/baeldung/java/lists/README.md
deleted file mode 100644
index 2a1e8aeeaa..0000000000
--- a/out/test/test95/org/baeldung/java/lists/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-### Relevant Articles:
-- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
diff --git a/out/test/test98/com/baeldung/applicationcontext/README.md b/out/test/test98/com/baeldung/applicationcontext/README.md
deleted file mode 100644
index 211007e0cf..0000000000
--- a/out/test/test98/com/baeldung/applicationcontext/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-### Relevant Articles:
-- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets)
-- [Intro to the Spring ClassPathXmlApplicationContext](http://www.baeldung.com/spring-classpathxmlapplicationcontext)
diff --git a/out/test/test98/com/baeldung/beanfactory/README.md b/out/test/test98/com/baeldung/beanfactory/README.md
deleted file mode 100644
index cff20a184b..0000000000
--- a/out/test/test98/com/baeldung/beanfactory/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-### Relevant Articles:
-- [Guide to the Spring BeanFactory](http://www.baeldung.com/spring-beanfactory)
diff --git a/parent-boot-1/pom.xml b/parent-boot-1/pom.xml
index e4902de0e6..c52327a42e 100644
--- a/parent-boot-1/pom.xml
+++ b/parent-boot-1/pom.xml
@@ -1,117 +1,54 @@
- 4.0.0
- com.baeldung
- parent-boot-1
- 0.0.1-SNAPSHOT
- pom
- Parent for all Spring Boot 1.x modules
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ parent-boot-1
+ 0.0.1-SNAPSHOT
+ pom
+ Parent for all Spring Boot 1.x modules
-
- org.springframework.boot
- spring-boot-starter-parent
- 1.5.13.RELEASE
-
-
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
-
-
- io.rest-assured
- rest-assured
- ${rest-assured.version}
-
-
- org.springframework.boot
- spring-boot-starter-test
- test
-
-
+
+
+
+ org.springframework.boot
+ spring-boot-dependencies
+ 1.5.15.RELEASE
+ pom
+ import
+
+
+
+
+
+ io.rest-assured
+ rest-assured
+ ${rest-assured.version}
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
- 3
- true
-
- **/*IntegrationTest.java
- **/*IntTest.java
- **/*LongRunningUnitTest.java
- **/*ManualTest.java
- **/*LiveTest.java
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
-
- ${maven.compiler.target}
-
-
-
-
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+ 1.5.15.RELEASE
+
+
+
-
-
- integration
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- integration-test
-
- test
-
-
-
- **/*ManualTest.java
- **/*LiveTest.java
- **/AutoconfigurationTest.java
- **/*UnitTest.java
-
-
- **/*IntegrationTest.java
- **/*IntTest.java
- */EthControllerTestOne.java
- **/*EntryPointsTest.java
-
-
-
-
-
-
- json
-
-
-
-
-
-
-
-
- UTF-8
- UTF-8
- 1.8
- 3.0.6
-
- 2.20.1
- 3.7.0
- 1.8
- 1.8
-
+
+ 3.1.0
+
\ No newline at end of file
diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml
index 2fc46e4c28..86a77a90db 100644
--- a/parent-boot-2/pom.xml
+++ b/parent-boot-2/pom.xml
@@ -1,7 +1,6 @@
4.0.0
- com.baeldung
parent-boot-2
0.0.1-SNAPSHOT
pom
@@ -18,7 +17,7 @@
org.springframework.boot
spring-boot-dependencies
- 2.0.1.RELEASE
+ 2.0.4.RELEASE
pom
import
@@ -41,10 +40,11 @@
org.springframework.boot
spring-boot-maven-plugin
- 2.0.1.RELEASE
+ 2.0.4.RELEASE
+
thin-jar
diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml
new file mode 100644
index 0000000000..7fd18e4fa4
--- /dev/null
+++ b/parent-kotlin/pom.xml
@@ -0,0 +1,194 @@
+
+
+ 4.0.0
+ parent-kotlin
+ pom
+ parent-kotlin
+ Parent for all kotlin modules
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ jcenter
+ http://jcenter.bintray.com
+
+
+ kotlin-ktor
+ https://dl.bintray.com/kotlin/ktor/
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-dependencies
+ 2.0.1.RELEASE
+ pom
+ import
+
+
+
+
+
+
+ org.jetbrains.kotlin
+ kotlin-stdlib-jdk8
+ ${kotlin.version}
+
+
+ org.jetbrains.kotlin
+ kotlin-reflect
+ ${kotlin.version}
+
+
+
+ org.jetbrains.kotlinx
+ kotlinx-coroutines-core
+ ${kotlinx.version}
+
+
+
+ io.ktor
+ ktor-server-netty
+ ${ktor.io.version}
+
+
+ io.ktor
+ ktor-gson
+ ${ktor.io.version}
+
+
+
+ org.jetbrains.kotlin
+ kotlin-test-junit
+ ${kotlin.version}
+ test
+
+
+
+
+
+
+
+ org.jetbrains.kotlin
+ kotlin-maven-plugin
+ ${kotlin.version}
+
+
+ compile
+
+ compile
+
+
+
+ ${project.basedir}/src/main/kotlin
+ ${project.basedir}/src/main/java
+
+ ${java.version}
+
+
+
+ test-compile
+
+ test-compile
+
+
+
+ ${project.basedir}/src/test/kotlin
+ ${project.basedir}/src/test/java
+
+ ${java.version}
+
+
+
+
+
+ spring
+
+
+
+
+ org.jetbrains.kotlin
+ kotlin-maven-allopen
+ ${kotlin.version}
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ ${java.version}
+
+
+
+
+ default-compile
+ none
+
+
+
+ default-testCompile
+ none
+
+
+ java-compile
+ compile
+
+ compile
+
+
+
+ java-test-compile
+ test-compile
+
+ testCompile
+
+
+
+
+
+ maven-failsafe-plugin
+ ${maven-failsafe-plugin.version}
+
+
+ org.junit.platform
+ junit-platform-surefire-provider
+ ${junit.platform.version}
+
+
+
+
+ junit5
+
+ integration-test
+ verify
+
+
+
+ **/*Test5.java
+
+
+
+
+
+
+
+
+
+ 1.2.61
+ 0.25.0
+ 0.9.3
+ 3.11.0
+ 1.2.0
+
+
diff --git a/persistence-modules/README.md b/persistence-modules/README.md
index 8f8c3eb13d..f12163bd6a 100644
--- a/persistence-modules/README.md
+++ b/persistence-modules/README.md
@@ -7,6 +7,5 @@
- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search)
- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
- [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce)
-- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging)
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md
index e9aabaaa74..418e0a67e2 100644
--- a/persistence-modules/java-jpa/README.md
+++ b/persistence-modules/java-jpa/README.md
@@ -1,3 +1,4 @@
# Relevant Articles
-* [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping)
+- [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping)
+- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)
\ No newline at end of file
diff --git a/jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/Car.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/Car.java
similarity index 100%
rename from jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/Car.java
rename to persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/Car.java
diff --git a/jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/QueryParameter.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/QueryParameter.java
similarity index 100%
rename from jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/QueryParameter.java
rename to persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/QueryParameter.java
diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml
index e9230eb6cd..3d881673b2 100644
--- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml
+++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml
@@ -20,4 +20,18 @@
+
+
+ org.hibernate.jpa.HibernatePersistenceProvider
+ com.baeldung.jpa.model.Car
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jpa-storedprocedure/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql b/persistence-modules/java-jpa/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql
similarity index 100%
rename from jpa-storedprocedure/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql
rename to persistence-modules/java-jpa/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql
diff --git a/jpa-storedprocedure/src/main/resources/config/database/create_table_mysql.sql b/persistence-modules/java-jpa/src/main/resources/config/database/create_table_mysql.sql
similarity index 100%
rename from jpa-storedprocedure/src/main/resources/config/database/create_table_mysql.sql
rename to persistence-modules/java-jpa/src/main/resources/config/database/create_table_mysql.sql
diff --git a/jpa-storedprocedure/src/main/resources/config/database/insert_cars.sql b/persistence-modules/java-jpa/src/main/resources/config/database/insert_cars.sql
similarity index 100%
rename from jpa-storedprocedure/src/main/resources/config/database/insert_cars.sql
rename to persistence-modules/java-jpa/src/main/resources/config/database/insert_cars.sql
diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java
similarity index 100%
rename from jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java
rename to persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java
diff --git a/jpa-storedprocedure/src/test/resources/persistence.xml b/persistence-modules/java-jpa/src/test/resources/persistence.xml
similarity index 100%
rename from jpa-storedprocedure/src/test/resources/persistence.xml
rename to persistence-modules/java-jpa/src/test/resources/persistence.xml
diff --git a/persistence-modules/spring-data-neo4j/pom.xml b/persistence-modules/spring-data-neo4j/pom.xml
index 923d877fd7..bd7d783646 100644
--- a/persistence-modules/spring-data-neo4j/pom.xml
+++ b/persistence-modules/spring-data-neo4j/pom.xml
@@ -37,18 +37,6 @@
org.springframework.data
spring-data-neo4j
${spring-data-neo4j.version}
-
-
- commons-logging
- commons-logging
-
-
-
-
- org.springframework.data
- spring-data-neo4j
- ${spring-data-neo4j.version}
- test-jar
com.voodoodyne.jackson.jsog
@@ -86,6 +74,11 @@
${neo4j-ogm.version}
test
+
+ org.neo4j
+ neo4j-ogm-embedded-driver
+ ${neo4j-ogm.version}
+
org.neo4j.test
neo4j-harness
@@ -96,23 +89,17 @@
org.springframework
spring-test
${spring-test.version}
-
-
- commons-logging
- commons-logging
-
-
- 1.1.1
- 3.1.0
- 4.1.6.RELEASE
+ 1.6.2
+ 3.4.6
+ 5.0.1.RELEASE
1.1
- 1.5.13.RELEASE
- 4.3.17.RELEASE
- 2.1.1
+ 2.0.1.RELEASE
+ 5.0.1.RELEASE
+ 3.1.2
diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java
index 344282d665..9bbc571aee 100644
--- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java
+++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java
@@ -1,5 +1,6 @@
package com.baeldung.spring.data.neo4j.config;
+import org.neo4j.ogm.config.Configuration.Builder;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@@ -8,15 +9,14 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" })
@Configuration
-@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
+@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repository")
public class MovieDatabaseNeo4jConfiguration {
public static final String URL = System.getenv("NEO4J_URL") != null ? System.getenv("NEO4J_URL") : "http://neo4j:movies@localhost:7474";
@Bean
public org.neo4j.ogm.config.Configuration getConfiguration() {
- org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
- config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver").setURI(URL);
+ org.neo4j.ogm.config.Configuration config = new Builder().uri(URL).build();
return config;
}
diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java
index fda478e5be..a4cbe4b809 100644
--- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java
+++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java
@@ -1,26 +1,25 @@
package com.baeldung.spring.data.neo4j.config;
+import org.neo4j.ogm.config.Configuration.Builder;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
-import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
+import org.springframework.data.neo4j.transaction.Neo4jTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" })
-@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
+@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repository")
@Profile({ "embedded", "test" })
-public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration {
+public class MovieDatabaseNeo4jTestConfiguration {
@Bean
public org.neo4j.ogm.config.Configuration getConfiguration() {
- final org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
- config.driverConfiguration()
- .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
+ org.neo4j.ogm.config.Configuration config = new Builder().build();
return config;
}
@@ -28,5 +27,10 @@ public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration {
public SessionFactory getSessionFactory() {
return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain");
}
+
+ @Bean
+ public Neo4jTransactionManager transactionManager() {
+ return new Neo4jTransactionManager(getSessionFactory());
+ }
}
diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java
index f2325a334f..455407a92b 100644
--- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java
+++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java
@@ -1,12 +1,13 @@
package com.baeldung.spring.data.neo4j.domain;
-import org.neo4j.ogm.annotation.GraphId;
+import org.neo4j.ogm.annotation.GeneratedValue;
+import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
@NodeEntity
public class Car {
- @GraphId
+ @Id @GeneratedValue
private Long id;
private String make;
diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java
index 029754c0fc..996a661b07 100644
--- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java
+++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java
@@ -2,7 +2,9 @@ package com.baeldung.spring.data.neo4j.domain;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.voodoodyne.jackson.jsog.JSOGGenerator;
-import org.neo4j.ogm.annotation.GraphId;
+
+import org.neo4j.ogm.annotation.GeneratedValue;
+import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
@@ -13,7 +15,7 @@ import java.util.List;
@NodeEntity
public class Movie {
- @GraphId
+ @Id @GeneratedValue
Long id;
private String title;
diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java
index dc5a850f29..453ca1c3f3 100644
--- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java
+++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java
@@ -2,7 +2,9 @@ package com.baeldung.spring.data.neo4j.domain;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.voodoodyne.jackson.jsog.JSOGGenerator;
-import org.neo4j.ogm.annotation.GraphId;
+
+import org.neo4j.ogm.annotation.GeneratedValue;
+import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
@@ -11,7 +13,7 @@ import java.util.List;
@JsonIdentityInfo(generator = JSOGGenerator.class)
@NodeEntity
public class Person {
- @GraphId
+ @Id @GeneratedValue
Long id;
private String name;
diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java
index 40dabb054b..5a18837dae 100644
--- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java
+++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java
@@ -3,7 +3,8 @@ package com.baeldung.spring.data.neo4j.domain;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.voodoodyne.jackson.jsog.JSOGGenerator;
import org.neo4j.ogm.annotation.EndNode;
-import org.neo4j.ogm.annotation.GraphId;
+import org.neo4j.ogm.annotation.GeneratedValue;
+import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.RelationshipEntity;
import org.neo4j.ogm.annotation.StartNode;
@@ -12,8 +13,8 @@ import java.util.Collection;
@JsonIdentityInfo(generator = JSOGGenerator.class)
@RelationshipEntity(type = "ACTED_IN")
public class Role {
- @GraphId
- Long id;
+ @Id @GeneratedValue
+ Long id;
private Collection roles;
@StartNode
private Person person;
diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java
similarity index 78%
rename from persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java
rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java
index afb82551e7..dde946ea73 100644
--- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java
+++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java
@@ -1,8 +1,8 @@
-package com.baeldung.spring.data.neo4j.repostory;
+package com.baeldung.spring.data.neo4j.repository;
import com.baeldung.spring.data.neo4j.domain.Movie;
import org.springframework.data.neo4j.annotation.Query;
-import org.springframework.data.neo4j.repository.GraphRepository;
+import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@@ -11,7 +11,7 @@ import java.util.List;
import java.util.Map;
@Repository
-public interface MovieRepository extends GraphRepository {
+public interface MovieRepository extends Neo4jRepository {
Movie findByTitle(@Param("title") String title);
diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java
new file mode 100644
index 0000000000..22094d26b6
--- /dev/null
+++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java
@@ -0,0 +1,9 @@
+package com.baeldung.spring.data.neo4j.repository;
+
+import com.baeldung.spring.data.neo4j.domain.Person;
+import org.springframework.data.neo4j.repository.Neo4jRepository;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface PersonRepository extends Neo4jRepository {
+}
diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java
deleted file mode 100644
index 4ac40ef75b..0000000000
--- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package com.baeldung.spring.data.neo4j.repostory;
-
-import com.baeldung.spring.data.neo4j.domain.Person;
-import org.springframework.data.neo4j.repository.GraphRepository;
-import org.springframework.stereotype.Repository;
-
-@Repository
-public interface PersonRepository extends GraphRepository {
-}
diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java
index ae1f6eb8e5..086bf48bfa 100644
--- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java
+++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java
@@ -1,10 +1,11 @@
package com.baeldung.spring.data.neo4j.services;
-import com.baeldung.spring.data.neo4j.repostory.MovieRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
+import com.baeldung.spring.data.neo4j.repository.MovieRepository;
+
import java.util.*;
@Service
diff --git a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java
index 06b31667dd..96e5e76402 100644
--- a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java
+++ b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java
@@ -12,14 +12,12 @@ import org.neo4j.ogm.session.SessionFactory;
import com.baeldung.spring.data.neo4j.domain.Car;
import com.baeldung.spring.data.neo4j.domain.Company;
-import org.neo4j.ogm.transaction.Transaction;
public class Neo4jOgmLiveTest {
@Test
public void testOgm() {
- Configuration conf = new Configuration();
- conf.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
+ Configuration conf = new Configuration.Builder().build();
SessionFactory factory = new SessionFactory(conf, "com.baeldung.spring.data.neo4j.domain");
Session session = factory.openSession();
diff --git a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java
index 95bc38aafc..3d9215f32f 100644
--- a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java
+++ b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java
@@ -4,8 +4,9 @@ import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration
import com.baeldung.spring.data.neo4j.domain.Movie;
import com.baeldung.spring.data.neo4j.domain.Person;
import com.baeldung.spring.data.neo4j.domain.Role;
-import com.baeldung.spring.data.neo4j.repostory.MovieRepository;
-import com.baeldung.spring.data.neo4j.repostory.PersonRepository;
+import com.baeldung.spring.data.neo4j.repository.MovieRepository;
+import com.baeldung.spring.data.neo4j.repository.PersonRepository;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -50,10 +51,10 @@ public class MovieRepositoryIntegrationTest {
Role charlie = new Role();
charlie.setMovie(italianJob);
charlie.setPerson(mark);
- Collection roleNames = new HashSet();
+ Collection roleNames = new HashSet<>();
roleNames.add("Charlie Croker");
charlie.setRoles(roleNames);
- List roles = new ArrayList();
+ List roles = new ArrayList<>();
roles.add(charlie);
italianJob.setRoles(roles);
movieRepository.save(italianJob);
diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md
index d48723ac31..b4d73708c3 100644
--- a/persistence-modules/spring-hibernate-5/README.md
+++ b/persistence-modules/spring-hibernate-5/README.md
@@ -3,3 +3,4 @@
- [Guide to @Immutable Annotation in Hibernate](http://www.baeldung.com/hibernate-immutable)
- [Hibernate Many to Many Annotation Tutorial](http://www.baeldung.com/hibernate-many-to-many)
- [Programmatic Transactions in the Spring TestContext Framework](http://www.baeldung.com/spring-test-programmatic-transactions)
+- [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries)
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/model/Item.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/model/Item.java
new file mode 100644
index 0000000000..957207b7e6
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/model/Item.java
@@ -0,0 +1,81 @@
+package com.baeldung.hibernate.criteria.model;
+
+import java.io.Serializable;
+
+public class Item implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+ private Integer itemId;
+ private String itemName;
+ private String itemDescription;
+ private Integer itemPrice;
+
+ // constructors
+ public Item() {
+
+ }
+
+ public Item(final Integer itemId, final String itemName, final String itemDescription) {
+ super();
+ this.itemId = itemId;
+ this.itemName = itemName;
+ this.itemDescription = itemDescription;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((itemId == null) ? 0 : itemId.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ final Item other = (Item) obj;
+ if (itemId == null) {
+ if (other.itemId != null)
+ return false;
+ } else if (!itemId.equals(other.itemId))
+ return false;
+ return true;
+ }
+
+ public Integer getItemId() {
+ return itemId;
+ }
+
+ public void setItemId(final Integer itemId) {
+ this.itemId = itemId;
+ }
+
+ public String getItemName() {
+ return itemName;
+ }
+
+ public void setItemName(final String itemName) {
+ this.itemName = itemName;
+ }
+
+ public String getItemDescription() {
+ return itemDescription;
+ }
+
+ public Integer getItemPrice() {
+ return itemPrice;
+ }
+
+ public void setItemPrice(final Integer itemPrice) {
+ this.itemPrice = itemPrice;
+ }
+
+ public void setItemDescription(final String itemDescription) {
+ this.itemDescription = itemDescription;
+ }
+}
diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java
similarity index 100%
rename from spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java
rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java
new file mode 100644
index 0000000000..72d4dea377
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java
@@ -0,0 +1,335 @@
+/**
+ * ApplicationViewer is the class that starts the application
+ * First it creates the session object and then creates the
+ * criteria query.
+ *
+ * @author Pritam Banerjee
+ * @version 1.0
+ * @since 07/20/2016
+ */
+
+package com.baeldung.hibernate.criteria.view;
+
+import java.util.List;
+
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Predicate;
+import javax.persistence.criteria.Root;
+
+import org.hibernate.Session;
+import org.hibernate.query.Query;
+
+import com.baeldung.hibernate.criteria.model.Item;
+import com.baeldung.hibernate.criteria.util.HibernateUtil;
+
+public class ApplicationView {
+
+ // default Constructor
+ public ApplicationView() {
+
+ }
+
+ public boolean checkIfCriteriaTimeLower() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery- cr = cb.createQuery(Item.class);
+ final Root
- root = cr.from(Item.class);
+
+ // calculate the time taken by criteria
+ final long startTimeCriteria = System.nanoTime();
+ cr.select(root)
+ .where(cb.like(root.get("itemName"), "%item One%"));
+ // .add(Restrictions.like("itemName", "%item One%"));
+ Query
- query = session.createQuery(cr);
+
+ final List
- results = query.getResultList();
+ final long endTimeCriteria = System.nanoTime();
+ final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000;
+
+ // calculate the time taken by HQL
+ final long startTimeHQL = System.nanoTime();
+ session.beginTransaction();
+ final List
- items = session.createQuery("FROM Item where itemName like '%item One%'")
+ .list();
+ final long endTimeHQL = System.nanoTime();
+ final long durationHQL = (endTimeHQL - startTimeHQL) / 1000;
+
+ if (durationCriteria > durationHQL) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ // To get items having price more than 1000
+ public String[] greaterThanCriteria() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery
- cr = cb.createQuery(Item.class);
+ final Root
- root = cr.from(Item.class);
+ cr.select(root)
+ .where(cb.gt(root.get("itemPrice"), 1000));
+ // cr.add(Restrictions.gt("itemPrice", 1000));
+ Query
- query = session.createQuery(cr);
+ final List
- greaterThanItemsList = query.getResultList();
+ final String greaterThanItems[] = new String[greaterThanItemsList.size()];
+ for (int i = 0; i < greaterThanItemsList.size(); i++) {
+ greaterThanItems[i] = greaterThanItemsList.get(i)
+ .getItemName();
+ }
+ session.close();
+ return greaterThanItems;
+ }
+
+ // To get items having price less than 1000
+ public String[] lessThanCriteria() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery
- cr = cb.createQuery(Item.class);
+ final Root
- root = cr.from(Item.class);
+ cr.select(root)
+ .where(cb.lt(root.get("itemPrice"), 1000));
+ // cr.add(Restrictions.lt("itemPrice", 1000));
+ Query
- query = session.createQuery(cr);
+ final List
- lessThanItemsList = query.getResultList();
+ final String lessThanItems[] = new String[lessThanItemsList.size()];
+ for (int i = 0; i < lessThanItemsList.size(); i++) {
+ lessThanItems[i] = lessThanItemsList.get(i)
+ .getItemName();
+ }
+ session.close();
+ return lessThanItems;
+ }
+
+ // To get items whose Name start with Chair
+ public String[] likeCriteria() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery
- cr = cb.createQuery(Item.class);
+ final Root
- root = cr.from(Item.class);
+ cr.select(root)
+ .where(cb.like(root.get("itemName"), "%chair%"));
+ // cr.add(Restrictions.like("itemName", "%chair%"));
+ Query
- query = session.createQuery(cr);
+ final List
- likeItemsList = query.getResultList();
+ final String likeItems[] = new String[likeItemsList.size()];
+ for (int i = 0; i < likeItemsList.size(); i++) {
+ likeItems[i] = likeItemsList.get(i)
+ .getItemName();
+ }
+ session.close();
+ return likeItems;
+ }
+
+ // Case sensitive search
+ public String[] likeCaseCriteria() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery
- cr = cb.createQuery(Item.class);
+ final Root
- root = cr.from(Item.class);
+ cr.select(root)
+ .where(cb.like(cb.lower(root.get("itemName")), "%chair%"));
+ // cr.add(Restrictions.ilike("itemName", "%Chair%"));
+ Query
- query = session.createQuery(cr);
+ final List
- ilikeItemsList = query.getResultList();
+ final String ilikeItems[] = new String[ilikeItemsList.size()];
+ for (int i = 0; i < ilikeItemsList.size(); i++) {
+ ilikeItems[i] = ilikeItemsList.get(i)
+ .getItemName();
+ }
+ session.close();
+ return ilikeItems;
+ }
+
+ // To get records having itemPrice in between 100 and 200
+ public String[] betweenCriteria() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery
- cr = cb.createQuery(Item.class);
+ final Root
- root = cr.from(Item.class);
+ cr.select(root)
+ .where(cb.between(root.get("itemPrice"), 100, 200));
+ // cr.add(Restrictions.between("itemPrice", 100, 200));
+ Query
- query = session.createQuery(cr);
+ final List
- betweenItemsList = query.getResultList();
+ final String betweenItems[] = new String[betweenItemsList.size()];
+ for (int i = 0; i < betweenItemsList.size(); i++) {
+ betweenItems[i] = betweenItemsList.get(i)
+ .getItemName();
+ }
+ session.close();
+ return betweenItems;
+ }
+
+ // To check if the given property is null
+ public String[] nullCriteria() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery
- cr = cb.createQuery(Item.class);
+ final Root
- root = cr.from(Item.class);
+ cr.select(root)
+ .where(cb.isNull(root.get("itemDescription")));
+ // cr.add(Restrictions.isNull("itemDescription"));
+ Query
- query = session.createQuery(cr);
+ final List
- nullItemsList = query.getResultList();
+ final String nullDescItems[] = new String[nullItemsList.size()];
+ for (int i = 0; i < nullItemsList.size(); i++) {
+ nullDescItems[i] = nullItemsList.get(i)
+ .getItemName();
+ }
+ session.close();
+ return nullDescItems;
+ }
+
+ // To check if the given property is not null
+ public String[] notNullCriteria() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery
- cr = cb.createQuery(Item.class);
+ final Root
- root = cr.from(Item.class);
+ cr.select(root)
+ .where(cb.isNotNull(root.get("itemDescription")));
+ // cr.add(Restrictions.isNotNull("itemDescription"));
+ Query
- query = session.createQuery(cr);
+ final List
- notNullItemsList = query.getResultList();
+ final String notNullDescItems[] = new String[notNullItemsList.size()];
+ for (int i = 0; i < notNullItemsList.size(); i++) {
+ notNullDescItems[i] = notNullItemsList.get(i)
+ .getItemName();
+ }
+ session.close();
+ return notNullDescItems;
+ }
+
+ // Adding more than one expression in one cr
+ public String[] twoCriteria() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery
- cr = cb.createQuery(Item.class);
+ final Root
- root = cr.from(Item.class);
+ Predicate[] predicates = new Predicate[2];
+ predicates[0] = cb.isNull(root.get("itemDescription"));
+ predicates[1] = cb.like(root.get("itemName"), "chair%");
+ cr.select(root)
+ .where(predicates);
+ // cr.add(Restrictions.isNull("itemDescription"));
+ // cr.add(Restrictions.like("itemName", "chair%"));
+ Query
- query = session.createQuery(cr);
+ final List
- notNullItemsList = query.getResultList();
+ final String notNullDescItems[] = new String[notNullItemsList.size()];
+ for (int i = 0; i < notNullItemsList.size(); i++) {
+ notNullDescItems[i] = notNullItemsList.get(i)
+ .getItemName();
+ }
+ session.close();
+ return notNullDescItems;
+ }
+
+ // To get items matching with the above defined conditions joined
+ // with Logical AND
+ public String[] andLogicalCriteria() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery
- cr = cb.createQuery(Item.class);
+ final Root
- root = cr.from(Item.class);
+ Predicate greaterThanPrice = cb.gt(root.get("itemPrice"), 1000);
+ Predicate chairItems = cb.like(root.get("itemName"), "Chair%");
+ cr.select(root)
+ .where(cb.and(greaterThanPrice, chairItems));
+ // final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000);
+ // final Criterion chairItems = Restrictions.like("itemName", "Chair%");
+ // final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems);
+ // cr.add(andExample);
+ Query
- query = session.createQuery(cr);
+ final List
- andItemsList = query.getResultList();
+ final String andItems[] = new String[andItemsList.size()];
+ for (int i = 0; i < andItemsList.size(); i++) {
+ andItems[i] = andItemsList.get(i)
+ .getItemName();
+ }
+ session.close();
+ return andItems;
+ }
+
+ // To get items matching with the above defined conditions joined
+ // with Logical OR
+ public String[] orLogicalCriteria() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery
- cr = cb.createQuery(Item.class);
+ final Root
- root = cr.from(Item.class);
+ Predicate greaterThanPrice = cb.gt(root.get("itemPrice"), 1000);
+ Predicate chairItems = cb.like(root.get("itemName"), "Chair%");
+ cr.select(root)
+ .where(cb.or(greaterThanPrice, chairItems));
+ Query
- query = session.createQuery(cr);
+ final List
- orItemsList = query.getResultList();
+ final String orItems[] = new String[orItemsList.size()];
+ for (int i = 0; i < orItemsList.size(); i++) {
+ orItems[i] = orItemsList.get(i)
+ .getItemName();
+ }
+ session.close();
+ return orItems;
+ }
+
+ // Sorting example
+ public String[] sortingCriteria() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery
- cr = cb.createQuery(Item.class);
+ final Root
- root = cr.from(Item.class);
+ cr.select(root);
+ cr.orderBy(cb.asc(root.get("itemName")), cb.desc(root.get("itemPrice")));
+ // cr.addOrder(Order.asc("itemName"));
+ // cr.addOrder(Order.desc("itemPrice")).list();
+ Query
- query = session.createQuery(cr);
+ final List
- sortedItemsList = query.getResultList();
+ final String sortedItems[] = new String[sortedItemsList.size()];
+ for (int i = 0; i < sortedItemsList.size(); i++) {
+ sortedItems[i] = sortedItemsList.get(i)
+ .getItemName();
+ }
+ session.close();
+ return sortedItems;
+ }
+
+ // Set projections Row Count
+ public Long[] projectionRowCount() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery cr = cb.createQuery(Long.class);
+ final Root
- root = cr.from(Item.class);
+ cr.select(cb.count(root));
+ Query query = session.createQuery(cr);
+ final List itemProjected = query.getResultList();
+ // session.createCriteria(Item.class).setProjection(Projections.rowCount()).list();
+ final Long projectedRowCount[] = new Long[itemProjected.size()];
+ for (int i = 0; i < itemProjected.size(); i++) {
+ projectedRowCount[i] = itemProjected.get(i);
+ }
+ session.close();
+ return projectedRowCount;
+ }
+
+ // Set projections average of itemPrice
+ public Double[] projectionAverage() {
+ final Session session = HibernateUtil.getHibernateSession();
+ final CriteriaBuilder cb = session.getCriteriaBuilder();
+ final CriteriaQuery cr = cb.createQuery(Double.class);
+ final Root
- root = cr.from(Item.class);
+ cr.select(cb.avg(root.get("itemPrice")));
+ Query query = session.createQuery(cr);
+ final List avgItemPriceList = query.getResultList();
+ // session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list();
+
+ final Double avgItemPrice[] = new Double[avgItemPriceList.size()];
+ for (int i = 0; i < avgItemPriceList.size(); i++) {
+ avgItemPrice[i] = (Double) avgItemPriceList.get(i);
+ }
+ session.close();
+ return avgItemPrice;
+ }
+
+}
diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/import.sql b/persistence-modules/spring-hibernate-5/src/main/resources/import.sql
new file mode 100644
index 0000000000..ae008f29bc
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/main/resources/import.sql
@@ -0,0 +1,31 @@
+insert into item (item_id, item_name, item_desc, item_price)
+values(1,'item One', 'test 1', 35.12);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(2,'Pogo stick', 'Pogo stick', 466.12);
+insert into item (item_id, item_name, item_desc, item_price)
+values(3,'Raft', 'Raft', 345.12);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(4,'Skate Board', 'Skating', 135.71);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(5,'Umbrella', 'Umbrella for Rain', 619.25);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(6,'Glue', 'Glue for home', 432.73);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(7,'Paint', 'Paint for Room', 1311.40);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(8,'Red paint', 'Red paint for room', 1135.71);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(9,'Household Chairs', 'Chairs for house', 25.71);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(10,'Office Chairs', 'Chairs for office', 395.98);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36);
diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java
similarity index 99%
rename from spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java
rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java
index 2275bf14f2..723b097305 100644
--- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java
+++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java
@@ -43,7 +43,6 @@ public class HibernateCriteriaIntegrationTest {
}
session.close();
assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria());
-
}
@Test
diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java
similarity index 100%
rename from spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java
rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java
diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java
similarity index 100%
rename from spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java
rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java
diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml b/persistence-modules/spring-hibernate-5/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml
similarity index 100%
rename from spring-hibernate4/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml
rename to persistence-modules/spring-hibernate-5/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml
diff --git a/spring-hibernate4/src/test/resources/criteria.cfg.xml b/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml
similarity index 85%
rename from spring-hibernate4/src/test/resources/criteria.cfg.xml
rename to persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml
index 726e9acb3f..bc4fed9680 100644
--- a/spring-hibernate4/src/test/resources/criteria.cfg.xml
+++ b/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml
@@ -10,8 +10,8 @@
sa
org.hibernate.dialect.H2Dialect
- update
- true
+ create-drop
+ false
\ No newline at end of file
diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/import.sql b/persistence-modules/spring-hibernate-5/src/test/resources/import.sql
new file mode 100644
index 0000000000..087d62d331
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/test/resources/import.sql
@@ -0,0 +1,21 @@
+insert into item (item_id, item_name, item_desc, item_price) values(1,'item One', 'test 1', 35.12);
+
+insert into item (item_id, item_name, item_desc, item_price) values(2,'Pogo stick', 'Pogo stick', 466.12);
+
+insert into item (item_id, item_name, item_desc, item_price) values(3,'Raft', 'Raft', 345.12);
+
+insert into item (item_id, item_name, item_desc, item_price) values(4,'Skate Board', 'Skating', 135.71);
+
+insert into item (item_id, item_name, item_desc, item_price) values(5,'Umbrella', 'Umbrella for Rain', 619.25);
+
+insert into item (item_id, item_name, item_desc, item_price) values(6,'Glue', 'Glue for home', 432.73);
+
+insert into item (item_id, item_name, item_desc, item_price) values(7,'Paint', 'Paint for Room', 1311.40);
+
+insert into item (item_id, item_name, item_desc, item_price) values(8,'Red paint', 'Red paint for room', 1135.71);
+
+insert into item (item_id, item_name, item_desc, item_price) values(9,'Household Chairs', 'Chairs for house', 25.71);
+
+insert into item (item_id, item_name, item_desc, item_price) values(10,'Office Chairs', 'Chairs for office', 395.98);
+
+insert into item (item_id, item_name, item_desc, item_price) values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36);
diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md
index 02d4306ecb..1c89f2453d 100644
--- a/persistence-modules/spring-jpa/README.md
+++ b/persistence-modules/spring-jpa/README.md
@@ -9,20 +9,15 @@
- [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa)
- [JPA Pagination](http://www.baeldung.com/jpa-pagination)
- [Sorting with JPA](http://www.baeldung.com/jpa-sort)
-- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases)
- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache)
- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource)
- [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate)
- [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database)
-- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories)
- [A Guide to Spring AbstractRoutingDatasource](http://www.baeldung.com/spring-abstract-routing-data-source)
-- [Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
- [A Guide to Hibernate with Spring 4](http://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
- [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types)
- [Obtaining Auto-generated Keys in Spring JDBC](http://www.baeldung.com/spring-jdbc-autogenerated-keys)
- [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
-- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
-- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
### Eclipse Config
After importing the project into Eclipse, you may see the following error:
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java
deleted file mode 100644
index 7e2efc72bc..0000000000
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package org.baeldung.extended.persistence.dao;
-
-import org.baeldung.inmemory.persistence.model.Student;
-
-public interface ExtendedStudentRepository extends ExtendedRepository {
-}
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/dao/BookRepositoryImpl.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/dao/BookRepositoryImpl.java
new file mode 100644
index 0000000000..f782d69e1e
--- /dev/null
+++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/dao/BookRepositoryImpl.java
@@ -0,0 +1,46 @@
+package org.baeldung.persistence.criteria.dao;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.TypedQuery;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Predicate;
+import javax.persistence.criteria.Root;
+
+import org.baeldung.persistence.criteria.model.Book;
+import org.baeldung.persistence.criteria.repository.BookRepositoryCustom;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public class BookRepositoryImpl implements BookRepositoryCustom {
+
+ private EntityManager em;
+
+ public BookRepositoryImpl(EntityManager em) {
+ this.em = em;
+ }
+
+ @Override
+ public List findBooksByAuthorNameAndTitle(String authorName, String title) {
+ CriteriaBuilder cb = em.getCriteriaBuilder();
+ CriteriaQuery cq = cb.createQuery(Book.class);
+
+ Root book = cq.from(Book.class);
+ List predicates = new ArrayList<>();
+
+ if (authorName != null) {
+ predicates.add(cb.equal(book.get("author"), authorName));
+ }
+ if (title != null) {
+ predicates.add(cb.like(book.get("title"), "%" + title + "%"));
+ }
+ cq.where(predicates.toArray(new Predicate[0]));
+
+ TypedQuery query = em.createQuery(cq);
+ return query.getResultList();
+ }
+
+}
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/model/Book.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/model/Book.java
new file mode 100644
index 0000000000..beb6c0190c
--- /dev/null
+++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/model/Book.java
@@ -0,0 +1,36 @@
+package org.baeldung.persistence.criteria.model;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+public class Book {
+
+ @Id
+ private Long id;
+
+ private String title;
+
+ private String author;
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getAuthor() {
+ return author;
+ }
+
+ public void setAuthor(String author) {
+ this.author = author;
+ }
+
+}
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepository.java
new file mode 100644
index 0000000000..af30ae461e
--- /dev/null
+++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepository.java
@@ -0,0 +1,9 @@
+package org.baeldung.persistence.criteria.repository;
+
+import org.baeldung.persistence.criteria.model.Book;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface BookRepository extends JpaRepository, BookRepositoryCustom, JpaSpecificationExecutor {
+
+}
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepositoryCustom.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepositoryCustom.java
new file mode 100644
index 0000000000..35330cfa3c
--- /dev/null
+++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepositoryCustom.java
@@ -0,0 +1,11 @@
+package org.baeldung.persistence.criteria.repository;
+
+import java.util.List;
+
+import org.baeldung.persistence.criteria.model.Book;
+
+public interface BookRepositoryCustom {
+
+ List findBooksByAuthorNameAndTitle(String authorName, String title);
+
+}
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookService.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookService.java
new file mode 100644
index 0000000000..7b1aff857e
--- /dev/null
+++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookService.java
@@ -0,0 +1,25 @@
+package org.baeldung.persistence.criteria.repository;
+
+import static org.baeldung.persistence.criteria.repository.BookSpecifications.hasAuthor;
+import static org.baeldung.persistence.criteria.repository.BookSpecifications.titleContains;
+import static org.springframework.data.jpa.domain.Specifications.where;
+
+import java.util.List;
+
+import org.baeldung.persistence.criteria.model.Book;
+import org.springframework.stereotype.Service;
+
+@Service
+public class BookService {
+
+ private BookRepository bookRepository;
+
+ public BookService(BookRepository bookRepository) {
+ this.bookRepository = bookRepository;
+ }
+
+ public List query(String author, String title) {
+ return bookRepository.findAll(where(hasAuthor(author)).and(titleContains(title)));
+ }
+
+}
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookSpecifications.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookSpecifications.java
new file mode 100644
index 0000000000..392b750977
--- /dev/null
+++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookSpecifications.java
@@ -0,0 +1,16 @@
+package org.baeldung.persistence.criteria.repository;
+
+import org.baeldung.persistence.criteria.model.Book;
+import org.springframework.data.jpa.domain.Specification;
+
+public class BookSpecifications {
+
+ public static Specification hasAuthor(String author) {
+ return (book, cq, cb) -> cb.equal(book.get("author"), author);
+ }
+
+ public static Specification titleContains(String title) {
+ return (book, cq, cb) -> cb.like(book.get("title"), "%" + title + "%");
+ }
+
+}
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/User.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/User.java
deleted file mode 100644
index f84a10cf76..0000000000
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/User.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package org.baeldung.persistence.model;
-
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-@Entity
-@Table(name = "users")
-public class User {
-
- @Id
- @GeneratedValue
- private Integer id;
- private String name;
- private Integer status;
-
- public User() {
- }
-
- public User(String name, Integer status) {
- this.name = name;
- this.status = status;
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public Integer getStatus() {
- return status;
- }
-
- public void setStatus(Integer status) {
- this.status = status;
- }
-}
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java
deleted file mode 100644
index e250a291bc..0000000000
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package org.baeldung.persistence.multiple.dao.user;
-
-import org.baeldung.persistence.multiple.model.user.User;
-import org.springframework.data.jpa.repository.JpaRepository;
-
-public interface UserRepository extends JpaRepository {
-
-}
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java
index 079888155e..7aff5f51d0 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java
+++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java
@@ -1,10 +1,6 @@
package org.baeldung.persistence.multiple.model.user;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import javax.persistence.*;
@Entity
@Table(schema = "spring_jpa_user")
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java
index 61904198f5..6fb9de4a47 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java
+++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java
@@ -1,15 +1,8 @@
package org.baeldung.persistence.multiple.model.user;
+import javax.persistence.*;
import java.util.List;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
-
@Entity
@Table(schema = "spring_jpa_user")
public class User {
diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java
index aa2dfb5293..beaa51f5f9 100644
--- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java
+++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java
@@ -8,7 +8,6 @@ import org.junit.runners.Suite;
FooPaginationPersistenceIntegrationTest.class
,FooServicePersistenceIntegrationTest.class
,FooServiceSortingIntegrationTest.class
- ,JpaMultipleDBIntegrationTest.class
,FooServiceSortingWitNullsManualIntegrationTest.class
}) // @formatter:on
public class PersistenceTestSuite {
diff --git a/pom.xml b/pom.xml
index db3bef7fda..be6029a946 100644
--- a/pom.xml
+++ b/pom.xml
@@ -321,6 +321,7 @@
parent-spring-4
parent-spring-5
parent-java
+ parent-kotlin
asm
atomix
apache-cayenne
@@ -342,15 +343,18 @@
azure
bootique
cdi
+ java-strings
core-java
core-java-collections
core-java-io
core-java-8
+ java-streams
core-java-persistence
core-kotlin
core-groovy
core-java-concurrency
+ core-java-concurrency-collections
couchbase
deltaspike
dozer
@@ -394,7 +398,6 @@
jee-7
jhipster/jhipster-monolithic
jjwt
- jpa-storedprocedure
jsf
json-path
json
@@ -434,6 +437,7 @@
testing-modules/rest-testing
resteasy
rxjava
+ rxjava-2
spring-swagger-codegen
testing-modules/selenium-junit-testng
persistence-modules/solr
@@ -441,6 +445,7 @@
spring-4
spring-5
spring-5-reactive
+ spring-5-reactive-security
spring-5-reactive-client
spring-5-mvc
spring-5-security
@@ -453,6 +458,7 @@
spring-batch
spring-bom
spring-boot
+ spring-boot-client
spring-boot-keycloak
spring-boot-bootstrap
spring-boot-admin
@@ -467,6 +473,7 @@
spring-core
spring-cucumber
spring-ejb
+ spring-ejb/spring-ejb-client
spring-aop
persistence-modules/spring-data-cassandra
spring-data-couchbase-2
@@ -510,6 +517,7 @@
spring-rest-full
spring-rest-query-language
spring-rest
+ spring-resttemplate
spring-rest-simple
spring-security-acl
spring-security-cache-control
@@ -584,6 +592,7 @@
spring-webflux-amqp
antlr
maven-archetype
+ optaplanner
apache-meecrowave
spring-reactive-kotlin
jnosql
@@ -633,7 +642,7 @@
parent-spring-4
parent-spring-5
parent-java
-
+ parent-kotlin
core-java-collections
core-java-io
core-java-8
+ java-streams
core-groovy
couchbase
@@ -933,7 +950,6 @@
jgroups
jee-7
jjwt
- jpa-storedprocedure
jsf
json-path
json
@@ -972,12 +988,14 @@
testing-modules/rest-testing
resteasy
rxjava
+ rxjava-2
spring-swagger-codegen
testing-modules/selenium-junit-testng
persistence-modules/solr
spark-java
spring-4
spring-5-reactive
+ spring-5-reactive-security
spring-5-reactive-client
spring-5-mvc
spring-5-security
@@ -1001,6 +1019,7 @@
spring-core
spring-cucumber
spring-ejb
+ spring-ejb/spring-ejb-client
spring-aop
persistence-modules/spring-data-dynamodb
@@ -1041,6 +1060,7 @@
spring-rest-full
spring-rest-query-language
spring-rest
+ spring-resttemplate
spring-rest-simple
spring-security-acl
spring-security-cache-control
@@ -1106,6 +1126,7 @@
spring-security-thymeleaf
persistence-modules/java-jdbi
jersey
+ jersey-client-rx
java-spi
performance-tests
twilio
@@ -1196,7 +1217,7 @@
parent-spring-4
parent-spring-5
parent-java
-
+ parent-kotlin
libraries
geotools
jhipster/jhipster-monolithic
@@ -1211,6 +1232,7 @@
hibernate5
spring-data-elasticsearch
core-java-concurrency
+ core-java-concurrency-collections
@@ -1238,7 +1260,7 @@
4.12
1.3
- 2.8.9
+ 2.21.0
1.7.21
1.1.7
@@ -1275,4 +1297,4 @@
3.8
-
+
\ No newline at end of file
diff --git a/rxjava-2/README.md b/rxjava-2/README.md
new file mode 100644
index 0000000000..ccf575757f
--- /dev/null
+++ b/rxjava-2/README.md
@@ -0,0 +1,6 @@
+## Relevant articles:
+
+- [RxJava and Error Handling](http://www.baeldung.com/rxjava-error-handling)
+- [RxJava 2 – Flowable](http://www.baeldung.com/rxjava-2-flowable)
+- [RxJava Maybe](http://www.baeldung.com/rxjava-maybe)
+- [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay)
\ No newline at end of file
diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml
new file mode 100644
index 0000000000..4c5ea014d7
--- /dev/null
+++ b/rxjava-2/pom.xml
@@ -0,0 +1,46 @@
+
+
+ 4.0.0
+
+ rxjava-2
+ 1.0-SNAPSHOT
+
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-java
+
+
+
+
+ io.reactivex.rxjava2
+ rxjava
+ ${rx.java2.version}
+
+
+ com.jayway.awaitility
+ awaitility
+ ${awaitility.version}
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+
+
+ com.jakewharton.rxrelay2
+ rxrelay
+ ${rxrelay.version}
+
+
+
+
+ 3.8.0
+ 2.1.3
+ 1.7.0
+ 2.0.0
+
+
+
\ No newline at end of file
diff --git a/rxjava/src/main/java/com/baeldung/rxjava/RandomRelay.java b/rxjava-2/src/main/java/com/baeldung/rxjava/RandomRelay.java
similarity index 100%
rename from rxjava/src/main/java/com/baeldung/rxjava/RandomRelay.java
rename to rxjava-2/src/main/java/com/baeldung/rxjava/RandomRelay.java
diff --git a/rxjava-2/src/main/resources/logback.xml b/rxjava-2/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/rxjava-2/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/rxjava/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java
similarity index 100%
rename from rxjava/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java
rename to rxjava-2/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java
diff --git a/rxjava/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java
similarity index 100%
rename from rxjava/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java
rename to rxjava-2/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java
diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java
similarity index 100%
rename from rxjava/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java
rename to rxjava-2/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java
diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java
similarity index 100%
rename from rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java
rename to rxjava-2/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java
diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java
similarity index 100%
rename from rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java
rename to rxjava-2/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java
diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java
new file mode 100644
index 0000000000..ade48a2cb9
--- /dev/null
+++ b/rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java
@@ -0,0 +1,65 @@
+package com.baeldung.rxjava.operators;
+
+import io.reactivex.Observable;
+import io.reactivex.schedulers.TestScheduler;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import static org.hamcrest.CoreMatchers.hasItems;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+public class RxFlatmapAndSwitchmapUnitTest {
+ @Test
+ public void givenObservable_whenFlatmap_shouldAssertAllItemsReturned() {
+ //given
+ List actualOutput = new ArrayList<>();
+ final TestScheduler scheduler = new TestScheduler();
+ final List keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books");
+
+ //when
+ Observable.fromIterable(keywordToSearch)
+ .flatMap(s -> Observable
+ .just(s + " FirstResult", s + " SecondResult")
+ .delay(10, TimeUnit.SECONDS, scheduler))
+ .toList()
+ .doOnSuccess(s -> actualOutput.addAll(s))
+ .subscribe();
+
+ scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
+
+ //then
+ assertThat(actualOutput, hasItems("b FirstResult", "b SecondResult",
+ "boo FirstResult", "boo SecondResult",
+ "bo FirstResult", "bo SecondResult",
+ "book FirstResult", "book SecondResult",
+ "books FirstResult", "books SecondResult"));
+ }
+
+ @Test
+ public void givenObservable_whenSwitchmap_shouldAssertLatestItemReturned() {
+ //given
+ List actualOutput = new ArrayList<>();
+ final TestScheduler scheduler = new TestScheduler();
+ final List keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books");
+
+ //when
+ Observable.fromIterable(keywordToSearch)
+ .switchMap(s -> Observable
+ .just(s + " FirstResult", s + " SecondResult")
+ .delay(10, TimeUnit.SECONDS, scheduler))
+ .toList()
+ .doOnSuccess(s -> actualOutput.addAll(s))
+ .subscribe();
+
+ scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
+
+ //then
+ assertEquals(2, actualOutput.size());
+ assertThat(actualOutput, hasItems("books FirstResult", "books SecondResult"));
+ }
+}
diff --git a/rxjava/README.md b/rxjava/README.md
index 5c60e3bbce..76135797a6 100644
--- a/rxjava/README.md
+++ b/rxjava/README.md
@@ -4,15 +4,11 @@
- [How to Test RxJava?](http://www.baeldung.com/rxjava-testing)
- [Implementing Custom Operators in RxJava](http://www.baeldung.com/rxjava-custom-operators)
- [Introduction to RxJava](http://www.baeldung.com/rx-java)
-- [RxJava and Error Handling](http://www.baeldung.com/rxjava-error-handling)
- [Observable Utility Operators in RxJava](http://www.baeldung.com/rxjava-observable-operators)
- [Introduction to rxjava-jdbc](http://www.baeldung.com/rxjava-jdbc)
- [Schedulers in RxJava](http://www.baeldung.com/rxjava-schedulers)
- [Mathematical and Aggregate Operators in RxJava](http://www.baeldung.com/rxjava-math)
- [Combining Observables in RxJava](http://www.baeldung.com/rxjava-combine-observables)
-- [RxJava 2 – Flowable](http://www.baeldung.com/rxjava-2-flowable)
- [RxJava StringObservable](http://www.baeldung.com/rxjava-string)
-- [RxJava Maybe](http://www.baeldung.com/rxjava-maybe)
-- [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay)
- [Filtering Observables in RxJava](http://www.baeldung.com/rxjava-filtering)
- [RxJava One Observable, Multiple Subscribers](http://www.baeldung.com/rxjava-multiple-subscribers-observable)
diff --git a/rxjava/pom.xml b/rxjava/pom.xml
index 49732c1ef4..b316001d87 100644
--- a/rxjava/pom.xml
+++ b/rxjava/pom.xml
@@ -20,12 +20,6 @@
${rx.java.version}
-
- io.reactivex.rxjava2
- rxjava
- ${rx.java2.version}
-
-
io.reactivex
rxjava-math
@@ -59,22 +53,15 @@
assertj-core
${assertj.version}
-
- com.jakewharton.rxrelay2
- rxrelay
- ${rxrelay.version}
-
3.8.0
1.2.5
- 2.1.3
0.7.11
1.0.0
1.1.1
1.7.0
- 2.0.0
1.4.196
diff --git a/spring-4/pom.xml b/spring-4/pom.xml
index d2632b5f55..cf10f64aa2 100644
--- a/spring-4/pom.xml
+++ b/spring-4/pom.xml
@@ -3,7 +3,6 @@
4.0.0
spring-4
spring-4
- 0.0.1-SNAPSHOT
jar
spring-4
@@ -19,6 +18,25 @@
org.springframework.boot
spring-boot-starter-web
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+ org.apache.tomcat
+ tomcat-jdbc
+
+
+
+
+ com.h2database
+ h2
+ test
+
+
+ com.zaxxer
+ HikariCP
+
org.springframework.boot
spring-boot-starter-test
@@ -32,7 +50,6 @@
org.projectlombok
lombok
- ${lombok.version}
provided
@@ -58,6 +75,7 @@
1.0.1
1.16.18
1.8
+ 1.4.197
diff --git a/spring-4/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java b/spring-4/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java
new file mode 100644
index 0000000000..0bd8637681
--- /dev/null
+++ b/spring-4/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java
@@ -0,0 +1,12 @@
+package com.baeldung.connectionpool;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class ApplicationWithHikariConnectionPool {
+
+ public static void main(String[] args) {
+ SpringApplication.run(ApplicationWithHikariConnectionPool.class, args);
+ }
+}
diff --git a/spring-4/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java b/spring-4/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java
new file mode 100644
index 0000000000..0cc876d5b1
--- /dev/null
+++ b/spring-4/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java
@@ -0,0 +1,28 @@
+package com.baeldung.connectionpool;
+
+import static org.junit.Assert.*;
+
+import javax.sql.DataSource;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(
+ // instead of setting this property, we can exclude the dependency to org.apache.tomcat:tomcat-jdbc in pom.xml
+ properties = "spring.datasource.type=com.zaxxer.hikari.HikariDataSource")
+public class HikariIntegrationTest {
+
+ @Autowired
+ private DataSource dataSource;
+
+ @Test
+ public void hikariConnectionPoolIsConfigured() {
+ assertEquals("com.zaxxer.hikari.HikariDataSource", dataSource.getClass()
+ .getName());
+ }
+
+}
diff --git a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java
index 41b5c1eed1..8251467122 100644
--- a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java
+++ b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java
@@ -1,7 +1,11 @@
package com.baeldung;
+import javax.servlet.Filter;
+
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.web.filter.DelegatingFilterProxy;
+import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
@SpringBootApplication
public class Spring5Application {
@@ -10,4 +14,31 @@ public class Spring5Application {
SpringApplication.run(Spring5Application.class, args);
}
+ public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
+
+ @Override
+ protected Class>[] getRootConfigClasses() {
+ return null;
+ }
+
+ @Override
+ protected Class>[] getServletConfigClasses() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ protected String[] getServletMappings() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ protected javax.servlet.Filter[] getServletFilters() {
+ DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy();
+ delegateFilterProxy.setTargetBeanName("loggingFilter");
+ return new Filter[] { delegateFilterProxy };
+ }
+ }
+
}
diff --git a/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java b/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java
new file mode 100644
index 0000000000..4aa33cd749
--- /dev/null
+++ b/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java
@@ -0,0 +1,38 @@
+package com.baeldung.spring.filter;
+
+import java.io.IOException;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+@Component("loggingFilter")
+public class CustomFilter implements Filter {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(CustomFilter.class);
+
+ @Override
+ public void init(FilterConfig config) throws ServletException {
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+ HttpServletRequest req = (HttpServletRequest) request;
+ LOGGER.info("Request Info : " + req);
+ chain.doFilter(request, response);
+ }
+
+ @Override
+ public void destroy() {
+ // cleanup code, if necessary
+ }
+}
diff --git a/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java b/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java
index ff1fb87393..c5f63486fe 100644
--- a/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java
+++ b/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java
@@ -13,7 +13,7 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter
@Controller
public class ResponseBodyEmitterController {
- private ExecutorService nonBlockingService = Executors.newSingleThreadExecutor();
+ private ExecutorService nonBlockingService = Executors.newCachedThreadPool();
@GetMapping(Constants.API_RBE)
public ResponseEntity handleRbe() {
diff --git a/spring-5-mvc/src/main/webapp/WEB-INF/web.xml b/spring-5-mvc/src/main/webapp/WEB-INF/web.xml
index bfcf43dad2..43c7143e5b 100644
--- a/spring-5-mvc/src/main/webapp/WEB-INF/web.xml
+++ b/spring-5-mvc/src/main/webapp/WEB-INF/web.xml
@@ -16,6 +16,14 @@
functional
/
+
+ loggingFilter
+ org.springframework.web.filter.DelegatingFilterProxy
+
+
+ loggingFilter
+ /*
+
\ No newline at end of file
diff --git a/spring-5-reactive-client/src/main/resources/logback.xml b/spring-5-reactive-client/src/main/resources/logback.xml
index 8bbe8c1d67..7072369b8d 100644
--- a/spring-5-reactive-client/src/main/resources/logback.xml
+++ b/spring-5-reactive-client/src/main/resources/logback.xml
@@ -3,7 +3,7 @@
# Pattern of log message for console appender
- %d{yyyy-MM-dd HH:mm:ss} %-5p %m%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/spring-5-reactive-client/src/test/resources/logback-test.xml b/spring-5-reactive-client/src/test/resources/logback-test.xml
index 8bbe8c1d67..7072369b8d 100644
--- a/spring-5-reactive-client/src/test/resources/logback-test.xml
+++ b/spring-5-reactive-client/src/test/resources/logback-test.xml
@@ -3,7 +3,7 @@
# Pattern of log message for console appender
- %d{yyyy-MM-dd HH:mm:ss} %-5p %m%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/spring-5-reactive-security/.gitignore b/spring-5-reactive-security/.gitignore
new file mode 100644
index 0000000000..dec013dfa4
--- /dev/null
+++ b/spring-5-reactive-security/.gitignore
@@ -0,0 +1,12 @@
+#folders#
+.idea
+/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/spring-5-reactive-security/README.md b/spring-5-reactive-security/README.md
new file mode 100644
index 0000000000..3395cf5562
--- /dev/null
+++ b/spring-5-reactive-security/README.md
@@ -0,0 +1,11 @@
+## Spring 5 Reactive Security Examples
+
+### The Course
+The "REST With Spring" Classes: http://bit.ly/restwithspring
+
+### Relevant Articles
+
+- [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators)
+- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive)
+- [Guide to Spring 5 WebFlux](http://www.baeldung.com/spring-webflux)
+
diff --git a/spring-5-reactive-security/pom.xml b/spring-5-reactive-security/pom.xml
new file mode 100644
index 0000000000..3b64b9b3ac
--- /dev/null
+++ b/spring-5-reactive-security/pom.xml
@@ -0,0 +1,135 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ spring-5-reactive-security
+ 0.0.1-SNAPSHOT
+ jar
+ spring-5-reactive-security
+ spring 5 security sample project about new features
+
+
+ com.baeldung
+ parent-boot-2
+ 0.0.1-SNAPSHOT
+ ../parent-boot-2
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-validation
+
+
+ org.springframework.boot
+ spring-boot-starter-tomcat
+
+
+ org.springframework.boot
+ spring-boot-starter-webflux
+
+
+ org.projectreactor
+ reactor-spring
+ ${reactor-spring.version}
+
+
+ javax.json.bind
+ javax.json.bind-api
+
+
+ org.springframework.boot
+ spring-boot-starter-actuator
+
+
+ org.projectlombok
+ lombok
+ compile
+
+
+ org.apache.geronimo.specs
+ geronimo-json_1.1_spec
+ ${geronimo-json_1.1_spec.version}
+
+
+ org.apache.johnzon
+ johnzon-jsonb
+
+
+
+ org.apache.commons
+ commons-lang3
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-devtools
+ runtime
+
+
+ org.springframework
+ spring-test
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+ org.apache.commons
+ commons-collections4
+ ${commons-collections4.version}
+ test
+
+
+
+ io.reactivex.rxjava2
+ rxjava
+ ${rxjava-version}
+
+
+ io.projectreactor
+ reactor-test
+ ${project-reactor-test}
+ test
+
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+ org.springframework.security
+ spring-security-test
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+ com.baeldung.webflux.EmployeeSpringApplication
+ JAR
+
+
+
+
+
+
+ 1.0.1.RELEASE
+ 2.1.12
+ 1.1.3
+ 1.0
+ 1.0
+ 4.1
+ 3.1.6.RELEASE
+
+
+
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java
similarity index 100%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java
similarity index 100%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java
similarity index 100%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java
diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java
new file mode 100644
index 0000000000..f07ddfb0f7
--- /dev/null
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java
@@ -0,0 +1,15 @@
+package com.baeldung.reactive.actuator;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.Bean;
+
+@SpringBootApplication
+public class Spring5ReactiveApplication{
+
+ public static void main(String[] args) {
+ SpringApplication.run(Spring5ReactiveApplication.class, args);
+ }
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java
similarity index 91%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java
index 427fd70a6c..07f805fea4 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java
@@ -22,7 +22,7 @@ public class WebSecurityConfig {
.authorizeExchange()
.matchers(EndpointRequest.to(
FeaturesEndpoint.class
- )).permitAll().and().csrf().disable().build();
+ )).permitAll().anyExchange().permitAll().and().csrf().disable().build();
}
}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetController.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetController.java
similarity index 100%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetController.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetController.java
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetService.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetService.java
similarity index 100%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetService.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetService.java
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SecurityConfig.java
similarity index 76%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SecurityConfig.java
index 5ec3b6e241..225f78b3f7 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SecurityConfig.java
@@ -8,6 +8,8 @@ import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.server.SecurityWebFilterChain;
import com.baeldung.reactive.actuator.FeaturesEndpoint;
@@ -35,19 +37,24 @@ public class SecurityConfig {
@Bean
public MapReactiveUserDetailsService userDetailsService() {
- UserDetails user = User.withDefaultPasswordEncoder()
- .username("user")
- .password("password")
+ UserDetails user = User
+ .withUsername("user")
+ .password(passwordEncoder().encode("password"))
.roles("USER")
.build();
- UserDetails admin = User.withDefaultPasswordEncoder()
- .username("admin")
- .password("password")
+ UserDetails admin = User
+ .withUsername("admin")
+ .password(passwordEncoder().encode("password"))
.roles("ADMIN")
.build();
return new MapReactiveUserDetailsService(user, admin);
}
+
+ @Bean
+ public PasswordEncoder passwordEncoder() {
+ return new BCryptPasswordEncoder();
+ }
}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/SpringSecurity5Application.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java
similarity index 97%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/SpringSecurity5Application.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java
index ca49ec6826..f2963c4fa5 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/SpringSecurity5Application.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java
@@ -1,4 +1,4 @@
-package com.baeldung.reactive;
+package com.baeldung.reactive.security;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/Employee.java
similarity index 81%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/Employee.java
index 6a03555654..bbdf85d293 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/Employee.java
@@ -1,17 +1,17 @@
-package com.baeldung.reactive.webflux;
-
-import lombok.AllArgsConstructor;
-import lombok.Data;
-import lombok.NoArgsConstructor;
-
-@Data
-@AllArgsConstructor
-@NoArgsConstructor
-public class Employee {
-
- private String id;
- private String name;
-
- // standard getters and setters
-
-}
+package com.baeldung.webflux;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+public class Employee {
+
+ private String id;
+ private String name;
+
+ // standard getters and setters
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeConfig.java
similarity index 93%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeConfig.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeConfig.java
index 082be68698..6e73004650 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeConfig.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeConfig.java
@@ -1,33 +1,33 @@
-package com.baeldung.reactive.webflux;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.web.reactive.HandlerMapping;
-import org.springframework.web.reactive.config.EnableWebFlux;
-import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
-import org.springframework.web.reactive.socket.WebSocketHandler;
-import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
-
-@Configuration
-@EnableWebFlux
-public class EmployeeConfig {
-
- @Bean
- public HandlerMapping handlerMapping() {
- Map map = new HashMap<>();
- map.put("/employee-feed", new EmployeeWebSocketHandler());
-
- SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
- mapping.setUrlMap(map);
- mapping.setOrder(10);
- return mapping;
- }
-
- @Bean
- public WebSocketHandlerAdapter handlerAdapter() {
- return new WebSocketHandlerAdapter();
- }
-}
+package com.baeldung.webflux;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.reactive.HandlerMapping;
+import org.springframework.web.reactive.config.EnableWebFlux;
+import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
+import org.springframework.web.reactive.socket.WebSocketHandler;
+import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
+
+@Configuration
+@EnableWebFlux
+public class EmployeeConfig {
+
+ @Bean
+ public HandlerMapping handlerMapping() {
+ Map map = new HashMap<>();
+ map.put("/employee-feed", new EmployeeWebSocketHandler());
+
+ SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
+ mapping.setUrlMap(map);
+ mapping.setOrder(10);
+ return mapping;
+ }
+
+ @Bean
+ public WebSocketHandlerAdapter handlerAdapter() {
+ return new WebSocketHandlerAdapter();
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeController.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeController.java
similarity index 93%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeController.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeController.java
index 98b16dafab..34e44afc8b 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeController.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeController.java
@@ -1,38 +1,38 @@
-package com.baeldung.reactive.webflux;
-
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import reactor.core.publisher.Flux;
-import reactor.core.publisher.Mono;
-
-@RestController
-@RequestMapping("/employees")
-public class EmployeeController {
-
- private EmployeeRepository employeeRepository;
-
- public EmployeeController(EmployeeRepository employeeRepository) {
- this.employeeRepository = employeeRepository;
- }
-
- @GetMapping("/{id}")
- private Mono getEmployeeById(@PathVariable String id) {
- return employeeRepository.findEmployeeById(id);
- }
-
- @GetMapping
- private Flux getAllEmployees() {
- return employeeRepository.findAllEmployees();
- }
-
- @PostMapping("/update")
- private Mono updateEmployee(@RequestBody Employee employee) {
- return employeeRepository.updateEmployee(employee);
- }
-
-}
+package com.baeldung.webflux;
+
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+@RestController
+@RequestMapping("/employees")
+public class EmployeeController {
+
+ private EmployeeRepository employeeRepository;
+
+ public EmployeeController(EmployeeRepository employeeRepository) {
+ this.employeeRepository = employeeRepository;
+ }
+
+ @GetMapping("/{id}")
+ private Mono getEmployeeById(@PathVariable String id) {
+ return employeeRepository.findEmployeeById(id);
+ }
+
+ @GetMapping
+ private Flux getAllEmployees() {
+ return employeeRepository.findAllEmployees();
+ }
+
+ @PostMapping("/update")
+ private Mono updateEmployee(@RequestBody Employee employee) {
+ return employeeRepository.updateEmployee(employee);
+ }
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeCreationEvent.java
similarity index 89%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeCreationEvent.java
index 7a66e1e147..d4f9a4fb02 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeCreationEvent.java
@@ -1,4 +1,4 @@
-package com.baeldung.reactive.webflux;
+package com.baeldung.webflux;
import lombok.AllArgsConstructor;
import lombok.Data;
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeRepository.java
similarity index 95%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeRepository.java
index a407c76fa8..d7f618f178 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeRepository.java
@@ -1,64 +1,64 @@
-package com.baeldung.reactive.webflux;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.springframework.stereotype.Repository;
-
-import reactor.core.publisher.Flux;
-import reactor.core.publisher.Mono;
-
-@Repository
-public class EmployeeRepository {
-
- static Map employeeData;
-
- static Map employeeAccessData;
-
- static
- {
- employeeData = new HashMap<>();
- employeeData.put("1",new Employee("1","Employee 1"));
- employeeData.put("2",new Employee("2","Employee 2"));
- employeeData.put("3",new Employee("3","Employee 3"));
- employeeData.put("4",new Employee("4","Employee 4"));
- employeeData.put("5",new Employee("5","Employee 5"));
- employeeData.put("6",new Employee("6","Employee 6"));
- employeeData.put("7",new Employee("7","Employee 7"));
- employeeData.put("8",new Employee("8","Employee 8"));
- employeeData.put("9",new Employee("9","Employee 9"));
- employeeData.put("10",new Employee("10","Employee 10"));
-
- employeeAccessData=new HashMap<>();
- employeeAccessData.put("1", "Employee 1 Access Key");
- employeeAccessData.put("2", "Employee 2 Access Key");
- employeeAccessData.put("3", "Employee 3 Access Key");
- employeeAccessData.put("4", "Employee 4 Access Key");
- employeeAccessData.put("5", "Employee 5 Access Key");
- employeeAccessData.put("6", "Employee 6 Access Key");
- employeeAccessData.put("7", "Employee 7 Access Key");
- employeeAccessData.put("8", "Employee 8 Access Key");
- employeeAccessData.put("9", "Employee 9 Access Key");
- employeeAccessData.put("10", "Employee 10 Access Key");
- }
-
- public Mono findEmployeeById(String id)
- {
- return Mono.just(employeeData.get(id));
- }
-
- public Flux findAllEmployees()
- {
- return Flux.fromIterable(employeeData.values());
- }
-
- public Mono updateEmployee(Employee employee)
- {
- Employee existingEmployee=employeeData.get(employee.getId());
- if(existingEmployee!=null)
- {
- existingEmployee.setName(employee.getName());
- }
- return Mono.just(existingEmployee);
- }
-}
+package com.baeldung.webflux;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.springframework.stereotype.Repository;
+
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+@Repository
+public class EmployeeRepository {
+
+ static Map employeeData;
+
+ static Map employeeAccessData;
+
+ static
+ {
+ employeeData = new HashMap<>();
+ employeeData.put("1",new Employee("1","Employee 1"));
+ employeeData.put("2",new Employee("2","Employee 2"));
+ employeeData.put("3",new Employee("3","Employee 3"));
+ employeeData.put("4",new Employee("4","Employee 4"));
+ employeeData.put("5",new Employee("5","Employee 5"));
+ employeeData.put("6",new Employee("6","Employee 6"));
+ employeeData.put("7",new Employee("7","Employee 7"));
+ employeeData.put("8",new Employee("8","Employee 8"));
+ employeeData.put("9",new Employee("9","Employee 9"));
+ employeeData.put("10",new Employee("10","Employee 10"));
+
+ employeeAccessData=new HashMap<>();
+ employeeAccessData.put("1", "Employee 1 Access Key");
+ employeeAccessData.put("2", "Employee 2 Access Key");
+ employeeAccessData.put("3", "Employee 3 Access Key");
+ employeeAccessData.put("4", "Employee 4 Access Key");
+ employeeAccessData.put("5", "Employee 5 Access Key");
+ employeeAccessData.put("6", "Employee 6 Access Key");
+ employeeAccessData.put("7", "Employee 7 Access Key");
+ employeeAccessData.put("8", "Employee 8 Access Key");
+ employeeAccessData.put("9", "Employee 9 Access Key");
+ employeeAccessData.put("10", "Employee 10 Access Key");
+ }
+
+ public Mono findEmployeeById(String id)
+ {
+ return Mono.just(employeeData.get(id));
+ }
+
+ public Flux findAllEmployees()
+ {
+ return Flux.fromIterable(employeeData.values());
+ }
+
+ public Mono updateEmployee(Employee employee)
+ {
+ Employee existingEmployee=employeeData.get(employee.getId());
+ if(existingEmployee!=null)
+ {
+ existingEmployee.setName(employee.getName());
+ }
+ return Mono.just(existingEmployee);
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeSpringApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeSpringApplication.java
similarity index 88%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeSpringApplication.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeSpringApplication.java
index 54b23a18de..2652c36695 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeSpringApplication.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeSpringApplication.java
@@ -1,17 +1,17 @@
-package com.baeldung.reactive.webflux;
-
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-
-@SpringBootApplication
-public class EmployeeSpringApplication {
-
- public static void main(String[] args) {
-
- SpringApplication.run(EmployeeSpringApplication.class, args);
-
- EmployeeWebClient employeeWebClient = new EmployeeWebClient();
- employeeWebClient.consume();
- }
-
-}
+package com.baeldung.webflux;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class EmployeeSpringApplication {
+
+ public static void main(String[] args) {
+
+ SpringApplication.run(EmployeeSpringApplication.class, args);
+
+ EmployeeWebClient employeeWebClient = new EmployeeWebClient();
+ employeeWebClient.consume();
+ }
+
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebClient.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebClient.java
similarity index 91%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebClient.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebClient.java
index 45d42ecda9..eb32408a7f 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebClient.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebClient.java
@@ -1,28 +1,28 @@
-package com.baeldung.reactive.webflux;
-
-import org.springframework.web.reactive.function.client.WebClient;
-
-import reactor.core.publisher.Flux;
-import reactor.core.publisher.Mono;
-
-public class EmployeeWebClient {
-
- WebClient client = WebClient.create("http://localhost:8080");
-
- public void consume() {
-
- Mono employeeMono = client.get()
- .uri("/employees/{id}", "1")
- .retrieve()
- .bodyToMono(Employee.class);
-
- employeeMono.subscribe(System.out::println);
-
- Flux employeeFlux = client.get()
- .uri("/employees")
- .retrieve()
- .bodyToFlux(Employee.class);
-
- employeeFlux.subscribe(System.out::println);
- }
+package com.baeldung.webflux;
+
+import org.springframework.web.reactive.function.client.WebClient;
+
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+public class EmployeeWebClient {
+
+ WebClient client = WebClient.create("http://localhost:8080");
+
+ public void consume() {
+
+ Mono employeeMono = client.get()
+ .uri("/employees/{id}", "1")
+ .retrieve()
+ .bodyToMono(Employee.class);
+
+ employeeMono.subscribe(System.out::println);
+
+ Flux employeeFlux = client.get()
+ .uri("/employees")
+ .retrieve()
+ .bodyToFlux(Employee.class);
+
+ employeeFlux.subscribe(System.out::println);
+ }
}
\ No newline at end of file
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSecurityConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSecurityConfig.java
similarity index 71%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSecurityConfig.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSecurityConfig.java
index 7922e6ba44..75475a0f08 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSecurityConfig.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSecurityConfig.java
@@ -1,38 +1,46 @@
-package com.baeldung.reactive.webflux;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.http.HttpMethod;
-import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
-import org.springframework.security.config.web.server.ServerHttpSecurity;
-import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
-import org.springframework.security.core.userdetails.User;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.web.server.SecurityWebFilterChain;
-
-@EnableWebFluxSecurity
-public class EmployeeWebSecurityConfig {
-
- @Bean
- public MapReactiveUserDetailsService userDetailsService() {
- UserDetails user = User.withDefaultPasswordEncoder()
- .username("admin")
- .password("password")
- .roles("ADMIN")
- .build();
- return new MapReactiveUserDetailsService(user);
- }
-
- @Bean
- public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
- http.csrf()
- .disable()
- .authorizeExchange()
- .pathMatchers(HttpMethod.POST, "/employees/update")
- .hasRole("ADMIN")
- .pathMatchers("/**")
- .permitAll()
- .and()
- .httpBasic();
- return http.build();
- }
-}
+package com.baeldung.webflux;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.http.HttpMethod;
+import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
+import org.springframework.security.config.web.server.ServerHttpSecurity;
+import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.web.server.SecurityWebFilterChain;
+
+@EnableWebFluxSecurity
+public class EmployeeWebSecurityConfig {
+
+ @Bean
+ public MapReactiveUserDetailsService userDetailsService() {
+ UserDetails user = User
+ .withUsername("admin")
+ .password(passwordEncoder().encode("password"))
+ .roles("ADMIN")
+ .build();
+ return new MapReactiveUserDetailsService(user);
+ }
+
+ @Bean
+ public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
+ http.csrf()
+ .disable()
+ .authorizeExchange()
+ .pathMatchers(HttpMethod.POST, "/employees/update")
+ .hasRole("ADMIN")
+ .pathMatchers("/**")
+ .permitAll()
+ .and()
+ .httpBasic();
+ return http.build();
+ }
+
+ @Bean
+ public PasswordEncoder passwordEncoder() {
+ return new BCryptPasswordEncoder();
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketClient.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketClient.java
similarity index 94%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketClient.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketClient.java
index 4571cadc47..feb1eb62fb 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketClient.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketClient.java
@@ -1,4 +1,4 @@
-package com.baeldung.reactive.webflux;
+package com.baeldung.webflux;
import java.net.URI;
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketHandler.java
similarity index 94%
rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java
rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketHandler.java
index c696bc8215..40b7b760ee 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java
+++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketHandler.java
@@ -1,39 +1,39 @@
-package com.baeldung.reactive.webflux;
-
-import static java.time.LocalDateTime.now;
-import static java.util.UUID.randomUUID;
-
-import java.time.Duration;
-
-import org.springframework.stereotype.Component;
-import org.springframework.web.reactive.socket.WebSocketHandler;
-import org.springframework.web.reactive.socket.WebSocketSession;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import reactor.core.publisher.Flux;
-import reactor.core.publisher.Mono;
-
-@Component("EmployeeWebSocketHandler")
-public class EmployeeWebSocketHandler implements WebSocketHandler {
-
- ObjectMapper om = new ObjectMapper();
-
- @Override
- public Mono handle(WebSocketSession webSocketSession) {
-
- Flux employeeCreationEvent = Flux.generate(sink -> {
- EmployeeCreationEvent event = new EmployeeCreationEvent(randomUUID().toString(), now().toString());
- try {
- sink.next(om.writeValueAsString(event));
- } catch (JsonProcessingException e) {
- sink.error(e);
- }
- });
-
- return webSocketSession.send(employeeCreationEvent
- .map(webSocketSession::textMessage)
- .delayElements(Duration.ofSeconds(1)));
- }
-}
+package com.baeldung.webflux;
+
+import static java.time.LocalDateTime.now;
+import static java.util.UUID.randomUUID;
+
+import java.time.Duration;
+
+import org.springframework.stereotype.Component;
+import org.springframework.web.reactive.socket.WebSocketHandler;
+import org.springframework.web.reactive.socket.WebSocketSession;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+@Component("EmployeeWebSocketHandler")
+public class EmployeeWebSocketHandler implements WebSocketHandler {
+
+ ObjectMapper om = new ObjectMapper();
+
+ @Override
+ public Mono handle(WebSocketSession webSocketSession) {
+
+ Flux employeeCreationEvent = Flux.generate(sink -> {
+ EmployeeCreationEvent event = new EmployeeCreationEvent(randomUUID().toString(), now().toString());
+ try {
+ sink.next(om.writeValueAsString(event));
+ } catch (JsonProcessingException e) {
+ sink.error(e);
+ }
+ });
+
+ return webSocketSession.send(employeeCreationEvent
+ .map(webSocketSession::textMessage)
+ .delayElements(Duration.ofSeconds(1)));
+ }
+}
diff --git a/spring-5-reactive-security/src/main/resources/application.properties b/spring-5-reactive-security/src/main/resources/application.properties
new file mode 100644
index 0000000000..234834b894
--- /dev/null
+++ b/spring-5-reactive-security/src/main/resources/application.properties
@@ -0,0 +1,5 @@
+logging.level.root=INFO
+
+management.endpoints.web.exposure.include.=*
+
+info.app.name=Spring Boot 2 actuator Application
diff --git a/spring-5-reactive-security/src/main/resources/files/hello.txt b/spring-5-reactive-security/src/main/resources/files/hello.txt
new file mode 100644
index 0000000000..b6fc4c620b
--- /dev/null
+++ b/spring-5-reactive-security/src/main/resources/files/hello.txt
@@ -0,0 +1 @@
+hello
\ No newline at end of file
diff --git a/spring-5-reactive-security/src/main/resources/files/test/test.txt b/spring-5-reactive-security/src/main/resources/files/test/test.txt
new file mode 100644
index 0000000000..30d74d2584
--- /dev/null
+++ b/spring-5-reactive-security/src/main/resources/files/test/test.txt
@@ -0,0 +1 @@
+test
\ No newline at end of file
diff --git a/spring-5-reactive-security/src/main/resources/logback.xml b/spring-5-reactive-security/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/spring-5-reactive-security/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-5-reactive-security/src/main/resources/static/client-websocket.html b/spring-5-reactive-security/src/main/resources/static/client-websocket.html
new file mode 100644
index 0000000000..3f840e8bd4
--- /dev/null
+++ b/spring-5-reactive-security/src/main/resources/static/client-websocket.html
@@ -0,0 +1,34 @@
+
+
+
+
+Baeldung: Spring 5 Reactive Client WebSocket (Browser)
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-5-reactive-security/src/main/webapp/WEB-INF/web.xml b/spring-5-reactive-security/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000..bfcf43dad2
--- /dev/null
+++ b/spring-5-reactive-security/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,21 @@
+
+
+
+ Spring Functional Application
+
+
+ functional
+ com.baeldung.functional.RootServlet
+ 1
+ true
+
+
+ functional
+ /
+
+
+
+
\ No newline at end of file
diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java
similarity index 95%
rename from spring-5-reactive/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java
rename to spring-5-reactive-security/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java
index 3020e86723..94979a18ca 100644
--- a/spring-5-reactive/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java
+++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java
@@ -9,8 +9,6 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
-import com.baeldung.reactive.Spring5ReactiveApplication;
-
import java.io.IOException;
import static org.junit.Assert.assertEquals;
diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java
similarity index 93%
rename from spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java
rename to spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java
index e8c8c25723..3dc832d781 100644
--- a/spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java
+++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java
@@ -1,74 +1,76 @@
-package com.baeldung.reactive.webflux;
-
-import static org.mockito.BDDMockito.given;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.MethodSorters;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.test.mock.mockito.MockBean;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.test.web.reactive.server.WebTestClient;
-
-import com.baeldung.reactive.Spring5ReactiveApplication;
-
-import reactor.core.publisher.Flux;
-import reactor.core.publisher.Mono;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes=Spring5ReactiveApplication.class)
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class EmployeeControllerIntegrationTest {
-
- @Autowired
- private WebTestClient testClient;
-
- @MockBean
- private EmployeeRepository employeeRepository;
-
- @Test
- public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() {
-
- Employee employee = new Employee("1", "Employee 1 Name");
-
- given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee));
- testClient.get()
- .uri("/employees/1")
- .exchange()
- .expectStatus()
- .isOk()
- .expectBody(Employee.class)
- .isEqualTo(employee);
- }
-
- @Test
- public void whenGetAllEmployees_thenCorrectEmployees() {
-
- List employeeList = new ArrayList<>();
-
- Employee employee1 = new Employee("1", "Employee 1 Name");
- Employee employee2 = new Employee("2", "Employee 2 Name");
- Employee employee3 = new Employee("3", "Employee 3 Name");
-
- employeeList.add(employee1);
- employeeList.add(employee2);
- employeeList.add(employee3);
-
- Flux employeeFlux = Flux.fromIterable(employeeList);
-
- given(employeeRepository.findAllEmployees()).willReturn(employeeFlux);
- testClient.get()
- .uri("/employees")
- .exchange()
- .expectStatus()
- .isOk()
- .expectBodyList(Employee.class)
- .hasSize(3)
- .isEqualTo(employeeList);
- }
-}
+package com.baeldung.reactive.webflux;
+
+import static org.mockito.BDDMockito.given;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.reactive.server.WebTestClient;
+
+import com.baeldung.reactive.actuator.Spring5ReactiveApplication;
+import com.baeldung.webflux.Employee;
+import com.baeldung.webflux.EmployeeRepository;
+
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes=Spring5ReactiveApplication.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class EmployeeControllerIntegrationTest {
+
+ @Autowired
+ private WebTestClient testClient;
+
+ @MockBean
+ private EmployeeRepository employeeRepository;
+
+ @Test
+ public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() {
+
+ Employee employee = new Employee("1", "Employee 1 Name");
+
+ given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee));
+ testClient.get()
+ .uri("/employees/1")
+ .exchange()
+ .expectStatus()
+ .isOk()
+ .expectBody(Employee.class)
+ .isEqualTo(employee);
+ }
+
+ @Test
+ public void whenGetAllEmployees_thenCorrectEmployees() {
+
+ List employeeList = new ArrayList<>();
+
+ Employee employee1 = new Employee("1", "Employee 1 Name");
+ Employee employee2 = new Employee("2", "Employee 2 Name");
+ Employee employee3 = new Employee("3", "Employee 3 Name");
+
+ employeeList.add(employee1);
+ employeeList.add(employee2);
+ employeeList.add(employee3);
+
+ Flux employeeFlux = Flux.fromIterable(employeeList);
+
+ given(employeeRepository.findAllEmployees()).willReturn(employeeFlux);
+ testClient.get()
+ .uri("/employees")
+ .exchange()
+ .expectStatus()
+ .isOk()
+ .expectBodyList(Employee.class)
+ .hasSize(3)
+ .isEqualTo(employeeList);
+ }
+}
diff --git a/spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/security/SecurityIntegrationTest.java
similarity index 94%
rename from spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java
rename to spring-5-reactive-security/src/test/java/com/baeldung/security/SecurityIntegrationTest.java
index a59ef57db8..423500e09c 100644
--- a/spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java
+++ b/spring-5-reactive-security/src/test/java/com/baeldung/security/SecurityIntegrationTest.java
@@ -1,6 +1,5 @@
package com.baeldung.security;
-import com.baeldung.reactive.SpringSecurity5Application;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -12,6 +11,8 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
+import com.baeldung.reactive.security.SpringSecurity5Application;
+
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = SpringSecurity5Application.class)
public class SecurityIntegrationTest {
diff --git a/spring-5-reactive-security/src/test/resources/baeldung-weekly.png b/spring-5-reactive-security/src/test/resources/baeldung-weekly.png
new file mode 100644
index 0000000000..a1b7eebcab
Binary files /dev/null and b/spring-5-reactive-security/src/test/resources/baeldung-weekly.png differ
diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md
index 0a7fe7a47e..0665eb4f57 100644
--- a/spring-5-reactive/README.md
+++ b/spring-5-reactive/README.md
@@ -1,4 +1,4 @@
-## Spring REST Example Project
+## Spring 5 Reactive Project
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
@@ -7,12 +7,9 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web)
- [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient)
-- [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators)
- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching)
-- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive)
- [Reactive WebSockets with Spring 5](http://www.baeldung.com/spring-5-reactive-websockets)
- [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters)
- [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header)
- [Spring Webflux and CORS](http://www.baeldung.com/spring-webflux-cors)
- [Handling Errors in Spring WebFlux](http://www.baeldung.com/spring-webflux-errors)
-- [Guide to Spring 5 WebFlux](http://www.baeldung.com/spring-webflux)
diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml
index f89fd45581..e81d3d8b79 100644
--- a/spring-5-reactive/pom.xml
+++ b/spring-5-reactive/pom.xml
@@ -39,10 +39,6 @@
javax.json.bind
javax.json.bind-api
-
- org.springframework.boot
- spring-boot-starter-actuator
-
org.projectlombok
lombok
@@ -86,10 +82,6 @@
${commons-collections4.version}
test
-
- org.apache.commons
- commons-lang3
-
io.reactivex.rxjava2
@@ -102,15 +94,6 @@
${project-reactor-test}
test
-
- org.springframework.boot
- spring-boot-starter-security
-
-
- org.springframework.security
- spring-security-test
- test
-
diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java
index 402b607b19..a1d5d87d5c 100644
--- a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java
+++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java
@@ -21,9 +21,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.server.reactive.HttpHandler;
-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.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
@@ -68,18 +65,6 @@ public class FunctionalSpringBootApplication {
return registrationBean;
}
- @Configuration
- @EnableWebSecurity
- @Profile("!https")
- static class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(final HttpSecurity http) throws Exception {
- http.authorizeRequests()
- .anyRequest()
- .permitAll();
- }
- }
-
public static void main(String[] args) {
SpringApplication.run(FunctionalSpringBootApplication.class, args);
}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/util/CpuUtils.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/util/CpuUtils.java
new file mode 100644
index 0000000000..8d16434920
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/util/CpuUtils.java
@@ -0,0 +1,15 @@
+package com.baeldung.reactive.util;
+
+import com.sun.management.OperatingSystemMXBean;
+
+import java.lang.management.ManagementFactory;
+
+public class CpuUtils {
+
+ private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
+
+ static Double getUsage() {
+ return (operatingSystemMXBean.getSystemCpuLoad() / operatingSystemMXBean.getAvailableProcessors()) * 100;
+ }
+
+}
diff --git a/spring-5-reactive/src/main/resources/application.properties b/spring-5-reactive/src/main/resources/application.properties
index 234834b894..92f3116f84 100644
--- a/spring-5-reactive/src/main/resources/application.properties
+++ b/spring-5-reactive/src/main/resources/application.properties
@@ -1,5 +1,2 @@
logging.level.root=INFO
-management.endpoints.web.exposure.include.=*
-
-info.app.name=Spring Boot 2 actuator Application
diff --git a/spring-5-security/README.md b/spring-5-security/README.md
index 94a8f83281..564dcd3c96 100644
--- a/spring-5-security/README.md
+++ b/spring-5-security/README.md
@@ -4,4 +4,4 @@
- [Extra Login Fields with Spring Security](http://www.baeldung.com/spring-security-extra-login-fields)
- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer)
- [New Password Storage In Spring Security 5](http://www.baeldung.com/spring-security-5-password-storage)
-
+- [Default Password Encoder in Spring Security 5](https://www.baeldung.com/spring-security-5-default-password-encoder)
diff --git a/spring-5/README.md b/spring-5/README.md
index 47bae09862..baf03fb3b3 100644
--- a/spring-5/README.md
+++ b/spring-5/README.md
@@ -12,4 +12,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs)
- [Spring ResponseStatusException](http://www.baeldung.com/spring-response-status-exception)
- [Spring Assert Statements](http://www.baeldung.com/spring-assert)
-- [Spring Security 5 – OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login)
diff --git a/spring-5/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java b/spring-5/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java
new file mode 100644
index 0000000000..0bd8637681
--- /dev/null
+++ b/spring-5/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java
@@ -0,0 +1,12 @@
+package com.baeldung.connectionpool;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class ApplicationWithHikariConnectionPool {
+
+ public static void main(String[] args) {
+ SpringApplication.run(ApplicationWithHikariConnectionPool.class, args);
+ }
+}
diff --git a/spring-5/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java b/spring-5/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java
new file mode 100644
index 0000000000..d91cca85ee
--- /dev/null
+++ b/spring-5/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java
@@ -0,0 +1,26 @@
+package com.baeldung.connectionpool;
+
+import static org.junit.Assert.*;
+
+import javax.sql.DataSource;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class HikariIntegrationTest {
+
+ @Autowired
+ private DataSource dataSource;
+
+ @Test
+ public void hikariConnectionPoolIsConfigured() {
+ assertEquals("com.zaxxer.hikari.HikariDataSource", dataSource.getClass()
+ .getName());
+ }
+
+}
diff --git a/spring-5/src/test/resources/logback-test.xml b/spring-5/src/test/resources/logback-test.xml
index 84f8e4706a..424ab87f79 100644
--- a/spring-5/src/test/resources/logback-test.xml
+++ b/spring-5/src/test/resources/logback-test.xml
@@ -1,5 +1,15 @@
-
-
+
+
+ # Pattern of log message for console appender
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml
index 1b9e831a29..0a19f483c1 100644
--- a/spring-activiti/pom.xml
+++ b/spring-activiti/pom.xml
@@ -2,9 +2,7 @@
4.0.0
- com.example
spring-activiti
- 0.0.1-SNAPSHOT
jar
spring-activiti
Demo project for Spring Boot
@@ -44,33 +42,6 @@
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
- 3
- true
-
- **/*IntegrationTest.java
- **/*IntTest.java
- **/*LongRunningUnitTest.java
- **/*ManualTest.java
- **/JdbcTest.java
- **/*LiveTest.java
-
-
-
-
-
-
-
com.example.activitiwithspring.ActivitiWithSpringApplication
UTF-8
diff --git a/spring-all/src/main/resources/logback.xml b/spring-all/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/spring-all/src/main/resources/logback.xml
+++ b/spring-all/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/spring-aop/src/main/resources/logback.xml b/spring-aop/src/main/resources/logback.xml
index 3245e94f08..7c15f603a0 100644
--- a/spring-aop/src/main/resources/logback.xml
+++ b/spring-aop/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/spring-batch/src/main/resources/logback.xml b/spring-batch/src/main/resources/logback.xml
index 0313fb5008..91d4292b8e 100644
--- a/spring-batch/src/main/resources/logback.xml
+++ b/spring-batch/src/main/resources/logback.xml
@@ -3,7 +3,7 @@
- %d{yyyy-MM-dd HH:mm:ss} [%thread] %level %logger{35} - %msg%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/spring-boot-admin/spring-boot-admin-client/pom.xml b/spring-boot-admin/spring-boot-admin-client/pom.xml
index fcbbb11cd7..ea03d6ef6d 100644
--- a/spring-boot-admin/spring-boot-admin-client/pom.xml
+++ b/spring-boot-admin/spring-boot-admin-client/pom.xml
@@ -46,6 +46,7 @@
org.springframework.boot
spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
@@ -59,6 +60,7 @@
1.5.4
+ 2.0.4.RELEASE
diff --git a/spring-boot-admin/spring-boot-admin-server/pom.xml b/spring-boot-admin/spring-boot-admin-server/pom.xml
index 50228034c1..d8e7bb5574 100644
--- a/spring-boot-admin/spring-boot-admin-server/pom.xml
+++ b/spring-boot-admin/spring-boot-admin-server/pom.xml
@@ -76,6 +76,7 @@
org.springframework.boot
spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
@@ -83,6 +84,7 @@
1.5.4
1.5.4
+ 2.0.4.RELEASE
diff --git a/spring-boot-angular-ecommerce/src/main/frontend/package.json b/spring-boot-angular-ecommerce/src/main/frontend/package.json
index 28e716b9a6..958e9f1023 100644
--- a/spring-boot-angular-ecommerce/src/main/frontend/package.json
+++ b/spring-boot-angular-ecommerce/src/main/frontend/package.json
@@ -5,6 +5,9 @@
"ng": "ng",
"start": "ng serve --proxy-config proxy-conf.json",
"build": "ng build",
+ "postbuild": "npm run deploy",
+ "predeploy": "rimraf ../resources/static/ && mkdirp ../resources/static",
+ "deploy": "copyfiles -f dist/** ../resources/static",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
diff --git a/spring-boot-bootstrap/cloudfoundry/manifest.yml b/spring-boot-bootstrap/cloudfoundry/manifest.yml
new file mode 100755
index 0000000000..80fce8ff4b
--- /dev/null
+++ b/spring-boot-bootstrap/cloudfoundry/manifest.yml
@@ -0,0 +1,10 @@
+---
+applications:
+- name: spring-boot-bootstrap
+ memory: 768M
+ random-route: true
+ path: ../target/spring-boot-bootstrap-cf.jar
+ env:
+ SPRING_PROFILES_ACTIVE: cloud,mysql
+ services:
+ - spring-bootstrap-db
diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml
index 5868694e5b..c1ce4df6e2 100644
--- a/spring-boot-bootstrap/pom.xml
+++ b/spring-boot-bootstrap/pom.xml
@@ -1,6 +1,6 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
org.baeldung
spring-boot-bootstrap
@@ -14,6 +14,17 @@
0.0.1-SNAPSHOT
../parent-boot-2
+
+
+
+ org.springframework.cloud
+ spring-cloud-dependencies
+ Finchley.SR1
+ pom
+ import
+
+
+
@@ -28,10 +39,22 @@
org.springframework.boot
spring-boot-starter-data-jpa
+
+ org.springframework.cloud
+ spring-cloud-starter
+
+
+ org.springframework.boot
+ spring-boot-starter-cloud-connectors
+
com.h2database
h2
+
+ mysql
+ mysql-connector-java
+
org.springframework.boot
spring-boot-starter-security
@@ -55,6 +78,47 @@
+
+ cloudfoundry
+
+
+ org.springframework.cloud
+ spring-cloud-starter
+
+
+ org.springframework.boot
+ spring-boot-starter-cloud-connectors
+
+
+
+
+
+ src/main/resources
+
+ **/logback.xml
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+ ${project.name}-cf
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ **/cloud/config/*.java
+
+
+
+
+
+
autoconfiguration
@@ -112,7 +176,19 @@
-
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ **/cloud/*.java
+
+
+
+
+
4.0.0
diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java b/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java
new file mode 100755
index 0000000000..b9f9598ca3
--- /dev/null
+++ b/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java
@@ -0,0 +1,19 @@
+package org.baeldung.cloud.config;
+
+import org.springframework.cloud.config.java.AbstractCloudConfig;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+
+import javax.sql.DataSource;
+
+@Configuration
+@Profile("cloud")
+public class CloudDataSourceConfig extends AbstractCloudConfig {
+
+ @Bean
+ public DataSource dataSource() {
+ return connectionFactory().dataSource();
+ }
+
+}
diff --git a/spring-boot-bootstrap/src/main/resources/application-local.properties b/spring-boot-bootstrap/src/main/resources/application-local.properties
new file mode 100644
index 0000000000..8c1c677988
--- /dev/null
+++ b/spring-boot-bootstrap/src/main/resources/application-local.properties
@@ -0,0 +1,20 @@
+server.port = 8081
+
+spring.application.name = Bootstrap Spring Boot
+
+spring.thymeleaf.cache = false
+spring.thymeleaf.enabled=true
+spring.thymeleaf.prefix=classpath:/templates/
+spring.thymeleaf.suffix=.html
+
+spring.security.user.name=john
+spring.security.user.password=123
+
+spring.datasource.driver-class-name=org.h2.Driver
+spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
+spring.datasource.username=sa
+spring.datasource.password=
+spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
+
+server.error.path=/error
+server.error.whitelabel.enabled=false
\ No newline at end of file
diff --git a/spring-boot-bootstrap/src/main/resources/application-mysql.properties b/spring-boot-bootstrap/src/main/resources/application-mysql.properties
new file mode 100644
index 0000000000..a1823b5d7f
--- /dev/null
+++ b/spring-boot-bootstrap/src/main/resources/application-mysql.properties
@@ -0,0 +1 @@
+spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
\ No newline at end of file
diff --git a/spring-boot-bootstrap/src/main/resources/application.properties b/spring-boot-bootstrap/src/main/resources/application.properties
index e50268d32c..eee89ca460 100644
--- a/spring-boot-bootstrap/src/main/resources/application.properties
+++ b/spring-boot-bootstrap/src/main/resources/application.properties
@@ -1,19 +1,11 @@
-server.port = 8081
-
-spring.application.name = Bootstrap Spring Boot
-
+server.port=${port:8080}
+spring.application.name = Bootstrap Spring Cloud
spring.thymeleaf.cache = false
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
-spring.security.user.name=john
-spring.security.user.password=123
-
-spring.datasource.driver-class-name=org.h2.Driver
-spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
-spring.datasource.username=sa
-spring.datasource.password=
-
server.error.path=/error
-server.error.whitelabel.enabled=false
\ No newline at end of file
+server.error.whitelabel.enabled=false
+
+spring.jpa.generate-ddl=true
\ No newline at end of file
diff --git a/spring-boot-client/.gitignore b/spring-boot-client/.gitignore
new file mode 100644
index 0000000000..da7c2c5c0a
--- /dev/null
+++ b/spring-boot-client/.gitignore
@@ -0,0 +1,5 @@
+/target/
+.settings/
+.classpath
+.project
+
diff --git a/spring-boot-client/README.MD b/spring-boot-client/README.MD
new file mode 100644
index 0000000000..8db48089a5
--- /dev/null
+++ b/spring-boot-client/README.MD
@@ -0,0 +1,7 @@
+### The Course
+The "REST With Spring" Classes: http://bit.ly/restwithspring
+
+### Relevant Articles:
+
+- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot)
+- [A Java Client for a WebSockets API](http://www.baeldung.com/websockets-api-java-spring-client)
\ No newline at end of file
diff --git a/spring-boot-client/pom.xml b/spring-boot-client/pom.xml
new file mode 100644
index 0000000000..fc89931f79
--- /dev/null
+++ b/spring-boot-client/pom.xml
@@ -0,0 +1,141 @@
+
+ 4.0.0
+ com.baeldung
+ spring-boot-client
+ 0.0.1-SNAPSHOT
+ war
+ spring-boot-client
+ This is simple boot client application for Spring boot actuator test
+
+
+ parent-boot-2
+ com.baeldung
+ 0.0.1-SNAPSHOT
+ ../parent-boot-2
+
+
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter-api
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
+
+
+
+ org.junit.platform
+ junit-platform-launcher
+ ${junit-platform.version}
+ test
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ com.h2database
+ h2
+
+
+ org.springframework.boot
+ spring-boot-starter
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+ org.springframework
+ spring-websocket
+
+
+ org.springframework
+ spring-messaging
+
+
+
+
+
+ spring-boot-client
+
+
+ src/main/resources
+ true
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+
+
+
+ pl.project13.maven
+ git-commit-id-plugin
+ ${git-commit-id-plugin.version}
+
+
+
+
+
+
+
+
+ autoconfiguration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*LiveTest.java
+ **/*IntegrationTest.java
+ **/*IntTest.java
+
+
+ **/AutoconfigurationTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
+
+
+ 18.0
+ 1.2.0
+ 2.2.4
+
+
+
\ No newline at end of file
diff --git a/spring-boot-client/src/main/java/org/baeldung/boot/Application.java b/spring-boot-client/src/main/java/org/baeldung/boot/Application.java
new file mode 100644
index 0000000000..c1b6558b26
--- /dev/null
+++ b/spring-boot-client/src/main/java/org/baeldung/boot/Application.java
@@ -0,0 +1,14 @@
+package org.baeldung.boot;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.ApplicationContext;
+
+@SpringBootApplication
+public class Application {
+ private static ApplicationContext applicationContext;
+
+ public static void main(String[] args) {
+ applicationContext = SpringApplication.run(Application.class, args);
+ }
+}
diff --git a/spring-boot/src/main/java/org/baeldung/boot/client/Details.java b/spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java
similarity index 100%
rename from spring-boot/src/main/java/org/baeldung/boot/client/Details.java
rename to spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java
diff --git a/spring-boot/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java b/spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java
similarity index 100%
rename from spring-boot/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java
rename to spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java
diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java b/spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java
similarity index 100%
rename from spring-boot/src/main/java/org/baeldung/websocket/client/Message.java
rename to spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java
diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java b/spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java
similarity index 100%
rename from spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java
rename to spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java
diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java b/spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java
similarity index 100%
rename from spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java
rename to spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java
diff --git a/spring-boot-client/src/main/resources/logback.xml b/spring-boot-client/src/main/resources/logback.xml
new file mode 100644
index 0000000000..56af2d397e
--- /dev/null
+++ b/spring-boot-client/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/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java
similarity index 100%
rename from spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java
rename to spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java
diff --git a/spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java b/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java
similarity index 91%
rename from spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java
rename to spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java
index 37fc202e8a..71fb330663 100644
--- a/spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java
+++ b/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java
@@ -1,23 +1,24 @@
package org.baeldung.boot.client;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
-import org.springframework.http.MediaType;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.test.web.client.MockRestServiceServer;
-
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
-import org.baeldung.boot.client.Details;
-import org.baeldung.boot.client.DetailsServiceClient;
+import org.baeldung.boot.Application;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.http.MediaType;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.client.MockRestServiceServer;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
+@SpringBootTest(classes = Application.class)
@RestClientTest(DetailsServiceClient.class)
public class DetailsServiceClientIntegrationTest {
diff --git a/spring-boot-persistence/README.MD b/spring-boot-persistence/README.MD
index 3fe6eb62c8..72fdca74fa 100644
--- a/spring-boot-persistence/README.MD
+++ b/spring-boot-persistence/README.MD
@@ -1,3 +1,5 @@
### Relevant Articles:
- [Spring Boot with Multiple SQL Import Files](http://www.baeldung.com/spring-boot-sql-import-files)
+- [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source)
+- [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql)
diff --git a/spring-boot-persistence/pom.xml b/spring-boot-persistence/pom.xml
index 60e6689e31..08989edfa9 100644
--- a/spring-boot-persistence/pom.xml
+++ b/spring-boot-persistence/pom.xml
@@ -1,53 +1,75 @@
-
+
+
4.0.0
+
com.baeldung
spring-boot-persistence
- 0.0.1-SNAPSHOT
- jar
- spring-boot-persistence
- This is a simple Spring Data Repositories test
-
+ 0.1.0
+
parent-boot-2
- com.baeldung
- 0.0.1-SNAPSHOT
- ../parent-boot-2
+ com.baeldung
+ 0.0.1-SNAPSHOT
+ ../parent-boot-2
-
+
org.springframework.boot
spring-boot-starter-data-jpa
+
+
+ com.zaxxer
+ HikariCP
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.apache.tomcat
+ tomcat-jdbc
+ ${tomcat-jdbc.version}
+
+
+ mysql
+ mysql-connector-java
+ ${mysql-connector-java.version}
com.h2database
h2
-
-
- org.springframework.boot
- spring-boot-starter
+ ${h2database.version}
+ runtime
-
+
+
+ UTF-8
+ 1.8
+ 8.0.12
+ 9.0.10
+ 1.4.197
+
+
spring-boot-persistence
-
- src/main/resources
- true
-
+
+ src/main/resources
+ true
+
- org.apache.maven.plugins
- maven-war-plugin
-
-
- pl.project13.maven
- git-commit-id-plugin
+ org.springframework.boot
+ spring-boot-maven-plugin
-
-
\ No newline at end of file
+
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java b/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java
similarity index 73%
rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java
rename to spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java
index 439c6cb602..ef90714347 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java
+++ b/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java
@@ -1,11 +1,10 @@
-package org.baeldung.config;
+package com.baeldung.boot.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
-import org.baeldung.extended.persistence.dao.ExtendedRepositoryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -19,10 +18,10 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
-@EnableJpaRepositories(basePackages = "org.baeldung.extended.persistence.dao", repositoryBaseClass = ExtendedRepositoryImpl.class)
-@PropertySource("persistence-student-h2.properties")
+@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.repository" })
+@PropertySource("classpath:persistence-generic-entity.properties")
@EnableTransactionManagement
-public class StudentJPAH2Config {
+public class H2JpaConfig {
@Autowired
private Environment env;
@@ -42,15 +41,15 @@ public class StudentJPAH2Config {
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
- em.setPackagesToScan(new String[] { "org.baeldung.inmemory.persistence.model" });
+ em.setPackagesToScan(new String[] { "org.baeldung.boot.domain" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
- JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
- JpaTransactionManager transactionManager = new JpaTransactionManager();
+ JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
+ final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
@@ -61,9 +60,8 @@ public class StudentJPAH2Config {
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
- hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
- hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
return hibernateProperties;
}
+
}
diff --git a/spring-boot-persistence/src/main/java/com/baeldung/domain/Country.java b/spring-boot-persistence/src/main/java/com/baeldung/domain/Country.java
new file mode 100644
index 0000000000..e6a88c7121
--- /dev/null
+++ b/spring-boot-persistence/src/main/java/com/baeldung/domain/Country.java
@@ -0,0 +1,36 @@
+package com.baeldung.domain;
+
+import static javax.persistence.GenerationType.IDENTITY;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+@Entity
+public class Country {
+
+ @Id
+ @GeneratedValue(strategy = IDENTITY)
+ private Integer id;
+
+ @Column(nullable = false)
+ private String name;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java
new file mode 100644
index 0000000000..ff37442cd4
--- /dev/null
+++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java
@@ -0,0 +1,22 @@
+package com.baeldung.tomcatconnectionpool.application;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.domain.EntityScan;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+@SpringBootApplication
+@EnableAutoConfiguration
+@ComponentScan(basePackages={"com.baeldung.tomcatconnectionpool.application"})
+@EnableJpaRepositories(basePackages="com.baeldung.tomcatconnectionpool.application.repositories")
+@EnableTransactionManagement
+@EntityScan(basePackages="com.baeldung.tomcatconnectionpool.application.entities")
+public class SpringBootConsoleApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SpringBootConsoleApplication.class);
+ }
+}
diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java
new file mode 100644
index 0000000000..4003d5aca9
--- /dev/null
+++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java
@@ -0,0 +1,53 @@
+package com.baeldung.tomcatconnectionpool.application.entities;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "customers")
+public class Customer {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private long id;
+ @Column(name = "first_name")
+ private String firstName;
+ @Column(name = "last_name")
+ private String lastName;
+
+ public Customer() {}
+
+ public Customer(String firstName, String lastName) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ @Override
+ public String toString() {
+ return "Customer{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + '}';
+ }
+}
diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java
new file mode 100644
index 0000000000..770906439c
--- /dev/null
+++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java
@@ -0,0 +1,12 @@
+package com.baeldung.tomcatconnectionpool.application.repositories;
+
+import com.baeldung.tomcatconnectionpool.application.entities.Customer;
+import java.util.List;
+import org.springframework.data.repository.CrudRepository;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface CustomerRepository extends CrudRepository {
+
+ List findByLastName(String lastName);
+}
diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java
new file mode 100644
index 0000000000..9666bac5a5
--- /dev/null
+++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java
@@ -0,0 +1,37 @@
+package com.baeldung.tomcatconnectionpool.application.runners;
+
+import com.baeldung.tomcatconnectionpool.application.entities.Customer;
+import com.baeldung.tomcatconnectionpool.application.repositories.CustomerRepository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.CommandLineRunner;
+import org.springframework.stereotype.Component;
+
+@Component
+public class CommandLineCrudRunner implements CommandLineRunner {
+
+ private static final Logger logger = LoggerFactory.getLogger(CommandLineCrudRunner.class);
+
+ @Autowired
+ private CustomerRepository customerRepository;
+
+ @Override
+ public void run(String... args) throws Exception {
+ customerRepository.save(new Customer("John", "Doe"));
+ customerRepository.save(new Customer("Jennifer", "Wilson"));
+
+ logger.info("Customers found with findAll():");
+ customerRepository.findAll().forEach(c -> logger.info(c.toString()));
+
+ logger.info("Customer found with findById(1L):");
+ Customer customer = customerRepository.findById(1L)
+ .orElseGet(() -> new Customer("Non-existing customer", ""));
+ logger.info(customer.toString());
+
+ logger.info("Customer found with findByLastName('Wilson'):");
+ customerRepository.findByLastName("Wilson").forEach(c -> {
+ logger.info(c.toString());
+ });
+ }
+}
diff --git a/spring-boot/src/main/java/org/baeldung/boot/domain/GenericEntity.java b/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java
similarity index 100%
rename from spring-boot/src/main/java/org/baeldung/boot/domain/GenericEntity.java
rename to spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java
diff --git a/spring-boot/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java b/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java
similarity index 100%
rename from spring-boot/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java
rename to spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java
diff --git a/spring-boot-persistence/src/main/resources/application.properties b/spring-boot-persistence/src/main/resources/application.properties
index e69de29bb2..303ce33c25 100644
--- a/spring-boot-persistence/src/main/resources/application.properties
+++ b/spring-boot-persistence/src/main/resources/application.properties
@@ -0,0 +1,16 @@
+spring.datasource.tomcat.initial-size=15
+spring.datasource.tomcat.max-wait=20000
+spring.datasource.tomcat.max-active=50
+spring.datasource.tomcat.max-idle=15
+spring.datasource.tomcat.min-idle=8
+spring.datasource.tomcat.default-auto-commit=true
+spring.datasource.url=jdbc:h2:mem:test
+spring.datasource.username=root
+spring.datasource.password=
+spring.datasource.driver-class-name=org.h2.Driver
+
+spring.jpa.show-sql=false
+spring.jpa.hibernate.ddl-auto=update
+spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
+spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
+spring.jpa.properties.hibernate.id.new_generator_mappings=false
diff --git a/spring-boot-persistence/src/main/resources/data.sql b/spring-boot-persistence/src/main/resources/data.sql
new file mode 100644
index 0000000000..feef02b6cf
--- /dev/null
+++ b/spring-boot-persistence/src/main/resources/data.sql
@@ -0,0 +1,10 @@
+insert into users values (1, 'Alex', 1);
+insert into users values (2, 'Bob', 1);
+insert into users values (3, 'John', 0);
+insert into users values (4, 'Harry', 0);
+insert into users values (5, 'Smith', 1);
+
+INSERT INTO country (name) VALUES ('India');
+INSERT INTO country (name) VALUES ('Brazil');
+INSERT INTO country (name) VALUES ('USA');
+INSERT INTO country (name) VALUES ('Italy');
\ No newline at end of file
diff --git a/spring-boot-persistence/src/main/resources/persistence-generic-entity.properties b/spring-boot-persistence/src/main/resources/persistence-generic-entity.properties
new file mode 100644
index 0000000000..b19304cb1f
--- /dev/null
+++ b/spring-boot-persistence/src/main/resources/persistence-generic-entity.properties
@@ -0,0 +1,8 @@
+jdbc.driverClassName=org.h2.Driver
+jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
+jdbc.user=sa
+jdbc.pass=sa
+
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.show_sql=true
+hibernate.hbm2ddl.auto=create-drop
diff --git a/spring-boot-persistence/src/main/resources/schema.sql b/spring-boot-persistence/src/main/resources/schema.sql
new file mode 100644
index 0000000000..4cfc8a7927
--- /dev/null
+++ b/spring-boot-persistence/src/main/resources/schema.sql
@@ -0,0 +1,15 @@
+drop table if exists USERS;
+drop table if exists country;
+
+create table USERS(
+ ID int not null AUTO_INCREMENT,
+ NAME varchar(100) not null,
+ STATUS int,
+ PRIMARY KEY ( ID )
+);
+
+CREATE TABLE country (
+ id INTEGER NOT NULL AUTO_INCREMENT,
+ name VARCHAR(128) NOT NULL,
+ PRIMARY KEY (id)
+);
\ No newline at end of file
diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java
similarity index 91%
rename from spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java
rename to spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java
index 290cfbe081..6479e90113 100644
--- a/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java
+++ b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java
@@ -1,7 +1,8 @@
-package org.baeldung;
+package com.baeldung;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
-import org.baeldung.boot.Application;
-import org.baeldung.boot.config.H2JpaConfig;
import org.baeldung.boot.domain.GenericEntity;
import org.baeldung.boot.repository.GenericEntityRepository;
import org.junit.Test;
@@ -10,8 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import com.baeldung.boot.config.H2JpaConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { Application.class, H2JpaConfig.class })
diff --git a/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java
new file mode 100644
index 0000000000..eef9ebe953
--- /dev/null
+++ b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java
@@ -0,0 +1,27 @@
+package com.baeldung;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.baeldung.boot.domain.GenericEntity;
+import org.baeldung.boot.repository.GenericEntityRepository;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = Application.class)
+public class SpringBootJPAIntegrationTest {
+ @Autowired
+ private GenericEntityRepository genericEntityRepository;
+
+ @Test
+ public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
+ GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
+ GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
+ assertNotNull(foundEntity);
+ assertEquals(genericEntity.getValue(), foundEntity.getValue());
+ }
+}
\ No newline at end of file
diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java
similarity index 95%
rename from spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java
rename to spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java
index 128a05f103..4c68f1d4a0 100644
--- a/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java
+++ b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java
@@ -1,6 +1,8 @@
-package org.baeldung;
+package com.baeldung;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
-import org.baeldung.boot.Application;
import org.baeldung.boot.domain.GenericEntity;
import org.baeldung.boot.repository.GenericEntityRepository;
import org.baeldung.config.H2TestProfileJPAConfig;
@@ -11,9 +13,6 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class, H2TestProfileJPAConfig.class })
@ActiveProfiles("test")
diff --git a/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java
new file mode 100644
index 0000000000..c68e137fb0
--- /dev/null
+++ b/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.tomcatconnectionpool.test.application;
+
+import javax.sql.DataSource;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.junit4.SpringRunner;
+import static org.assertj.core.api.Assertions.*;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class SpringBootTomcatConnectionPoolIntegrationTest {
+
+ @Autowired
+ private DataSource dataSource;
+
+ @Test
+ public void givenTomcatConnectionPoolInstance_whenCheckedPoolClassName_thenCorrect() {
+ assertThat(dataSource.getClass().getName()).isEqualTo("org.apache.tomcat.jdbc.pool.DataSource");
+ }
+}
diff --git a/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java b/spring-boot-persistence/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java
similarity index 94%
rename from spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java
rename to spring-boot-persistence/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java
index d0b92a7a93..7f962e1417 100644
--- a/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java
+++ b/spring-boot-persistence/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java
@@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
-@EnableJpaRepositories(basePackages = { "org.baeldung.repository", "org.baeldung.boot.repository", "org.baeldung.boot.boottest" })
+@EnableJpaRepositories(basePackages = { "org.baeldung.repository", "org.baeldung.boot.repository" })
@EnableTransactionManagement
public class H2TestProfileJPAConfig {
@@ -41,7 +41,7 @@ public class H2TestProfileJPAConfig {
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
- em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain", "org.baeldung.boot.boottest", "org.baeldung.model" });
+ em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
diff --git a/spring-boot-persistence/src/test/resources/application.properties b/spring-boot-persistence/src/test/resources/application.properties
index a5d09db840..a5c1d983cf 100644
--- a/spring-boot-persistence/src/test/resources/application.properties
+++ b/spring-boot-persistence/src/test/resources/application.properties
@@ -13,4 +13,4 @@ hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
spring.jpa.properties.hibernate.hbm2ddl.import_files=migrated_users.sql
-spring.datasource.data=import_*_users.sql,import_articles.sql
\ No newline at end of file
+spring.datasource.data=import_*_users.sql
\ No newline at end of file
diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml
index 12f51eec94..18d292c8a1 100644
--- a/spring-boot-security/pom.xml
+++ b/spring-boot-security/pom.xml
@@ -44,6 +44,23 @@
org.springframework.boot
spring-boot-starter-web
+
+
+
+ org.springframework.security
+ spring-security-taglibs
+
+
+
+
+ org.apache.tomcat.embed
+ tomcat-embed-jasper
+ provided
+
+
+ javax.servlet
+ jstl
+
org.springframework.boot
@@ -67,12 +84,14 @@
org.springframework.boot
spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
1.5.9.RELEASE
+ 2.0.4.RELEASE
diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java
new file mode 100644
index 0000000000..dccbace106
--- /dev/null
+++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java
@@ -0,0 +1,13 @@
+package com.baeldung.integrationtesting;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
+import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
+
+@Configuration
+@EnableGlobalMethodSecurity(
+ prePostEnabled = true,
+ securedEnabled = true)
+public class MethodSecurityConfigurer extends GlobalMethodSecurityConfiguration {
+
+}
diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java
new file mode 100644
index 0000000000..18469e4752
--- /dev/null
+++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.integrationtesting;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class SecuredApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SecuredApplication.class, args);
+ }
+
+}
diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java
new file mode 100644
index 0000000000..495c358784
--- /dev/null
+++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java
@@ -0,0 +1,21 @@
+package com.baeldung.integrationtesting;
+
+import java.util.Arrays;
+import java.util.List;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+public class SecuredController {
+
+ @GetMapping("/public/hello")
+ public List publicHello() {
+ return Arrays.asList("Hello", "World", "from", "Public");
+ }
+
+ @GetMapping("/private/hello")
+ public List privateHello() {
+ return Arrays.asList("Hello", "World", "from", "Private");
+ }
+
+}
diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java
new file mode 100644
index 0000000000..25253f163a
--- /dev/null
+++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java
@@ -0,0 +1,13 @@
+package com.baeldung.integrationtesting;
+
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.stereotype.Service;
+
+@Service
+public class SecuredService {
+
+ @PreAuthorize("authenticated")
+ public String sayHelloSecured() {
+ return "Hello user.";
+ }
+}
diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java
new file mode 100644
index 0000000000..32a48ce612
--- /dev/null
+++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java
@@ -0,0 +1,31 @@
+package com.baeldung.integrationtesting;
+
+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.WebSecurityConfigurerAdapter;
+
+@Configuration
+public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
+
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth.inMemoryAuthentication()
+ .withUser("spring")
+ .password("secret")
+ .roles("USER");
+ }
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.authorizeRequests()
+ .antMatchers("/private/**")
+ .hasRole("USER")
+ .antMatchers("/public/**")
+ .permitAll()
+ .and()
+ .httpBasic();
+ }
+
+
+}
diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java
new file mode 100644
index 0000000000..eca093a76f
--- /dev/null
+++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java
@@ -0,0 +1,14 @@
+package com.baeldung.springsecuritytaglibs;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+@Controller
+@RequestMapping("/")
+public class HomeController {
+
+ @RequestMapping
+ public String home() {
+ return "home";
+ }
+}
diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java
new file mode 100644
index 0000000000..397ea47f96
--- /dev/null
+++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java
@@ -0,0 +1,9 @@
+package com.baeldung.springsecuritytaglibs;
+
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.PropertySource;
+
+@SpringBootApplication
+@PropertySource("classpath:application-taglibs.properties")
+public class SpringBootSecurityTagLibsApplication {
+}
diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java
new file mode 100644
index 0000000000..665dd0bce9
--- /dev/null
+++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java
@@ -0,0 +1,31 @@
+package com.baeldung.springsecuritytaglibs.config;
+
+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;
+
+@Configuration
+@EnableWebSecurity
+public class SpringBootSecurityTagLibsConfig extends WebSecurityConfigurerAdapter {
+
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth.inMemoryAuthentication()
+ .withUser("testUser")
+ .password("password")
+ .roles("ADMIN");
+ }
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ // @formatter:off
+ http.csrf()
+ .and()
+ .authorizeRequests()
+ .antMatchers("/userManagement").hasRole("ADMIN")
+ .anyRequest().permitAll().and().httpBasic();
+ // @formatter:on
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-security/src/main/resources/application-taglibs.properties b/spring-boot-security/src/main/resources/application-taglibs.properties
new file mode 100644
index 0000000000..218868405f
--- /dev/null
+++ b/spring-boot-security/src/main/resources/application-taglibs.properties
@@ -0,0 +1,3 @@
+#jsp config
+spring.mvc.view.prefix: /WEB-INF/views/
+spring.mvc.view.suffix: .jsp
diff --git a/spring-boot-security/src/main/resources/application.properties b/spring-boot-security/src/main/resources/application.properties
index c2b8d70dc6..e776132359 100644
--- a/spring-boot-security/src/main/resources/application.properties
+++ b/spring-boot-security/src/main/resources/application.properties
@@ -1,4 +1,4 @@
#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
#security.user.password=password
#security.oauth2.client.client-id=client
-#security.oauth2.client.client-secret=secret
+#security.oauth2.client.client-secret=secret
\ No newline at end of file
diff --git a/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp
new file mode 100644
index 0000000000..80ecd61cb5
--- /dev/null
+++ b/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp
@@ -0,0 +1,38 @@
+<%@ page language="java" contentType="text/html; charset=UTF-8"
+ pageEncoding="UTF-8"%>
+<%@ taglib prefix="sec"
+ uri="http://www.springframework.org/security/tags"%>
+
+
+
+
+
+Home Page
+
+
+
+ Login
+
+
+
+ Logout
+
+
+
+
+ Welcome back,
+
+
+ Manage Users
+
+
+
+ Manage Users
+
+
+
+
\ No newline at end of file
diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java
new file mode 100644
index 0000000000..c224058155
--- /dev/null
+++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java
@@ -0,0 +1,34 @@
+package com.baeldung.integrationtesting;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
+import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+public class SecuredControllerRestTemplateIntegrationTest {
+
+ @Autowired
+ private TestRestTemplate template;
+
+ @Test
+ public void givenRequestOnPrivateService_shouldFailWith401() throws Exception {
+ ResponseEntity result = template.getForEntity("/private/hello", String.class);
+ assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
+ }
+
+ @Test
+ public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception {
+ ResponseEntity result = template.withBasicAuth("spring", "secret")
+ .getForEntity("/private/hello", String.class);
+ assertEquals(HttpStatus.OK, result.getStatusCode());
+ }
+
+}
diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java
new file mode 100644
index 0000000000..ce9e6de917
--- /dev/null
+++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.integrationtesting;
+
+import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
+import org.springframework.http.MediaType;
+import org.springframework.security.test.context.support.WithMockUser;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+public class SecuredControllerSpringBootIntegrationTest {
+
+ @Autowired
+ private WebApplicationContext context;
+
+ private MockMvc mvc;
+
+ @Before
+ public void setup() {
+ mvc = MockMvcBuilders
+ .webAppContextSetup(context)
+ .apply(springSecurity())
+ .build();
+ }
+
+ @Test
+ public void givenRequestOnPrivateService_shouldFailWith401() throws Exception {
+ mvc.perform(get("/private/hello")
+ .contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().isUnauthorized());
+ }
+
+ @WithMockUser("spring")
+ @Test
+ public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception {
+ mvc.perform(get("/private/hello")
+ .contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk());
+ }
+
+}
diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java
new file mode 100644
index 0000000000..7281648856
--- /dev/null
+++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java
@@ -0,0 +1,39 @@
+package com.baeldung.integrationtesting;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
+import org.springframework.http.MediaType;
+import org.springframework.security.test.context.support.WithMockUser;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.MockMvc;
+
+import com.baeldung.integrationtesting.SecuredController;
+
+@RunWith(SpringRunner.class)
+@WebMvcTest(SecuredController.class)
+public class SecuredControllerWebMvcIntegrationTest {
+
+ @Autowired
+ private MockMvc mvc;
+
+ @Test
+ public void givenRequestOnPrivateService_shouldFailWith401() throws Exception {
+ mvc.perform(get("/private/hello")
+ .contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().isUnauthorized());
+ }
+
+ @WithMockUser(value = "spring")
+ @Test
+ public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception {
+ mvc.perform(get("/private/hello")
+ .contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk());
+ }
+
+}
diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java
new file mode 100644
index 0000000000..816b05bd5a
--- /dev/null
+++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java
@@ -0,0 +1,32 @@
+package com.baeldung.integrationtesting;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
+import org.springframework.security.test.context.support.WithMockUser;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import com.baeldung.integrationtesting.SecuredService;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class SecuredMethodSpringBootIntegrationTest {
+
+ @Autowired
+ private SecuredService service;
+
+ @Test(expected = AuthenticationCredentialsNotFoundException.class)
+ public void givenUnauthenticated_whenCallService_thenThrowsException() {
+ service.sayHelloSecured();
+ }
+
+ @WithMockUser(username="spring")
+ @Test
+ public void givenAuthenticated_whenCallServiceWithSecured_thenOk() {
+ assertThat(service.sayHelloSecured()).isNotBlank();
+ }
+}
diff --git a/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java
new file mode 100644
index 0000000000..0585c06a59
--- /dev/null
+++ b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java
@@ -0,0 +1,60 @@
+package com.baeldung.springsecuritytaglibs;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
+import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class)
+public class HomeControllerUnitTest {
+
+ @Autowired
+ private TestRestTemplate restTemplate;
+
+ @Test
+ public void whenUserIsAuthenticatedThenAuthenticatedSectionsShowOnSite() throws Exception {
+ String body = this.restTemplate.withBasicAuth("testUser", "password")
+ .getForEntity("/", String.class)
+ .getBody();
+
+ // test
+ assertFalse(body.contains("Login"));
+
+ // test
+ assertTrue(body.contains("Logout"));
+
+ // test
+ assertTrue(body.contains("Manage Users"));
+
+ // test
+ assertTrue(body.contains("testUser"));
+
+ // test
+ assertTrue(body.contains(""));
+
+ // test
+ assertTrue(body.contains("
+ assertTrue(body.contains(""));
+ }
+
+ @Test
+ public void whenUserIsNotAuthenticatedThenOnlyAnonymousSectionsShowOnSite() throws Exception {
+ String body = this.restTemplate.getForEntity("/", String.class)
+ .getBody();
+
+ // test
+ assertTrue(body.contains("Login"));
+
+ // test
+ assertFalse(body.contains("Logout"));
+ }
+}
diff --git a/spring-boot/README.MD b/spring-boot/README.MD
index 1532889a5c..f11ea1b7ed 100644
--- a/spring-boot/README.MD
+++ b/spring-boot/README.MD
@@ -3,7 +3,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
-- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot)
- [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring)
- [The @ServletComponentScan Annotation in Spring Boot](http://www.baeldung.com/spring-servletcomponentscan)
- [Intro to Building an Application with Spring Boot](http://www.baeldung.com/intro-to-spring-boot)
@@ -12,19 +11,15 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Using Custom Banners in Spring Boot](http://www.baeldung.com/spring-boot-custom-banners)
- [Guide to Internationalization in Spring Boot](http://www.baeldung.com/spring-boot-internationalization)
- [Create a Custom FailureAnalyzer with Spring Boot](http://www.baeldung.com/spring-boot-failure-analyzer)
-- [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source)
- [Dynamic DTO Validation Config Retrieved from DB](http://www.baeldung.com/spring-dynamic-dto-validation)
- [Custom Information in Spring Boot Info Endpoint](http://www.baeldung.com/spring-boot-info-actuator-custom)
- [Using @JsonComponent in Spring Boot](http://www.baeldung.com/spring-boot-jsoncomponent)
- [Testing in Spring Boot](http://www.baeldung.com/spring-boot-testing)
- [Guide to @ConfigurationProperties in Spring Boot](http://www.baeldung.com/configuration-properties-in-spring-boot)
- [How to Get All Spring-Managed Beans?](http://www.baeldung.com/spring-show-all-beans)
-- [A Java Client for a WebSockets API](http://www.baeldung.com/websockets-api-java-spring-client)
- [Spring Boot and Togglz Aspect](http://www.baeldung.com/spring-togglz)
- [Getting Started with GraphQL and Spring Boot](http://www.baeldung.com/spring-graphql)
- [Guide to Spring Type Conversions](http://www.baeldung.com/spring-type-conversions)
-- [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql)
-- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8)
- [An Introduction to Kong](http://www.baeldung.com/kong)
- [Spring Boot Customize Whitelabel Error Page](http://www.baeldung.com/spring-boot-custom-error-page)
- [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class)
diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml
index 3a43dbd828..50859f674c 100644
--- a/spring-boot/pom.xml
+++ b/spring-boot/pom.xml
@@ -117,16 +117,6 @@
provided
-
- org.springframework
- spring-websocket
-
-
-
- org.springframework
- spring-messaging
-
-
org.togglz
togglz-spring-boot-starter
@@ -176,6 +166,7 @@
pl.project13.maven
git-commit-id-plugin
+ ${git-commit-id-plugin.version}
@@ -230,6 +221,7 @@
3.2.0
18.0
1.2.0
+ 2.2.4
\ No newline at end of file
diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java b/spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java
new file mode 100644
index 0000000000..9ddcf12d4e
--- /dev/null
+++ b/spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java
@@ -0,0 +1,5 @@
+package com.baeldung.componentscan;
+
+public class ExampleBean {
+
+}
diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java
new file mode 100644
index 0000000000..2377ed7a56
--- /dev/null
+++ b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java
@@ -0,0 +1,38 @@
+package com.baeldung.componentscan.springapp;
+
+import org.springframework.context.annotation.FilterType;
+import org.springframework.stereotype.Component;
+
+import com.baeldung.componentscan.ExampleBean;
+import com.baeldung.componentscan.springapp.flowers.Rose;
+
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan
+//@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Rose.class))
+//@ComponentScan(basePackages = "com.baeldung.componentscan.springapp")
+//@ComponentScan(basePackages = "com.baeldung.componentscan.springapp.animals")
+//@ComponentScan (excludeFilters = @ComponentScan.Filter(type=FilterType.REGEX,pattern="com\\.baeldung\\.componentscan\\.springapp\\.flowers\\..*"))
+public class SpringComponentScanApp {
+
+ private static ApplicationContext applicationContext;
+
+ @Bean
+ public ExampleBean exampleBean() {
+ return new ExampleBean();
+ }
+
+ public static void main(String[] args) {
+ applicationContext = new AnnotationConfigApplicationContext(SpringComponentScanApp.class);
+
+ for (String beanName : applicationContext.getBeanDefinitionNames()) {
+ System.out.println(beanName);
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java
new file mode 100644
index 0000000000..5f5b482972
--- /dev/null
+++ b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java
@@ -0,0 +1,8 @@
+package com.baeldung.componentscan.springapp.animals;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class Cat {
+
+}
diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java
new file mode 100644
index 0000000000..009162b57f
--- /dev/null
+++ b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java
@@ -0,0 +1,8 @@
+package com.baeldung.componentscan.springapp.animals;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class Dog {
+
+}
diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java
new file mode 100644
index 0000000000..b777b073b9
--- /dev/null
+++ b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java
@@ -0,0 +1,8 @@
+package com.baeldung.componentscan.springapp.flowers;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class Rose {
+
+}
diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java
new file mode 100644
index 0000000000..ba29a4e1f5
--- /dev/null
+++ b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java
@@ -0,0 +1,37 @@
+package com.baeldung.componentscan.springbootapp;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.context.annotation.FilterType;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+
+import com.baeldung.componentscan.ExampleBean;
+import com.baeldung.componentscan.springbootapp.flowers.Rose;
+
+@SpringBootApplication
+//@ComponentScan(basePackages = "com.baeldung.componentscan.springbootapp.animals")
+//@ComponentScan ( excludeFilters = @ComponentScan.Filter(type=FilterType.REGEX,pattern="com\\.baeldung\\.componentscan\\.springbootapp\\.flowers\\..*"))
+//@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Rose.class))
+
+public class SpringBootComponentScanApp {
+ private static ApplicationContext applicationContext;
+
+ @Bean
+ public ExampleBean exampleBean() {
+ return new ExampleBean();
+ }
+
+ public static void main(String[] args) {
+ applicationContext = SpringApplication.run(SpringBootComponentScanApp.class, args);
+ checkBeansPresence("cat", "dog", "rose", "exampleBean", "springBootApp");
+
+ }
+
+ private static void checkBeansPresence(String... beans) {
+ for (String beanName : beans) {
+ System.out.println("Is " + beanName + " in ApplicationContext: " + applicationContext.containsBean(beanName));
+ }
+ }
+}
diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java
new file mode 100644
index 0000000000..7c43d6a24c
--- /dev/null
+++ b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java
@@ -0,0 +1,8 @@
+package com.baeldung.componentscan.springbootapp.animals;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class Cat {
+
+}
diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java
new file mode 100644
index 0000000000..145430cb54
--- /dev/null
+++ b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java
@@ -0,0 +1,8 @@
+package com.baeldung.componentscan.springbootapp.animals;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class Dog {
+
+}
diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java
new file mode 100644
index 0000000000..0ccf782685
--- /dev/null
+++ b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java
@@ -0,0 +1,8 @@
+package com.baeldung.componentscan.springbootapp.flowers;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class Rose {
+
+}
diff --git a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java
index cba504b6c6..7335af2616 100644
--- a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java
+++ b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java
@@ -24,8 +24,6 @@ public interface UserRepository extends JpaRepository {
Optional findOneByName(String name);
- Stream findAllByName(String name);
-
@Async
CompletableFuture findOneByStatus(Integer status);
diff --git a/spring-boot/src/main/resources/logback.xml b/spring-boot/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/spring-boot/src/main/resources/logback.xml
+++ b/spring-boot/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java
index 72d204820e..04bb1170f8 100644
--- a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java
+++ b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java
@@ -52,30 +52,6 @@ public class UserRepositoryIntegrationTest {
.getName()).isEqualTo(USER_NAME_ADAM);
}
- @Test
- @Transactional
- public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() {
- User user1 = new User();
- user1.setName(USER_NAME_ADAM);
- userRepository.save(user1);
-
- User user2 = new User();
- user2.setName(USER_NAME_ADAM);
- userRepository.save(user2);
-
- User user3 = new User();
- user3.setName(USER_NAME_ADAM);
- userRepository.save(user3);
-
- User user4 = new User();
- user4.setName("SAMPLE");
- userRepository.save(user4);
-
- try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) {
- assertThat(foundUsersStream.count()).isEqualTo(3l);
- }
- }
-
@Test
public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException {
User user = new User();
diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml
index cc723534f8..b378d0070c 100644
--- a/spring-cloud/pom.xml
+++ b/spring-cloud/pom.xml
@@ -31,6 +31,7 @@
spring-cloud-zuul-eureka-integration
spring-cloud-contract
spring-cloud-kubernetes
+ spring-cloud-archaius
spring-cloud-vault
diff --git a/spring-cloud/spring-cloud-archaius/README.md b/spring-cloud/spring-cloud-archaius/README.md
new file mode 100644
index 0000000000..9de26352e1
--- /dev/null
+++ b/spring-cloud/spring-cloud-archaius/README.md
@@ -0,0 +1,14 @@
+# Spring Cloud Archaius
+
+#### Basic Config
+This service has the basic, out-of-the-box Spring Cloud Netflix Archaius configuration.
+
+#### Extra Configs
+This service customizes some properties supported by Archaius.
+
+These properties are set up on the main method, since Archaius uses System properties, but they could be added as command line arguments when launching the app.
+
+#### Additional Sources
+In this service we create a new AbstractConfiguration bean, setting up a new Configuration Properties source.
+
+These properties have precedence over all the other properties in the Archaius Composite Configuration.
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml b/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml
new file mode 100644
index 0000000000..1ae6d543fb
--- /dev/null
+++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml
@@ -0,0 +1,24 @@
+
+
+ 4.0.0
+ additional-sources-simple
+ 1.0.0-SNAPSHOT
+ jar
+ additional-sources-simple
+
+
+ com.baeldung.spring.cloud
+ spring-cloud-archaius
+ 1.0.0-SNAPSHOT
+ ..
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java
new file mode 100644
index 0000000000..e1a1d106cf
--- /dev/null
+++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.spring.cloud.archaius.additionalsources;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class AdditionalSourcesSimpleApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(AdditionalSourcesSimpleApplication.class, args);
+ }
+
+}
diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java
new file mode 100644
index 0000000000..f2d8ca2638
--- /dev/null
+++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java
@@ -0,0 +1,21 @@
+package com.baeldung.spring.cloud.archaius.additionalsources.config;
+
+import org.apache.commons.configuration.AbstractConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import com.netflix.config.DynamicConfiguration;
+import com.netflix.config.FixedDelayPollingScheduler;
+import com.netflix.config.PolledConfigurationSource;
+import com.netflix.config.sources.URLConfigurationSource;
+
+@Configuration
+public class ApplicationPropertiesConfigurations {
+
+ @Bean
+ public AbstractConfiguration addApplicationPropertiesSource() {
+ PolledConfigurationSource source = new URLConfigurationSource("classpath:other-config.properties");
+ return new DynamicConfiguration(source, new FixedDelayPollingScheduler());
+ }
+
+}
diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java
new file mode 100644
index 0000000000..304369a036
--- /dev/null
+++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java
@@ -0,0 +1,37 @@
+package com.baeldung.spring.cloud.archaius.additionalsources.controller;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.netflix.config.DynamicPropertyFactory;
+import com.netflix.config.DynamicStringProperty;
+
+@RestController
+public class ConfigPropertiesController {
+
+ private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance()
+ .getStringProperty("baeldung.archaius.properties.one", "not found!");
+
+ private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance()
+ .getStringProperty("baeldung.archaius.properties.two", "not found!");
+
+ private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance()
+ .getStringProperty("baeldung.archaius.properties.three", "not found!");
+
+ private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance()
+ .getStringProperty("baeldung.archaius.properties.four", "not found!");
+
+ @GetMapping("/properties-from-dynamic")
+ public Map getPropertiesFromDynamic() {
+ Map properties = new HashMap<>();
+ properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get());
+ properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get());
+ properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get());
+ properties.put(propertyFourWithDynamic.getName(), propertyFourWithDynamic.get());
+ return properties;
+ }
+}
diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties
new file mode 100644
index 0000000000..bf55e89a27
--- /dev/null
+++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties
@@ -0,0 +1,3 @@
+server.port=8082
+baeldung.archaius.properties.one=one FROM:application.properties
+baeldung.archaius.properties.two=two FROM:application.properties
diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties
new file mode 100644
index 0000000000..b104c0c488
--- /dev/null
+++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties
@@ -0,0 +1,2 @@
+baeldung.archaius.properties.one=one FROM:config.properties
+baeldung.archaius.properties.three=three FROM:config.properties
diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties
new file mode 100644
index 0000000000..00fe8ff2aa
--- /dev/null
+++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties
@@ -0,0 +1,2 @@
+baeldung.archaius.properties.one=one FROM:other-config.properties
+baeldung.archaius.properties.four=four FROM:other-config.properties
diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java
new file mode 100644
index 0000000000..f3a345d869
--- /dev/null
+++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java
@@ -0,0 +1,54 @@
+package com.baeldung.spring.cloud.archaius.additionalsources;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.core.ParameterizedTypeReference;
+import org.springframework.http.HttpMethod;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+public class ArchaiusAdditionalSourcesLiveTest {
+
+ private static final String BASE_URL = "http://localhost:8082";
+
+ private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic";
+ private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties();
+
+ private static Map createExpectedArchaiusProperties() {
+ Map map = new HashMap<>();
+ map.put("baeldung.archaius.properties.one", "one FROM:other-config.properties");
+ map.put("baeldung.archaius.properties.two", "two FROM:application.properties");
+ map.put("baeldung.archaius.properties.three", "three FROM:config.properties");
+ map.put("baeldung.archaius.properties.four", "four FROM:other-config.properties");
+ return map;
+ }
+
+ @Autowired
+ ConfigurableApplicationContext context;
+
+ @Autowired
+ private TestRestTemplate template;
+
+ private Map exchangeAsMap(String uri, ParameterizedTypeReference
-
@@ -59,27 +57,8 @@
-
-
-
- maven-surefire-plugin
-
-
- **/*IntegrationTest.java
- **/*IntTest.java
-
-
-
-
-
-
-
com.baeldung.spring.cloud.aws.SpringCloudAwsApplication
- UTF-8
- UTF-8
- 1.8
Dalston.SR4
-
diff --git a/spring-cloud/spring-cloud-connectors-heroku/pom.xml b/spring-cloud/spring-cloud-connectors-heroku/pom.xml
index f25c190d56..f00c9eb1fc 100644
--- a/spring-cloud/spring-cloud-connectors-heroku/pom.xml
+++ b/spring-cloud/spring-cloud-connectors-heroku/pom.xml
@@ -33,8 +33,7 @@
org.postgresql
postgresql
- ${postgresql.version}
-
+
com.h2database
h2
@@ -54,33 +53,8 @@
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
- 3
- true
-
- **/*IntegrationTest.java
- **/*IntTest.java
- **/*LongRunningUnitTest.java
- **/*ManualTest.java
- **/JdbcTest.java
- **/*LiveTest.java
-
- true
-
-
-
-
-
Brixton.SR7
- 2.21.0
9.4-1201-jdbc4
-
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-vault/database-setup.sql b/spring-cloud/spring-cloud-vault/database-setup.sql
new file mode 100644
index 0000000000..4bb1293f74
--- /dev/null
+++ b/spring-cloud/spring-cloud-vault/database-setup.sql
@@ -0,0 +1,20 @@
+--
+-- Sample schema for testing vault database secrets
+--
+create schema fakebank;
+use fakebank;
+create table account(
+ id decimal(16,0),
+ name varchar(30),
+ branch_id decimal(16,0),
+ customer_id decimal(16,0),
+ primary key (id));
+
+--
+-- MySQL user that will be used by Vault to create other users on demand
+--
+create user 'fakebank-admin'@'%' identified by 'Sup&rSecre7!'
+grant all privileges on fakebank.* to 'fakebank-admin'@'%' with grant option;
+grant create user on *.* to 'fakebank-admin' with grant option;
+
+flush privileges;
diff --git a/spring-cloud/spring-cloud-vault/pom.xml b/spring-cloud/spring-cloud-vault/pom.xml
index 29141534c3..afda1661c5 100644
--- a/spring-cloud/spring-cloud-vault/pom.xml
+++ b/spring-cloud/spring-cloud-vault/pom.xml
@@ -60,7 +60,7 @@
org.springframework.cloud
- spring-cloud-vault-config-databases
+
diff --git a/spring-cloud/spring-cloud-vault/sample-policy.hcl b/spring-cloud/spring-cloud-vault/sample-policy.hcl
new file mode 100644
index 0000000000..554888661e
--- /dev/null
+++ b/spring-cloud/spring-cloud-vault/sample-policy.hcl
@@ -0,0 +1,6 @@
+path "secret/fakebank" {
+ capabilities = ["read"]
+ allowed_parameters = {
+ "api_key" = []
+ }
+}
diff --git a/spring-cloud/spring-cloud-vault/vault-env.bat b/spring-cloud/spring-cloud-vault/vault-env.bat
index f1831a547f..d7aa5da215 100644
--- a/spring-cloud/spring-cloud-vault/vault-env.bat
+++ b/spring-cloud/spring-cloud-vault/vault-env.bat
@@ -2,4 +2,4 @@
echo Setting environment variables to access local vault..
set VAULT_ADDR=https://localhost:8200
set VAULT_CACERT=%~dp0%/src/test/vault-config/localhost.cert
-set VAULT_TLS_SERVER_NAME=localhost
+rem set VAULT_TLS_SERVER_NAME=localhost
diff --git a/spring-cloud/spring-cloud-vault/vault-env.sh b/spring-cloud/spring-cloud-vault/vault-env.sh
index 8814860410..06077cee2e 100644
--- a/spring-cloud/spring-cloud-vault/vault-env.sh
+++ b/spring-cloud/spring-cloud-vault/vault-env.sh
@@ -1,6 +1,6 @@
#!/bin/bash
echo Setting environment variables to access local vault..
-SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
+SCRIPTPATH=$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )
export VAULT_ADDR=https://localhost:8200
export VAULT_CACERT=$SCRIPTPATH/src/test/vault-config/localhost.cert
export VAULT_TLS_SERVER_NAME=localhost
diff --git a/spring-core/pom.xml b/spring-core/pom.xml
index 9e885462f3..60f3262f08 100644
--- a/spring-core/pom.xml
+++ b/spring-core/pom.xml
@@ -16,11 +16,6 @@
-
- org.mockito
- mockito-all
- ${mockito.version}
-
org.springframework
spring-test
@@ -82,15 +77,7 @@
-
-
- java.net
- https://maven.java.net/content/repositories/releases/
-
-
-
- 1.10.19
1.4.4.RELEASE
1
20.0
diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/app/CustomConfiguration.java b/spring-core/src/main/java/com/baeldung/dependency/exception/app/CustomConfiguration.java
new file mode 100644
index 0000000000..4366cb617a
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/dependency/exception/app/CustomConfiguration.java
@@ -0,0 +1,13 @@
+package com.baeldung.dependency.exception.app;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.ComponentScan;
+
+@SpringBootApplication
+@ComponentScan(basePackages = "com.baeldung.dependency.exception")
+public class CustomConfiguration {
+ public static void main(String[] args) {
+ SpringApplication.run(CustomConfiguration.class, args);
+ }
+}
diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java b/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java
new file mode 100644
index 0000000000..1e6fad63aa
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java
@@ -0,0 +1,13 @@
+package com.baeldung.dependency.exception.app;
+
+import com.baeldung.dependency.exception.repository.InventoryRepository;
+import org.springframework.stereotype.Service;
+
+@Service
+public class PurchaseDeptService {
+ private InventoryRepository repository;
+
+ public PurchaseDeptService(InventoryRepository repository) {
+ this.repository = repository;
+ }
+}
\ No newline at end of file
diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java
new file mode 100644
index 0000000000..4a6c836143
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java
@@ -0,0 +1,9 @@
+package com.baeldung.dependency.exception.repository;
+
+import org.springframework.context.annotation.Primary;
+import org.springframework.stereotype.Repository;
+
+@Primary
+@Repository
+public class DressRepository implements InventoryRepository {
+}
diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/InventoryRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/InventoryRepository.java
new file mode 100644
index 0000000000..ccb2ad9c32
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/InventoryRepository.java
@@ -0,0 +1,7 @@
+package com.baeldung.dependency.exception.repository;
+
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface InventoryRepository {
+}
diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java
new file mode 100644
index 0000000000..60495914cd
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java
@@ -0,0 +1,7 @@
+package com.baeldung.dependency.exception.repository;
+
+import org.springframework.stereotype.Repository;
+
+@Repository
+public class ShoeRepository implements InventoryRepository {
+}
diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/annotation/CarQualifier.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/annotation/CarQualifier.java
new file mode 100644
index 0000000000..cd7f81c0fb
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/annotation/CarQualifier.java
@@ -0,0 +1,15 @@
+package com.baeldung.dependencyinjectiontypes.annotation;
+
+import org.springframework.beans.factory.annotation.Qualifier;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ElementType.FIELD, ElementType.METHOD,
+ ElementType.TYPE, ElementType.PARAMETER})
+@Retention(RetentionPolicy.RUNTIME)
+@Qualifier
+public @interface CarQualifier {
+}
diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/app/CustomConfiguration.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/app/CustomConfiguration.java
new file mode 100644
index 0000000000..841a8d4656
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/app/CustomConfiguration.java
@@ -0,0 +1,39 @@
+package com.baeldung.dependencyinjectiontypes.app;
+
+import com.baeldung.dependencyinjectiontypes.annotation.CarQualifier;
+import com.baeldung.dependencyinjectiontypes.model.Car;
+import com.baeldung.dependencyinjectiontypes.model.CarHandler;
+import com.baeldung.dependencyinjectiontypes.model.Motorcycle;
+import com.baeldung.dependencyinjectiontypes.model.Vehicle;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+
+@SpringBootApplication
+@ComponentScan("com.baeldung.dependencyinjectiontypes.model")
+public class CustomConfiguration {
+ @Bean
+ @CarQualifier
+ public Car getMercedes() {
+ return new Car("E280", "Mercedes", "Diesel");
+ }
+
+ public static void main(String[] args) throws NoSuchFieldException {
+ ConfigurableApplicationContext context = SpringApplication.run(CustomConfiguration.class, args);
+ CarHandler carHandler = context.getBean(CarHandler.class);
+ carHandler.getVehicles().forEach(System.out::println);
+ }
+
+ @Bean
+ @CarQualifier
+ public Car getBmw() {
+ return new Car("M5", "BMW", "Petrol");
+ }
+
+ @Bean
+ public Motorcycle getSuzuki() {
+ return new Motorcycle("Yamaguchi", "Suzuki", true);
+ }
+}
diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Car.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Car.java
new file mode 100644
index 0000000000..a09d89248b
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Car.java
@@ -0,0 +1,25 @@
+package com.baeldung.dependencyinjectiontypes.model;
+
+public class Car extends Vehicle {
+ private String engineType;
+
+ public Car(String name, String manufacturer, String engineType) {
+ super(name, manufacturer);
+ this.engineType = engineType;
+ }
+
+ public String getEngineType() {
+ return engineType;
+ }
+
+ public void setEngineType(String engineType) {
+ this.engineType = engineType;
+ }
+
+ @Override
+ public String toString() {
+ return "Car{" +
+ "engineType='" + engineType + '\'' +
+ '}';
+ }
+}
diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/CarHandler.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/CarHandler.java
new file mode 100644
index 0000000000..f5d581ef0a
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/CarHandler.java
@@ -0,0 +1,26 @@
+package com.baeldung.dependencyinjectiontypes.model;
+
+import com.baeldung.dependencyinjectiontypes.annotation.CarQualifier;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.ResolvableType;
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+
+@Component
+public class CarHandler {
+
+ @Autowired
+ @CarQualifier
+ private List vehicles;
+
+ public List getVehicles() throws NoSuchFieldException {
+ ResolvableType vehiclesType = ResolvableType.forField(getClass().getDeclaredField("vehicles"));
+ System.out.println(vehiclesType);
+ ResolvableType type = vehiclesType.getGeneric();
+ System.out.println(type);
+ Class> aClass = type.resolve();
+ System.out.println(aClass);
+ return this.vehicles;
+ }
+}
diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Motorcycle.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Motorcycle.java
new file mode 100644
index 0000000000..ce5e97fb6d
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Motorcycle.java
@@ -0,0 +1,25 @@
+package com.baeldung.dependencyinjectiontypes.model;
+
+public class Motorcycle extends Vehicle {
+ private boolean twoWheeler;
+
+ public Motorcycle(String name, String manufacturer, boolean twoWheeler) {
+ super(name, manufacturer);
+ this.twoWheeler = true;
+ }
+
+ public boolean isTwoWheeler() {
+ return twoWheeler;
+ }
+
+ public void setTwoWheeler(boolean twoWheeler) {
+ this.twoWheeler = twoWheeler;
+ }
+
+ @Override
+ public String toString() {
+ return "Motorcycle{" +
+ "twoWheeler=" + twoWheeler +
+ '}';
+ }
+}
diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Vehicle.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Vehicle.java
new file mode 100644
index 0000000000..cb3dca764e
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Vehicle.java
@@ -0,0 +1,28 @@
+package com.baeldung.dependencyinjectiontypes.model;
+
+public abstract class Vehicle {
+ private String name;
+ private String manufacturer;
+
+
+ public Vehicle(String name, String manufacturer) {
+ this.name = name;
+ this.manufacturer = manufacturer;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getManufacturer() {
+ return manufacturer;
+ }
+
+ public void setManufacturer(String manufacturer) {
+ this.manufacturer = manufacturer;
+ }
+}
\ No newline at end of file
diff --git a/spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java b/spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java
new file mode 100644
index 0000000000..a2603bb95c
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java
@@ -0,0 +1,24 @@
+package com.baeldung.event.listener;
+
+import org.springframework.context.event.ContextStartedEvent;
+import org.springframework.context.event.ContextStoppedEvent;
+import org.springframework.context.event.EventListener;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Component;
+
+@Component
+public class ContextEventListener {
+
+ @Order(2)
+ @EventListener
+ public void handleContextRefreshEvent(ContextStartedEvent ctxStartEvt) {
+ System.out.println("Context Start Event received.");
+ }
+
+ @Order(1)
+ @EventListener(classes = { ContextStartedEvent.class, ContextStoppedEvent.class })
+ public void handleMultipleEvents() {
+ System.out.println("Multi-event listener invoked");
+ }
+
+}
diff --git a/spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java b/spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java
new file mode 100644
index 0000000000..f2a3af7640
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java
@@ -0,0 +1,10 @@
+package com.baeldung.event.listener;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan(basePackages = "com.baeldung.event.listener")
+public class EventConfig {
+
+}
diff --git a/spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java b/spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java
new file mode 100644
index 0000000000..bbe4693900
--- /dev/null
+++ b/spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java
@@ -0,0 +1,12 @@
+package com.baeldung.event.listener;
+
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+
+public class SpringRunner {
+
+ public static void main(String[] args) {
+ ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(EventConfig.class);
+ ctx.start();
+ }
+}
diff --git a/spring-custom-aop/src/main/resources/logback.xml b/spring-custom-aop/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/spring-custom-aop/src/main/resources/logback.xml
+++ b/spring-custom-aop/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/spring-data-couchbase-2/src/main/resources/logback.xml b/spring-data-couchbase-2/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/spring-data-couchbase-2/src/main/resources/logback.xml
+++ b/spring-data-couchbase-2/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/spring-data-couchbase-2/src/test/resources/logback.xml b/spring-data-couchbase-2/src/test/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/spring-data-couchbase-2/src/test/resources/logback.xml
+++ b/spring-data-couchbase-2/src/test/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/spring-data-jpa/README.md b/spring-data-jpa/README.md
new file mode 100644
index 0000000000..f54764e05c
--- /dev/null
+++ b/spring-data-jpa/README.md
@@ -0,0 +1,22 @@
+=========
+
+## Spring Data JPA Example Project
+
+### Relevant Articles:
+- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases)
+- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories)
+- [Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
+- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
+- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
+- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8)
+- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging)
+
+### Eclipse Config
+After importing the project into Eclipse, you may see the following error:
+"No persistence xml file found in project"
+
+This can be ignored:
+- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
+Or:
+- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator
+
diff --git a/spring-data-jpa/pom.xml b/spring-data-jpa/pom.xml
index 517d43bd0e..c4893df759 100644
--- a/spring-data-jpa/pom.xml
+++ b/spring-data-jpa/pom.xml
@@ -17,10 +17,30 @@
org.springframework.boot
spring-boot-starter-data-jpa
+
+ org.hibernate
+ hibernate-ehcache
+
+
+ org.hibernate
+ hibernate-envers
+
com.h2database
h2
+
+
+ org.springframework.security
+ spring-security-test
+ test
+
+
+
+ com.google.guava
+ guava
+ 21.0
+
\ No newline at end of file
diff --git a/spring-data-jpa/src/main/java/com/baeldung/Application.java b/spring-data-jpa/src/main/java/com/baeldung/Application.java
index 43888c2d67..4e14f94311 100644
--- a/spring-data-jpa/src/main/java/com/baeldung/Application.java
+++ b/spring-data-jpa/src/main/java/com/baeldung/Application.java
@@ -1,14 +1,17 @@
package com.baeldung;
+import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.context.ApplicationContext;
+import org.springframework.boot.autoconfigure.domain.EntityScan;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
+@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class)
public class Application {
- private static ApplicationContext applicationContext;
public static void main(String[] args) {
- applicationContext = SpringApplication.run(Application.class, args);
+ SpringApplication.run(Application.class, args);
}
+
}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java
new file mode 100644
index 0000000000..16407e510a
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java
@@ -0,0 +1,102 @@
+package com.baeldung.config;
+
+import com.baeldung.services.IBarService;
+import com.baeldung.services.impl.BarSpringDataJpaService;
+import com.google.common.base.Preconditions;
+import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl;
+import com.baeldung.services.IFooService;
+import com.baeldung.services.impl.FooService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.*;
+import org.springframework.core.env.Environment;
+import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.orm.jpa.JpaTransactionManager;
+import org.springframework.orm.jpa.JpaVendorAdapter;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import javax.sql.DataSource;
+import java.util.Properties;
+
+@Configuration
+@ComponentScan({"com.baeldung.dao", "com.baeldung.services"})
+@EnableTransactionManagement
+@EnableJpaRepositories(basePackages = {"com.baeldung.dao"}, repositoryBaseClass = ExtendedRepositoryImpl.class)
+@EnableJpaAuditing
+@PropertySource("classpath:persistence.properties")
+public class PersistenceConfiguration {
+
+ @Autowired
+ private Environment env;
+
+ public PersistenceConfiguration() {
+ super();
+ }
+
+ @Bean
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
+ final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
+ emf.setDataSource(dataSource());
+ emf.setPackagesToScan("com.baeldung.domain");
+
+ final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
+ emf.setJpaVendorAdapter(vendorAdapter);
+ emf.setJpaProperties(hibernateProperties());
+
+ return emf;
+ }
+
+ @Bean
+ public DataSource dataSource() {
+ final DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
+ dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
+ dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
+ dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
+
+ return dataSource;
+ }
+
+ @Bean
+ public PlatformTransactionManager transactionManager() {
+ final JpaTransactionManager transactionManager = new JpaTransactionManager();
+ transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
+ return transactionManager;
+ }
+
+ @Bean
+ public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
+ return new PersistenceExceptionTranslationPostProcessor();
+ }
+
+ @Bean
+ public IBarService barSpringDataJpaService() {
+ return new BarSpringDataJpaService();
+ }
+
+ @Bean
+ public IFooService fooService() {
+ return new FooService();
+ }
+
+ private final Properties hibernateProperties() {
+ final Properties hibernateProperties = new Properties();
+ hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
+ hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
+
+ hibernateProperties.setProperty("hibernate.show_sql", "true");
+ // hibernateProperties.setProperty("hibernate.format_sql", "true");
+ // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
+
+ // Envers properties
+ hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
+
+ return hibernateProperties;
+ }
+
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java
similarity index 84%
rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java
rename to spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java
index 13f8f4b27c..207fba9bc5 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java
+++ b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java
@@ -1,9 +1,6 @@
-package org.baeldung.config;
-
-import java.util.HashMap;
-
-import javax.sql.DataSource;
+package com.baeldung.config;
+import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -16,16 +13,17 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
-import com.google.common.base.Preconditions;
+import javax.sql.DataSource;
+import java.util.HashMap;
@Configuration
-@PropertySource({ "classpath:persistence-multiple-db.properties" })
-@EnableJpaRepositories(basePackages = "org.baeldung.persistence.multiple.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager")
-public class ProductConfig {
+@PropertySource({"classpath:persistence-multiple-db.properties"})
+@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager")
+public class PersistenceProductConfiguration {
@Autowired
private Environment env;
- public ProductConfig() {
+ public PersistenceProductConfiguration() {
super();
}
@@ -35,7 +33,7 @@ public class ProductConfig {
public LocalContainerEntityManagerFactoryBean productEntityManager() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(productDataSource());
- em.setPackagesToScan(new String[] { "org.baeldung.persistence.multiple.model.product" });
+ em.setPackagesToScan("com.baeldung.domain.product");
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java
similarity index 85%
rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java
rename to spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java
index 8e85f5d8e0..dd32477755 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java
+++ b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java
@@ -1,9 +1,6 @@
-package org.baeldung.config;
-
-import java.util.HashMap;
-
-import javax.sql.DataSource;
+package com.baeldung.config;
+import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -17,16 +14,17 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
-import com.google.common.base.Preconditions;
+import javax.sql.DataSource;
+import java.util.HashMap;
@Configuration
-@PropertySource({ "classpath:persistence-multiple-db.properties" })
-@EnableJpaRepositories(basePackages = "org.baeldung.persistence.multiple.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager")
-public class UserConfig {
+@PropertySource({"classpath:persistence-multiple-db.properties"})
+@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager")
+public class PersistenceUserConfiguration {
@Autowired
private Environment env;
- public UserConfig() {
+ public PersistenceUserConfiguration() {
super();
}
@@ -37,7 +35,7 @@ public class UserConfig {
public LocalContainerEntityManagerFactoryBean userEntityManager() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(userDataSource());
- em.setPackagesToScan(new String[] { "org.baeldung.persistence.multiple.model.user" });
+ em.setPackagesToScan("com.baeldung.domain.user");
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/IFooDao.java b/spring-data-jpa/src/main/java/com/baeldung/dao/IFooDao.java
new file mode 100644
index 0000000000..bb3c229945
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/IFooDao.java
@@ -0,0 +1,12 @@
+package com.baeldung.dao;
+
+import com.baeldung.domain.Foo;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+
+public interface IFooDao extends JpaRepository {
+
+ @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
+ Foo retrieveByName(@Param("name") String name);
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/repository/ArticleRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ArticleRepository.java
similarity index 95%
rename from spring-data-jpa/src/main/java/com/baeldung/repository/ArticleRepository.java
rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ArticleRepository.java
index 4e1b109430..8402c099d9 100644
--- a/spring-data-jpa/src/main/java/com/baeldung/repository/ArticleRepository.java
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ArticleRepository.java
@@ -1,4 +1,4 @@
-package com.baeldung.repository;
+package com.baeldung.dao.repositories;
import com.baeldung.domain.Article;
import org.springframework.data.jpa.repository.JpaRepository;
diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java
new file mode 100644
index 0000000000..ba077ccf1f
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java
@@ -0,0 +1,15 @@
+package com.baeldung.dao.repositories;
+
+import org.springframework.stereotype.Repository;
+
+import com.baeldung.domain.Item;
+
+@Repository
+public interface CustomItemRepository {
+
+ void deleteCustom(Item entity);
+
+ Item findItemById(Long id);
+
+ void findThenDelete(Long id);
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemTypeRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemTypeRepository.java
new file mode 100644
index 0000000000..81ebdf3fda
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemTypeRepository.java
@@ -0,0 +1,13 @@
+package com.baeldung.dao.repositories;
+
+import org.springframework.stereotype.Repository;
+
+import com.baeldung.domain.ItemType;
+
+@Repository
+public interface CustomItemTypeRepository {
+
+ void deleteCustom(ItemType entity);
+
+ void findThenDelete(Long id);
+}
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedRepository.java
similarity index 69%
rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java
rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedRepository.java
index 9c9c12029a..9e82f02fa6 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedRepository.java
@@ -1,4 +1,4 @@
-package org.baeldung.extended.persistence.dao;
+package com.baeldung.dao.repositories;
import java.io.Serializable;
import java.util.List;
@@ -8,5 +8,7 @@ import org.springframework.data.repository.NoRepositoryBean;
@NoRepositoryBean
public interface ExtendedRepository extends JpaRepository {
- public List findByAttributeContainsText(String attributeName, String text);
+
+ List findByAttributeContainsText(String attributeName, String text);
+
}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedStudentRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedStudentRepository.java
new file mode 100644
index 0000000000..199e4e5ff6
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedStudentRepository.java
@@ -0,0 +1,6 @@
+package com.baeldung.dao.repositories;
+
+import com.baeldung.domain.Student;
+
+public interface ExtendedStudentRepository extends ExtendedRepository {
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/IBarCrudRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/IBarCrudRepository.java
new file mode 100644
index 0000000000..54a7d77691
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/IBarCrudRepository.java
@@ -0,0 +1,10 @@
+package com.baeldung.dao.repositories;
+
+import com.baeldung.domain.Bar;
+import org.springframework.data.repository.CrudRepository;
+
+import java.io.Serializable;
+
+public interface IBarCrudRepository extends CrudRepository {
+ //
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ItemTypeRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ItemTypeRepository.java
new file mode 100644
index 0000000000..2af83bc322
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ItemTypeRepository.java
@@ -0,0 +1,10 @@
+package com.baeldung.dao.repositories;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+import com.baeldung.domain.ItemType;
+
+@Repository
+public interface ItemTypeRepository extends JpaRepository, CustomItemTypeRepository, CustomItemRepository {
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/LocationRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/LocationRepository.java
new file mode 100644
index 0000000000..27bbe27af0
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/LocationRepository.java
@@ -0,0 +1,10 @@
+package com.baeldung.dao.repositories;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+import com.baeldung.domain.Location;
+
+@Repository
+public interface LocationRepository extends JpaRepository {
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ReadOnlyLocationRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ReadOnlyLocationRepository.java
new file mode 100644
index 0000000000..8f68cdbbe5
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ReadOnlyLocationRepository.java
@@ -0,0 +1,15 @@
+package com.baeldung.dao.repositories;
+
+import java.util.Optional;
+
+import org.springframework.data.repository.Repository;
+
+import com.baeldung.domain.Location;
+
+@org.springframework.stereotype.Repository
+public interface ReadOnlyLocationRepository extends Repository {
+
+ Optional findById(Long id);
+
+ Location save(Location location);
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/StoreRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/StoreRepository.java
new file mode 100644
index 0000000000..9318c32ee9
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/StoreRepository.java
@@ -0,0 +1,13 @@
+package com.baeldung.dao.repositories;
+
+import java.util.List;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+import com.baeldung.domain.Store;
+
+@Repository
+public interface StoreRepository extends JpaRepository {
+ List findStoreByLocationId(Long locationId);
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java
new file mode 100644
index 0000000000..53def88af0
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java
@@ -0,0 +1,32 @@
+package com.baeldung.dao.repositories.impl;
+
+import javax.persistence.EntityManager;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+import com.baeldung.domain.Item;
+import com.baeldung.dao.repositories.CustomItemRepository;
+
+@Repository
+public class CustomItemRepositoryImpl implements CustomItemRepository {
+
+ @Autowired
+ private EntityManager entityManager;
+
+ @Override
+ public void deleteCustom(Item item) {
+ entityManager.remove(item);
+ }
+
+ @Override
+ public Item findItemById(Long id) {
+ return entityManager.find(Item.class, id);
+ }
+
+ @Override
+ public void findThenDelete(Long id) {
+ final Item item = entityManager.find(Item.class, id);
+ entityManager.remove(item);
+ }
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemTypeRepositoryImpl.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemTypeRepositoryImpl.java
new file mode 100644
index 0000000000..2b49f2380c
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemTypeRepositoryImpl.java
@@ -0,0 +1,31 @@
+package com.baeldung.dao.repositories.impl;
+
+import javax.persistence.EntityManager;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+import com.baeldung.domain.ItemType;
+import com.baeldung.dao.repositories.CustomItemTypeRepository;
+
+@Repository
+public class CustomItemTypeRepositoryImpl implements CustomItemTypeRepository {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(CustomItemTypeRepositoryImpl.class);
+
+ @Autowired
+ private EntityManager entityManager;
+
+ @Override
+ public void deleteCustom(ItemType itemType) {
+ entityManager.remove(itemType);
+ }
+
+ @Override
+ public void findThenDelete(Long id) {
+ ItemType itemTypeToDelete = entityManager.find(ItemType.class, id);
+ entityManager.remove(itemTypeToDelete);
+ }
+}
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/ExtendedRepositoryImpl.java
similarity index 93%
rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java
rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/ExtendedRepositoryImpl.java
index 7ed652dc4d..f6f06efb51 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/ExtendedRepositoryImpl.java
@@ -1,4 +1,4 @@
-package org.baeldung.extended.persistence.dao;
+package com.baeldung.dao.repositories.impl;
import java.io.Serializable;
import java.util.List;
@@ -10,6 +10,7 @@ import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
+import com.baeldung.dao.repositories.ExtendedRepository;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java
similarity index 54%
rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java
rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java
index bad0170a3a..7044d57e53 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java
@@ -1,6 +1,6 @@
-package org.baeldung.persistence.multiple.dao.product;
+package com.baeldung.dao.repositories.product;
-import org.baeldung.persistence.multiple.model.product.Product;
+import com.baeldung.domain.product.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository {
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/PossessionRepository.java
similarity index 55%
rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java
rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/PossessionRepository.java
index 34913632d8..f0eeb475c1 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/PossessionRepository.java
@@ -1,6 +1,6 @@
-package org.baeldung.persistence.multiple.dao.user;
+package com.baeldung.dao.repositories.user;
-import org.baeldung.persistence.multiple.model.user.Possession;
+import com.baeldung.domain.user.Possession;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PossessionRepository extends JpaRepository {
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/repository/UserRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java
similarity index 74%
rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/repository/UserRepository.java
rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java
index eadac9a0d7..5bb0232e4a 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/repository/UserRepository.java
+++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java
@@ -1,6 +1,6 @@
-package org.baeldung.persistence.repository;
+package com.baeldung.dao.repositories.user;
-import org.baeldung.persistence.model.User;
+import com.baeldung.domain.user.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@@ -8,24 +8,25 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
-import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.List;
+import java.util.stream.Stream;
-@Repository("userRepository")
public interface UserRepository extends JpaRepository {
+ Stream findAllByName(String name);
+
@Query("SELECT u FROM User u WHERE u.status = 1")
Collection findAllActiveUsers();
- @Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true)
+ @Query(value = "SELECT * FROM USERS.USERS u WHERE u.status = 1", nativeQuery = true)
Collection findAllActiveUsersNative();
@Query("SELECT u FROM User u WHERE u.status = ?1")
User findUserByStatus(Integer status);
- @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true)
+ @Query(value = "SELECT * FROM USERS.Users u WHERE u.status = ?1", nativeQuery = true)
User findUserByStatusNative(Integer status);
@Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
@@ -34,7 +35,7 @@ public interface UserRepository extends JpaRepository {
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name);
- @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
+ @Query(value = "SELECT * FROM USERS.Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name);
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
@@ -46,7 +47,7 @@ public interface UserRepository extends JpaRepository {
@Query("SELECT u FROM User u WHERE u.name like :name%")
User findUserByNameLikeNamedParam(@Param("name") String name);
- @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true)
+ @Query(value = "SELECT * FROM USERS.users u WHERE u.name LIKE ?1%", nativeQuery = true)
User findUserByNameLikeNative(String name);
@Query(value = "SELECT u FROM User u")
@@ -55,7 +56,7 @@ public interface UserRepository extends JpaRepository {
@Query(value = "SELECT u FROM User u ORDER BY id")
Page findAllUsersWithPagination(Pageable pageable);
- @Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
+ @Query(value = "SELECT * FROM USERS.Users ORDER BY id", countQuery = "SELECT count(*) FROM USERS.Users", nativeQuery = true)
Page findAllUsersWithPaginationNative(Pageable pageable);
@Modifying
@@ -63,7 +64,6 @@ public interface UserRepository extends JpaRepository {
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
@Modifying
- @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
+ @Query(value = "UPDATE USERS.Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNative(Integer status, String name);
-
}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Bar.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Bar.java
new file mode 100644
index 0000000000..efd297bafc
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Bar.java
@@ -0,0 +1,220 @@
+package com.baeldung.domain;
+
+import com.google.common.collect.Sets;
+import org.hibernate.annotations.OrderBy;
+import org.hibernate.envers.Audited;
+import org.jboss.logging.Logger;
+import org.springframework.data.annotation.CreatedBy;
+import org.springframework.data.annotation.CreatedDate;
+import org.springframework.data.annotation.LastModifiedBy;
+import org.springframework.data.annotation.LastModifiedDate;
+import org.springframework.data.jpa.domain.support.AuditingEntityListener;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.util.Date;
+import java.util.Set;
+
+@Entity
+@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b")
+@Audited
+@EntityListeners(AuditingEntityListener.class)
+public class Bar implements Serializable {
+
+ private static Logger logger = Logger.getLogger(Bar.class);
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @Column(name = "id")
+ private int id;
+
+ @Column(name = "name")
+ private String name;
+ @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @OrderBy(clause = "NAME DESC")
+ // @NotAudited
+ private Set fooSet = Sets.newHashSet();
+ @Column(name = "operation")
+ private String operation;
+ @Column(name = "timestamp")
+ private long timestamp;
+ @Column(name = "created_date", updatable = false, nullable = false)
+ @CreatedDate
+ private long createdDate;
+ @Column(name = "modified_date")
+ @LastModifiedDate
+ private long modifiedDate;
+ @Column(name = "created_by")
+ @CreatedBy
+ private String createdBy;
+ @Column(name = "modified_by")
+ @LastModifiedBy
+ private String modifiedBy;
+
+ public Bar() {
+ super();
+ }
+
+ public Bar(final String name) {
+ super();
+
+ this.name = name;
+ }
+
+ public Set getFooSet() {
+ return fooSet;
+ }
+
+ // API
+
+ public void setFooSet(final Set fooSet) {
+ this.fooSet = fooSet;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(final int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public OPERATION getOperation() {
+ return OPERATION.parse(operation);
+ }
+
+ public void setOperation(final String operation) {
+ this.operation = operation;
+ }
+
+ public void setOperation(final OPERATION operation) {
+ this.operation = operation.getValue();
+ }
+
+ public long getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(final long timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public long getCreatedDate() {
+ return createdDate;
+ }
+
+ public void setCreatedDate(final long createdDate) {
+ this.createdDate = createdDate;
+ }
+
+ public long getModifiedDate() {
+ return modifiedDate;
+ }
+
+ public void setModifiedDate(final long modifiedDate) {
+ this.modifiedDate = modifiedDate;
+ }
+
+ public String getCreatedBy() {
+ return createdBy;
+ }
+
+ public void setCreatedBy(final String createdBy) {
+ this.createdBy = createdBy;
+ }
+
+ public String getModifiedBy() {
+ return modifiedBy;
+ }
+
+ public void setModifiedBy(final String modifiedBy) {
+ this.modifiedBy = modifiedBy;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ final Bar other = (Bar) obj;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("Bar [name=").append(name).append("]");
+ return builder.toString();
+ }
+
+ @PrePersist
+ public void onPrePersist() {
+ logger.info("@PrePersist");
+ audit(OPERATION.INSERT);
+ }
+
+ @PreUpdate
+ public void onPreUpdate() {
+ logger.info("@PreUpdate");
+ audit(OPERATION.UPDATE);
+ }
+
+ @PreRemove
+ public void onPreRemove() {
+ logger.info("@PreRemove");
+ audit(OPERATION.DELETE);
+ }
+
+ private void audit(final OPERATION operation) {
+ setOperation(operation);
+ setTimestamp((new Date()).getTime());
+ }
+
+ public enum OPERATION {
+ INSERT, UPDATE, DELETE;
+ private String value;
+
+ OPERATION() {
+ value = toString();
+ }
+
+ public static OPERATION parse(final String value) {
+ OPERATION operation = null;
+ for (final OPERATION op : OPERATION.values()) {
+ if (op.getValue().equals(value)) {
+ operation = op;
+ break;
+ }
+ }
+ return operation;
+ }
+
+ public String getValue() {
+ return value;
+ }
+ }
+
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Foo.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Foo.java
new file mode 100644
index 0000000000..ef88840746
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Foo.java
@@ -0,0 +1,94 @@
+package com.baeldung.domain;
+
+import org.hibernate.envers.Audited;
+
+import javax.persistence.*;
+import java.io.Serializable;
+
+@NamedNativeQueries({@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class)})
+@Entity
+@Audited
+// @Proxy(lazy = false)
+public class Foo implements Serializable {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @Column(name = "id")
+ private long id;
+
+ @Column(name = "name", nullable = false)
+ private String name;
+
+ @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
+ @JoinColumn(name = "BAR_ID")
+ private Bar bar = new Bar();
+
+ public Foo() {
+ super();
+ }
+
+ public Foo(final String name) {
+ super();
+ this.name = name;
+ }
+
+ //
+
+ public Bar getBar() {
+ return bar;
+ }
+
+ public void setBar(final Bar bar) {
+ this.bar = bar;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(final long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ //
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ final Foo other = (Foo) obj;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("Foo [name=").append(name).append("]");
+ return builder.toString();
+ }
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Item.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Item.java
new file mode 100644
index 0000000000..97ce14d92d
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Item.java
@@ -0,0 +1,81 @@
+package com.baeldung.domain;
+
+import java.math.BigDecimal;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+@Entity
+public class Item {
+
+ private String color;
+ private String grade;
+
+ @Id
+ private Long id;
+
+ @ManyToOne
+ private ItemType itemType;
+
+ private String name;
+ private BigDecimal price;
+ @ManyToOne
+ private Store store;
+
+ public String getColor() {
+ return color;
+ }
+
+ public String getGrade() {
+ return grade;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public ItemType getItemType() {
+ return itemType;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public BigDecimal getPrice() {
+ return price;
+ }
+
+ public Store getStore() {
+ return store;
+ }
+
+ public void setColor(String color) {
+ this.color = color;
+ }
+
+ public void setGrade(String grade) {
+ this.grade = grade;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public void setItemType(ItemType itemType) {
+ this.itemType = itemType;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setPrice(BigDecimal price) {
+ this.price = price;
+ }
+
+ public void setStore(Store store) {
+ this.store = store;
+ }
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/ItemType.java b/spring-data-jpa/src/main/java/com/baeldung/domain/ItemType.java
new file mode 100644
index 0000000000..412079c2ae
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/domain/ItemType.java
@@ -0,0 +1,46 @@
+package com.baeldung.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.OneToMany;
+
+@Entity
+public class ItemType {
+
+ @Id
+ private Long id;
+ @OneToMany(cascade = CascadeType.ALL)
+ @JoinColumn(name = "ITEM_TYPE_ID")
+ private List- items = new ArrayList<>();
+
+ private String name;
+
+ public Long getId() {
+ return id;
+ }
+
+ public List
- getItems() {
+ return items;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public void setItems(List
- items) {
+ this.items = items;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/KVTag.java b/spring-data-jpa/src/main/java/com/baeldung/domain/KVTag.java
new file mode 100644
index 0000000000..b3e7d78b30
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/domain/KVTag.java
@@ -0,0 +1,34 @@
+package com.baeldung.domain;
+
+import javax.persistence.Embeddable;
+
+@Embeddable
+public class KVTag {
+ private String key;
+ private String value;
+
+ public KVTag() {
+ }
+
+ public KVTag(String key, String value) {
+ super();
+ this.key = key;
+ this.value = value;
+ }
+
+ public String getKey() {
+ return key;
+ }
+
+ public void setKey(String key) {
+ this.key = key;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Location.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Location.java
new file mode 100644
index 0000000000..2178d378eb
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Location.java
@@ -0,0 +1,55 @@
+package com.baeldung.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.OneToMany;
+
+@Entity
+public class Location {
+
+ private String city;
+ private String country;
+ @Id
+ private Long id;
+
+ @OneToMany(cascade = CascadeType.ALL)
+ @JoinColumn(name = "LOCATION_ID")
+ private List stores = new ArrayList<>();
+
+ public String getCity() {
+ return city;
+ }
+
+ public String getCountry() {
+ return country;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public List getStores() {
+ return stores;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ public void setCountry(String country) {
+ this.country = country;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public void setStores(List stores) {
+ this.stores = stores;
+ }
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/SkillTag.java b/spring-data-jpa/src/main/java/com/baeldung/domain/SkillTag.java
new file mode 100644
index 0000000000..1f2778c589
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/domain/SkillTag.java
@@ -0,0 +1,30 @@
+package com.baeldung.domain;
+
+import javax.persistence.Embeddable;
+
+@Embeddable
+public class SkillTag {
+ private String name;
+ private int value;
+
+ public SkillTag() {
+ }
+
+ public SkillTag(String name, int value) {
+ super();
+ this.name = name;
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ public void setValue(int value) {
+ this.value = value;
+ }
+
+ public String getName() {
+ return name;
+ }
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Store.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Store.java
new file mode 100644
index 0000000000..e04684c479
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Store.java
@@ -0,0 +1,76 @@
+package com.baeldung.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+
+@Entity
+public class Store {
+
+ private Boolean active;
+ @Id
+ private Long id;
+ @OneToMany(cascade = CascadeType.ALL)
+ @JoinColumn(name = "STORE_ID")
+ private List
- items = new ArrayList<>();
+ private Long itemsSold;
+
+ @ManyToOne
+ private Location location;
+
+ private String name;
+
+ public Boolean getActive() {
+ return active;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public List
- getItems() {
+ return items;
+ }
+
+ public Long getItemsSold() {
+ return itemsSold;
+ }
+
+ public Location getLocation() {
+ return location;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setActive(Boolean active) {
+ this.active = active;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public void setItems(List
- items) {
+ this.items = items;
+ }
+
+ public void setItemsSold(Long itemsSold) {
+ this.itemsSold = itemsSold;
+ }
+
+ public void setLocation(Location location) {
+ this.location = location;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Student.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Student.java
new file mode 100644
index 0000000000..bd7eaeb24b
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Student.java
@@ -0,0 +1,74 @@
+package com.baeldung.domain;
+
+import javax.persistence.ElementCollection;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import java.util.ArrayList;
+import java.util.List;
+
+@Entity
+public class Student {
+
+ @Id
+ private long id;
+ private String name;
+
+ @ElementCollection
+ private List tags = new ArrayList<>();
+
+ @ElementCollection
+ private List skillTags = new ArrayList<>();
+
+ @ElementCollection
+ private List kvTags = new ArrayList<>();
+
+ public Student() {
+ }
+
+ public Student(long id, String name) {
+ super();
+ this.id = id;
+ this.name = name;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public List getTags() {
+ return tags;
+ }
+
+ public void setTags(List tags) {
+ this.tags.addAll(tags);
+ }
+
+ public List getSkillTags() {
+ return skillTags;
+ }
+
+ public void setSkillTags(List skillTags) {
+ this.skillTags.addAll(skillTags);
+ }
+
+ public List getKVTags() {
+ return this.kvTags;
+ }
+
+ public void setKVTags(List kvTags) {
+ this.kvTags.addAll(kvTags);
+ }
+
+}
diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java b/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java
similarity index 90%
rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java
rename to spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java
index 8490ed397d..42e6dd8f45 100644
--- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java
+++ b/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java
@@ -1,11 +1,11 @@
-package org.baeldung.persistence.multiple.model.product;
+package com.baeldung.domain.product;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
-@Table(schema = "spring_jpa_product")
+@Table(schema = "products")
public class Product {
@Id
diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java b/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java
new file mode 100644
index 0000000000..614e13df36
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java
@@ -0,0 +1,86 @@
+package com.baeldung.domain.user;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(schema = "users")
+public class Possession {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private long id;
+
+ private String name;
+
+ public Possession() {
+ super();
+ }
+
+ public Possession(final String name) {
+ super();
+
+ this.name = name;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(final int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = (prime * result) + (int) (id ^ (id >>> 32));
+ result = (prime * result) + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ final Possession other = (Possession) obj;
+ if (id != other.id) {
+ return false;
+ }
+ if (name == null) {
+ if (other.name != null) {
+ return false;
+ }
+ } else if (!name.equals(other.name)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]");
+ return builder.toString();
+ }
+
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java b/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java
new file mode 100644
index 0000000000..3a8b617d9a
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java
@@ -0,0 +1,86 @@
+package com.baeldung.domain.user;
+
+import javax.persistence.*;
+import java.util.List;
+
+@Entity
+@Table(name = "users", schema = "users")
+public class User {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private int id;
+ private String name;
+ private int age;
+ @Column(unique = true, nullable = false)
+ private String email;
+ private Integer status;
+ @OneToMany
+ List possessionList;
+
+ public User() {
+ super();
+ }
+
+ public User(String name, String email, Integer status) {
+ this.name = name;
+ this.email = email;
+ this.status = status;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(final int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(final String email) {
+ this.email = email;
+ }
+
+ public Integer getStatus() {
+ return status;
+ }
+
+ public void setStatus(Integer status) {
+ this.status = status;
+ }
+
+ public int getAge() {
+ return age;
+ }
+
+ public void setAge(final int age) {
+ this.age = age;
+ }
+
+ public List getPossessionList() {
+ return possessionList;
+ }
+
+ public void setPossessionList(List possessionList) {
+ this.possessionList = possessionList;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("User [name=").append(name).append(", id=").append(id).append("]");
+ return builder.toString();
+ }
+
+}
\ No newline at end of file
diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/IBarService.java b/spring-data-jpa/src/main/java/com/baeldung/services/IBarService.java
new file mode 100644
index 0000000000..7e127488db
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/services/IBarService.java
@@ -0,0 +1,7 @@
+package com.baeldung.services;
+
+import com.baeldung.domain.Bar;
+
+public interface IBarService extends IOperations {
+ //
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/IFooService.java b/spring-data-jpa/src/main/java/com/baeldung/services/IFooService.java
new file mode 100644
index 0000000000..7e16ace5b6
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/services/IFooService.java
@@ -0,0 +1,13 @@
+package com.baeldung.services;
+
+import com.baeldung.domain.Foo;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Pageable;
+
+public interface IFooService extends IOperations {
+
+ Foo retrieveByName(String name);
+
+ Page findPaginated(Pageable pageable);
+
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/IOperations.java b/spring-data-jpa/src/main/java/com/baeldung/services/IOperations.java
new file mode 100644
index 0000000000..d50d465639
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/services/IOperations.java
@@ -0,0 +1,26 @@
+package com.baeldung.services;
+
+import org.springframework.data.domain.Page;
+
+import java.io.Serializable;
+import java.util.List;
+
+public interface IOperations {
+
+ T findOne(final long id);
+
+ List findAll();
+
+ Page findPaginated(int page, int size);
+
+ // write
+
+ T create(final T entity);
+
+ T update(final T entity);
+
+ void delete(final T entity);
+
+ void deleteById(final long entityId);
+
+}
diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractService.java
new file mode 100644
index 0000000000..708524225b
--- /dev/null
+++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractService.java
@@ -0,0 +1,61 @@
+package com.baeldung.services.impl;
+
+import com.baeldung.services.IOperations;
+import com.google.common.collect.Lists;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.repository.PagingAndSortingRepository;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.io.Serializable;
+import java.util.List;
+
+@Transactional
+public abstract class AbstractService implements IOperations {
+
+ // read - one
+
+ @Override
+ @Transactional(readOnly = true)
+ public T findOne(final long id) {
+ return getDao().findById(id).orElse(null);
+ }
+
+ // read - all
+
+ @Override
+ @Transactional(readOnly = true)
+ public List