listIterator = items.listIterator();
+ while(listIterator.hasNext()) {
+ String nextWithIndex = items.get(listIterator.nextIndex());
+ String next = listIterator.next();
+ if( "ONE".equals(next)) {
+ listIterator.set("SWAPPED");
+ }
+ }
+ listIterator.add("FOUR");
+ while(listIterator.hasPrevious()) {
+ String previousWithIndex = items.get(listIterator.previousIndex());
+ String previous = listIterator.previous();
+ System.out.println(previous);
+ }
+ listIterator.forEachRemaining(e -> {
+ System.out.println(e);
+ });
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/javadoc/Person.java b/core-java/src/main/java/com/baeldung/javadoc/Person.java
new file mode 100644
index 0000000000..5efb410de4
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/javadoc/Person.java
@@ -0,0 +1,22 @@
+package com.baeldung.javadoc;
+
+public class Person {
+ /**
+ * This is a first name
+ */
+ private String firstName;
+ private String lastName;
+
+ public String getFirstName() {
+ return firstName;
+ }
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+ public String getLastName() {
+ return lastName;
+ }
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java b/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java
new file mode 100644
index 0000000000..029a779cdb
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java
@@ -0,0 +1,64 @@
+package com.baeldung.javadoc;
+
+/**
+ * Hero is the main entity we will be using to . . .
+ * @author Captain America
+ *
+ */
+public class SuperHero extends Person {
+
+ /**
+ * The public name of a hero that is common knowledge
+ */
+ private String heroName;
+ private String uniquePower;
+ private int health;
+ private int defense;
+
+ /**
+ * This is a simple description of the method. . .
+ * Superman!
+ *
+ * @param incomingDamage the amount of incoming damage
+ * @return the amount of health hero has after attack
+ * @see HERO-402
+ * @since 1.0
+ */
+ public int successfullyAttacked(int incomingDamage, String damageType) {
+ // do things
+ return 0;
+ }
+
+ public String getHeroName() {
+ return heroName;
+ }
+
+ public void setHeroName(String heroName) {
+ this.heroName = heroName;
+ }
+
+ public String getUniquePower() {
+ return uniquePower;
+ }
+
+ public void setUniquePower(String uniquePower) {
+ this.uniquePower = uniquePower;
+ }
+
+ public int getHealth() {
+ return health;
+ }
+
+ public void setHealth(int health) {
+ this.health = health;
+ }
+
+ public int getDefense() {
+ return defense;
+ }
+
+ public void setDefense(int defense) {
+ this.defense = defense;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java
new file mode 100644
index 0000000000..3e85bf13bb
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java
@@ -0,0 +1,7 @@
+package com.baeldung.regexp.datepattern;
+
+public interface DateMatcher {
+
+ boolean matches(String date);
+
+}
diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java
new file mode 100644
index 0000000000..1d3a609b55
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java
@@ -0,0 +1,14 @@
+package com.baeldung.regexp.datepattern;
+
+import java.util.regex.Pattern;
+
+class FormattedDateMatcher implements DateMatcher {
+
+ private static final Pattern DATE_PATTERN = Pattern.compile(
+ "^\\d{4}-\\d{2}-\\d{2}$");
+
+ @Override
+ public boolean matches(String date) {
+ return DATE_PATTERN.matcher(date).matches();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java
new file mode 100644
index 0000000000..af4e183fef
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java
@@ -0,0 +1,14 @@
+package com.baeldung.regexp.datepattern;
+
+import java.util.regex.Pattern;
+
+class RangedDateMatcher implements DateMatcher {
+
+ private static final Pattern DATE_PATTERN = Pattern.compile(
+ "^((19|2[0-9])[0-9]{2})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$");
+
+ @Override
+ public boolean matches(String date) {
+ return DATE_PATTERN.matcher(date).matches();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java
new file mode 100644
index 0000000000..b0243ae48f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java
@@ -0,0 +1,16 @@
+package com.baeldung.regexp.datepattern.gregorian;
+
+import com.baeldung.regexp.datepattern.DateMatcher;
+
+import java.util.regex.Pattern;
+
+public class February29thMatcher implements DateMatcher {
+
+ private static final Pattern DATE_PATTERN = Pattern.compile(
+ "^((2000|2400|2800|(19|2[0-9](0[48]|[2468][048]|[13579][26])))-02-29)$");
+
+ @Override
+ public boolean matches(String date) {
+ return DATE_PATTERN.matcher(date).matches();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java
new file mode 100644
index 0000000000..f294348928
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java
@@ -0,0 +1,16 @@
+package com.baeldung.regexp.datepattern.gregorian;
+
+import com.baeldung.regexp.datepattern.DateMatcher;
+
+import java.util.regex.Pattern;
+
+public class FebruaryGeneralMatcher implements DateMatcher {
+
+ private static final Pattern DATE_PATTERN = Pattern.compile(
+ "^(((19|2[0-9])[0-9]{2})-02-(0[1-9]|1[0-9]|2[0-8]))$");
+
+ @Override
+ public boolean matches(String date) {
+ return DATE_PATTERN.matcher(date).matches();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java
new file mode 100644
index 0000000000..fc8abdb201
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java
@@ -0,0 +1,19 @@
+package com.baeldung.regexp.datepattern.gregorian;
+
+import com.baeldung.regexp.datepattern.DateMatcher;
+
+import java.util.regex.Pattern;
+
+class GregorianDateMatcher implements DateMatcher {
+
+ private static final Pattern DATE_PATTERN = Pattern.compile(
+ "^((2000|2400|2800|(19|2[0-9](0[48]|[2468][048]|[13579][26])))-02-29)$"
+ + "|^(((19|2[0-9])[0-9]{2})-02-(0[1-9]|1[0-9]|2[0-8]))$"
+ + "|^(((19|2[0-9])[0-9]{2})-(0[13578]|10|12)-(0[1-9]|[12][0-9]|3[01]))$"
+ + "|^(((19|2[0-9])[0-9]{2})-(0[469]|11)-(0[1-9]|[12][0-9]|30))$");
+
+ @Override
+ public boolean matches(String date) {
+ return DATE_PATTERN.matcher(date).matches();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java
new file mode 100644
index 0000000000..be202081e8
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java
@@ -0,0 +1,17 @@
+package com.baeldung.regexp.datepattern.gregorian;
+
+import com.baeldung.regexp.datepattern.DateMatcher;
+
+import java.util.regex.Pattern;
+
+public class MonthsOf30DaysMatcher implements DateMatcher {
+
+ private static final Pattern DATE_PATTERN = Pattern.compile(
+ "^(((19|2[0-9])[0-9]{2})-(0[469]|11)-(0[1-9]|[12][0-9]|30))$");
+
+ @Override
+ public boolean matches(String date) {
+ return DATE_PATTERN.matcher(date).matches();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java
new file mode 100644
index 0000000000..7f0943991b
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java
@@ -0,0 +1,17 @@
+package com.baeldung.regexp.datepattern.gregorian;
+
+import com.baeldung.regexp.datepattern.DateMatcher;
+
+import java.util.regex.Pattern;
+
+public class MonthsOf31DaysMatcher implements DateMatcher {
+
+ private static final Pattern DATE_PATTERN = Pattern.compile(
+ "^(((19|2[0-9])[0-9]{2})-(0[13578]|10|12)-(0[1-9]|[12][0-9]|3[01]))$");
+
+ @Override
+ public boolean matches(String date) {
+ return DATE_PATTERN.matcher(date).matches();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java
index a9f055f8f4..d2f9f0459c 100644
--- a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java
+++ b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java
@@ -16,7 +16,7 @@ public class EchoMultiServer {
try {
serverSocket = new ServerSocket(port);
while (true)
- new EchoClientHandler(serverSocket.accept()).run();
+ new EchoClientHandler(serverSocket.accept()).start();
} catch (IOException e) {
e.printStackTrace();
diff --git a/core-java/src/main/java/com/baeldung/staticclass/Pizza.java b/core-java/src/main/java/com/baeldung/staticclass/Pizza.java
new file mode 100644
index 0000000000..ee6283cee1
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/staticclass/Pizza.java
@@ -0,0 +1,33 @@
+package com.baeldung.staticclass;
+
+public class Pizza {
+
+ private static String cookedCount;
+ private boolean isThinCrust;
+
+ // Accessible globally
+ public static class PizzaSalesCounter {
+
+ private static String orderedCount;
+ public static String deliveredCount;
+
+ PizzaSalesCounter() {
+ System.out.println("Static field of enclosing class is "
+ + Pizza.cookedCount);
+ System.out.println("Non-static field of enclosing class is "
+ + new Pizza().isThinCrust);
+ }
+ }
+
+ Pizza() {
+ System.out.println("Non private static field of static class is "
+ + PizzaSalesCounter.deliveredCount);
+ System.out.println("Private static field of static class is "
+ + PizzaSalesCounter.orderedCount);
+ }
+
+ public static void main(String[] a) {
+ // Create instance of the static class without an instance of enclosing class
+ new Pizza.PizzaSalesCounter();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java b/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java
new file mode 100644
index 0000000000..e9c8056ff5
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java
@@ -0,0 +1,22 @@
+package com.baeldung.threadlocalrandom;
+
+import org.openjdk.jmh.runner.Runner;
+import org.openjdk.jmh.runner.options.Options;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+public class ThreadLocalRandomBenchMarkRunner {
+
+ public static void main(String[] args) throws Exception {
+
+ Options options = new OptionsBuilder().include(ThreadLocalRandomBenchMarker.class.getSimpleName())
+ .threads(1)
+ .forks(1)
+ .shouldFailOnError(true)
+ .shouldDoGC(true)
+ .jvmArgs("-server")
+ .build();
+
+ new Runner(options).run();
+
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java b/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java
new file mode 100644
index 0000000000..8a0e2d2826
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java
@@ -0,0 +1,64 @@
+package com.baeldung.threadlocalrandom;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Warmup;
+
+@BenchmarkMode(Mode.AverageTime)
+@Warmup(iterations = 1)
+@OutputTimeUnit(TimeUnit.MICROSECONDS)
+@State(Scope.Benchmark)
+public class ThreadLocalRandomBenchMarker {
+
+ List> randomCallables = new ArrayList<>();
+ List> threadLocalRandomCallables = new ArrayList<>();
+
+ @Setup(Level.Iteration)
+ public void init() {
+ Random random = new Random();
+ randomCallables = new ArrayList<>();
+ threadLocalRandomCallables = new ArrayList<>();
+ for (int i = 0; i < 1000; i++) {
+ randomCallables.add(() -> {
+ return random.nextInt();
+ });
+ }
+
+ for (int i = 0; i < 1000; i++) {
+ threadLocalRandomCallables.add(() -> {
+ return ThreadLocalRandom.current()
+ .nextInt();
+ });
+ }
+ }
+
+ @Benchmark
+ public void randomValuesUsingRandom() throws InterruptedException {
+ ExecutorService executor = Executors.newWorkStealingPool();
+ executor.invokeAll(randomCallables);
+ executor.shutdown();
+ }
+
+ @Benchmark
+ public void randomValuesUsingThreadLocalRandom() throws InterruptedException {
+ ExecutorService executor = Executors.newWorkStealingPool();
+ executor.invokeAll(threadLocalRandomCallables);
+ executor.shutdown();
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java
new file mode 100644
index 0000000000..0a9599c3f9
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java
@@ -0,0 +1,24 @@
+package com.baeldung.regexp.datepattern;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class FormattedDateMatcherUnitTest {
+
+ private DateMatcher matcher = new FormattedDateMatcher();
+
+ @Test
+ public void whenUsingFormattedDateMatcher_thenFormatConstraintsSatisfied() {
+ Assert.assertTrue(matcher.matches("2017-12-31"));
+ Assert.assertTrue(matcher.matches("2018-01-01"));
+ Assert.assertTrue(matcher.matches("0000-00-00"));
+ Assert.assertTrue(matcher.matches("1029-99-72"));
+
+ Assert.assertFalse(matcher.matches("2018-01"));
+ Assert.assertFalse(matcher.matches("2018-01-01-01"));
+ Assert.assertFalse(matcher.matches("2018-01-XX"));
+ Assert.assertFalse(matcher.matches(" 2018-01-01"));
+ Assert.assertFalse(matcher.matches("2018-01-01 "));
+ Assert.assertFalse(matcher.matches("2018/01/01"));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java
new file mode 100644
index 0000000000..abbff83ec1
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.regexp.datepattern;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class RangedDateMatcherUnitTest {
+
+ private DateMatcher matcher = new RangedDateMatcher();
+
+ @Test
+ public void whenUsingRangedDateMatcher_thenFormatConstraintsSatisfied() {
+ Assert.assertFalse(matcher.matches("2018-01"));
+ Assert.assertFalse(matcher.matches("2018-01-01-01"));
+ Assert.assertFalse(matcher.matches("2018-01-XX"));
+ Assert.assertFalse(matcher.matches(" 2018-01-01"));
+ Assert.assertFalse(matcher.matches("2018-01-01 "));
+ Assert.assertFalse(matcher.matches("2018/01/01"));
+ }
+
+ @Test
+ public void whenUsingRangedDateMatcher_thenRangeConstraintsSatisfied() {
+ Assert.assertTrue(matcher.matches("1900-01-01"));
+ Assert.assertTrue(matcher.matches("2018-02-31"));
+ Assert.assertTrue(matcher.matches("2999-12-31"));
+
+ Assert.assertFalse(matcher.matches("1899-12-31"));
+ Assert.assertFalse(matcher.matches("2018-05-35"));
+ Assert.assertFalse(matcher.matches("2018-13-05"));
+ Assert.assertFalse(matcher.matches("3000-01-01"));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java
new file mode 100644
index 0000000000..67a4276728
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java
@@ -0,0 +1,17 @@
+package com.baeldung.regexp.datepattern.gregorian;
+
+import com.baeldung.regexp.datepattern.DateMatcher;
+import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
+import org.junit.Test;
+
+public class February29thMatcherUnitTest {
+
+ private DateMatcher matcher = new February29thMatcher();
+
+ private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
+
+ @Test
+ public void whenYearIsLeap_thenYearHasFebruary29th() {
+ testHelper.assertFebruary29th();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java
new file mode 100644
index 0000000000..48ff140620
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java
@@ -0,0 +1,17 @@
+package com.baeldung.regexp.datepattern.gregorian;
+
+import com.baeldung.regexp.datepattern.DateMatcher;
+import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
+import org.junit.Test;
+
+public class FebruaryGeneralMatcherUnitTest {
+
+ private DateMatcher matcher = new FebruaryGeneralMatcher();
+
+ private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
+
+ @Test
+ public void whenMonthIsFebruary_thenMonthContainsUpTo28Days() {
+ testHelper.assertFebruaryGeneralDates();
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java
new file mode 100644
index 0000000000..e6e896a09c
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java
@@ -0,0 +1,42 @@
+package com.baeldung.regexp.datepattern.gregorian;
+
+import com.baeldung.regexp.datepattern.DateMatcher;
+import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
+import org.junit.Test;
+
+public class GregorianDateMatcherUnitTest {
+
+ private DateMatcher matcher = new GregorianDateMatcher();
+
+ private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
+
+ @Test
+ public void whenUsingGregorianDateMatcher_thenFormatConstraintsSatisfied() {
+ testHelper.assertFormat();
+ }
+
+ @Test
+ public void whenUsingGregorianDateMatcher_thenRangeConstraintsSatisfied() {
+ testHelper.assertRange();
+ }
+
+ @Test
+ public void whenYearIsLeap_thenFebruaryHas29Days() {
+ testHelper.assertFebruary29th();
+ }
+
+ @Test
+ public void whenMonthIsFebruary_thenMonthContainsUpTo28Days() {
+ testHelper.assertFebruaryGeneralDates();
+ }
+
+ @Test
+ public void whenMonthIsShort_thenMonthContainsUpTo30Days() {
+ testHelper.assertMonthsOf30Days();
+ }
+
+ @Test
+ public void whenMonthIsLong_thenMonthContainsUpTo31Days() {
+ testHelper.assertMonthsOf31Dates();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java
new file mode 100644
index 0000000000..d1ce4a6d57
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java
@@ -0,0 +1,17 @@
+package com.baeldung.regexp.datepattern.gregorian;
+
+import com.baeldung.regexp.datepattern.DateMatcher;
+import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
+import org.junit.Test;
+
+public class MonthsOf30DaysMatcherUnitTest {
+
+ private DateMatcher matcher = new MonthsOf30DaysMatcher();
+
+ private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
+
+ @Test
+ public void whenMonthIsShort_thenMonthContainsUpTo30Days() {
+ testHelper.assertMonthsOf30Days();
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java
new file mode 100644
index 0000000000..338c8de30c
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java
@@ -0,0 +1,17 @@
+package com.baeldung.regexp.datepattern.gregorian;
+
+import com.baeldung.regexp.datepattern.DateMatcher;
+import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper;
+import org.junit.Test;
+
+public class MonthsOf31DaysMatcherUnitTest {
+
+ private DateMatcher matcher = new MonthsOf31DaysMatcher();
+
+ private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher);
+
+ @Test
+ public void whenMonthIsLong_thenMonthContainsUpTo31Days() {
+ testHelper.assertMonthsOf31Dates();
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java
new file mode 100644
index 0000000000..6429e4fe2d
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java
@@ -0,0 +1,102 @@
+package com.baeldung.regexp.datepattern.gregorian.testhelper;
+
+import com.baeldung.regexp.datepattern.DateMatcher;
+import org.junit.Assert;
+
+public class GregorianDateTestHelper {
+
+ private final DateMatcher matcher;
+
+ public GregorianDateTestHelper(DateMatcher matcher) {
+ this.matcher = matcher;
+ }
+
+ public void assertFormat() {
+ Assert.assertTrue(matcher.matches("2017-12-31"));
+ Assert.assertTrue(matcher.matches("2018-01-01"));
+
+ Assert.assertFalse(matcher.matches("2018-02"));
+ Assert.assertFalse(matcher.matches("2018-02-01-01"));
+ Assert.assertFalse(matcher.matches("2018-02-XX"));
+ Assert.assertFalse(matcher.matches(" 2018-02-01"));
+ Assert.assertFalse(matcher.matches("2018-02-01 "));
+ Assert.assertFalse(matcher.matches("2020/02/28"));
+ Assert.assertFalse(matcher.matches("2020.02.29"));
+ }
+
+ public void assertRange() {
+ Assert.assertTrue(matcher.matches("1900-01-01"));
+ Assert.assertTrue(matcher.matches("2205-05-25"));
+ Assert.assertTrue(matcher.matches("2999-12-31"));
+
+ Assert.assertFalse(matcher.matches("1899-12-31"));
+ Assert.assertFalse(matcher.matches("2018-05-35"));
+ Assert.assertFalse(matcher.matches("2018-13-05"));
+ Assert.assertFalse(matcher.matches("3000-01-01"));
+ Assert.assertFalse(matcher.matches("3200-02-29"));
+ }
+
+ public void assertFebruary29th() {
+ Assert.assertTrue(matcher.matches("2000-02-29"));
+ Assert.assertTrue(matcher.matches("2400-02-29"));
+ Assert.assertTrue(matcher.matches("2800-02-29"));
+ Assert.assertTrue(matcher.matches("2020-02-29"));
+ Assert.assertTrue(matcher.matches("2024-02-29"));
+ Assert.assertTrue(matcher.matches("2028-02-29"));
+
+ Assert.assertFalse(matcher.matches("2017-02-29"));
+ Assert.assertFalse(matcher.matches("2018-02-29"));
+ Assert.assertFalse(matcher.matches("2019-02-29"));
+ Assert.assertFalse(matcher.matches("2100-02-29"));
+ Assert.assertFalse(matcher.matches("2200-02-29"));
+ Assert.assertFalse(matcher.matches("2300-02-29"));
+ }
+
+ public void assertFebruaryGeneralDates() {
+ Assert.assertTrue(matcher.matches("2018-02-01"));
+ Assert.assertTrue(matcher.matches("2019-02-13"));
+ Assert.assertTrue(matcher.matches("2020-02-25"));
+
+ Assert.assertFalse(matcher.matches("2000-02-30"));
+ Assert.assertFalse(matcher.matches("2400-02-62"));
+ Assert.assertFalse(matcher.matches("2420-02-94"));
+ }
+
+ public void assertMonthsOf30Days() {
+ Assert.assertTrue(matcher.matches("2018-04-30"));
+ Assert.assertTrue(matcher.matches("2019-06-30"));
+ Assert.assertTrue(matcher.matches("2020-09-30"));
+ Assert.assertTrue(matcher.matches("2021-11-30"));
+
+ Assert.assertTrue(matcher.matches("2022-04-02"));
+ Assert.assertTrue(matcher.matches("2023-06-14"));
+ Assert.assertTrue(matcher.matches("2024-09-26"));
+
+ Assert.assertFalse(matcher.matches("2018-04-31"));
+ Assert.assertFalse(matcher.matches("2019-06-31"));
+ Assert.assertFalse(matcher.matches("2020-09-31"));
+ Assert.assertFalse(matcher.matches("2021-11-31"));
+
+ Assert.assertFalse(matcher.matches("2022-04-32"));
+ Assert.assertFalse(matcher.matches("2023-06-64"));
+ Assert.assertFalse(matcher.matches("2024-09-96"));
+ }
+
+ public void assertMonthsOf31Dates() {
+ Assert.assertTrue(matcher.matches("2018-01-31"));
+ Assert.assertTrue(matcher.matches("2019-03-31"));
+ Assert.assertTrue(matcher.matches("2020-05-31"));
+ Assert.assertTrue(matcher.matches("2021-07-31"));
+ Assert.assertTrue(matcher.matches("2022-08-31"));
+ Assert.assertTrue(matcher.matches("2023-10-31"));
+ Assert.assertTrue(matcher.matches("2024-12-31"));
+
+ Assert.assertTrue(matcher.matches("2025-01-03"));
+ Assert.assertTrue(matcher.matches("2026-03-15"));
+ Assert.assertTrue(matcher.matches("2027-05-27"));
+
+ Assert.assertFalse(matcher.matches("2018-01-32"));
+ Assert.assertFalse(matcher.matches("2019-03-64"));
+ Assert.assertFalse(matcher.matches("2020-05-96"));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java
new file mode 100644
index 0000000000..c75813baba
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java
@@ -0,0 +1,63 @@
+package com.baeldung.threadlocalrandom;
+
+import java.util.concurrent.ThreadLocalRandom;
+
+import static org.junit.Assert.assertTrue;
+import org.junit.Test;
+
+public class ThreadLocalRandomTest {
+
+ @Test
+ public void givenUsingThreadLocalRandom_whenGeneratingRandomIntBounded_thenCorrect() {
+ int leftLimit = 1;
+ int rightLimit = 100;
+ int generatedInt = ThreadLocalRandom.current().nextInt(leftLimit, rightLimit);
+
+ assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit);
+ }
+
+ @Test
+ public void givenUsingThreadLocalRandom_whenGeneratingRandomIntUnbounded_thenCorrect() {
+ int generatedInt = ThreadLocalRandom.current().nextInt();
+
+ assertTrue(generatedInt < Integer.MAX_VALUE && generatedInt >= Integer.MIN_VALUE);
+ }
+
+ @Test
+ public void givenUsingThreadLocalRandom_whenGeneratingRandomLongBounded_thenCorrect() {
+ long leftLimit = 1L;
+ long rightLimit = 100L;
+ long generatedLong = ThreadLocalRandom.current().nextLong(leftLimit, rightLimit);
+
+ assertTrue(generatedLong < rightLimit && generatedLong >= leftLimit);
+ }
+
+ @Test
+ public void givenUsingThreadLocalRandom_whenGeneratingRandomLongUnbounded_thenCorrect() {
+ long generatedInt = ThreadLocalRandom.current().nextLong();
+
+ assertTrue(generatedInt < Long.MAX_VALUE && generatedInt >= Long.MIN_VALUE);
+ }
+
+ @Test
+ public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleBounded_thenCorrect() {
+ double leftLimit = 1D;
+ double rightLimit = 100D;
+ double generatedInt = ThreadLocalRandom.current().nextDouble(leftLimit, rightLimit);
+
+ assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit);
+ }
+
+ @Test
+ public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
+ double generatedInt = ThreadLocalRandom.current().nextDouble();
+
+ assertTrue(generatedInt < Double.MAX_VALUE && generatedInt >= Double.MIN_VALUE);
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void givenUsingThreadLocalRandom_whenSettingSeed_thenThrowUnsupportedOperationException() {
+ ThreadLocalRandom.current().setSeed(0l);
+ }
+
+}
\ No newline at end of file
diff --git a/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java b/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerLiveTest.java
similarity index 90%
rename from ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java
rename to ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerLiveTest.java
index 9298c34ec2..f62d229261 100644
--- a/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java
+++ b/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerLiveTest.java
@@ -1,25 +1,30 @@
package com.baeldung.ethereumj.controllers;
-import com.baeldung.ethereumj.ApplicationMain;
-import com.baeldung.ethereumj.Constants;
-import com.baeldung.ethereumj.transfer.EthResponse;
+import static junit.framework.TestCase.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.http.*;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
-import static junit.framework.TestCase.assertTrue;
-import static org.junit.Assert.assertNotNull;
+import com.baeldung.ethereumj.ApplicationMain;
+import com.baeldung.ethereumj.Constants;
+import com.baeldung.ethereumj.transfer.EthResponse;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationMain.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@TestPropertySource(properties = "server.port=8080")
-public class EthControllerTestOne {
+public class EthControllerLiveTest {
@LocalServerPort
int port;
diff --git a/flyway/flyway-callbacks/pom.xml b/flyway/flyway-callbacks/pom.xml
deleted file mode 100644
index 9506c2c0c9..0000000000
--- a/flyway/flyway-callbacks/pom.xml
+++ /dev/null
@@ -1,58 +0,0 @@
-
-
- 4.0.0
-
- flyway-callbacks
- jar
-
- flyway-callbacks
- Flyway Callbacks Demo
-
-
- parent-boot-5
- com.baeldung
- 0.0.1-SNAPSHOT
- ../../parent-boot-5
-
-
-
- UTF-8
- UTF-8
- 1.8
-
-
-
-
- org.flywaydb
- flyway-core
- 5.0.2
-
-
-
- org.springframework.boot
- spring-boot-starter-jdbc
-
-
-
- com.h2database
- h2
-
-
- org.springframework.boot
- spring-boot-starter-test
- test
-
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
-
-
-
diff --git a/flyway/myFlywayConfig.properties b/flyway/myFlywayConfig.properties
index 8bb102930a..6b11f6f277 100644
--- a/flyway/myFlywayConfig.properties
+++ b/flyway/myFlywayConfig.properties
@@ -1,5 +1,5 @@
-flyway.user=root
-flyway.password=mysql
+flyway.user=sa
+flyway.password=
flyway.schemas=app-db
-flyway.url=jdbc:mysql://localhost:3306/
+flyway.url=jdbc:h2:mem:DATABASE
flyway.locations=filesystem:db/migration
\ No newline at end of file
diff --git a/flyway/pom.xml b/flyway/pom.xml
index c3806ed3bd..84009e4579 100644
--- a/flyway/pom.xml
+++ b/flyway/pom.xml
@@ -1,34 +1,76 @@
+
- 4.0.0
- com.baeldung
- flyway
- 1.0
- flyway
- A sample project to demonstrate Flyway migrations
-
-
- mysql
- mysql-connector-java
- 6.0.3
-
-
-
-
-
- org.flywaydb
- flyway-maven-plugin
- 4.0.3
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.5.1
-
-
- 1.8
-
-
-
-
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+
+ flyway
+ jar
+
+ flyway
+ Flyway Callbacks Demo
+
+
+ parent-boot-5
+ com.baeldung
+ 0.0.1-SNAPSHOT
+ ../parent-boot-5
+
+
+
+ UTF-8
+ UTF-8
+ 1.8
+
+
+
+
+ org.flywaydb
+ flyway-core
+ 5.0.2
+
+
+
+ org.springframework.boot
+ spring-boot-starter-jdbc
+
+
+
+ mysql
+ mysql-connector-java
+ 6.0.3
+
+
+
+ com.h2database
+ h2
+ test
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+
+
+
+ org.flywaydb
+ flyway-maven-plugin
+ 5.0.2
+
+
+ com.h2database
+ h2
+ ${h2.version}
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
diff --git a/flyway/flyway-callbacks/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java b/flyway/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java
similarity index 100%
rename from flyway/flyway-callbacks/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java
rename to flyway/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java
diff --git a/flyway/flyway-callbacks/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java b/flyway/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java
similarity index 100%
rename from flyway/flyway-callbacks/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java
rename to flyway/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java
diff --git a/flyway/flyway-callbacks/src/main/resources/application.properties b/flyway/src/main/resources/application.properties
similarity index 100%
rename from flyway/flyway-callbacks/src/main/resources/application.properties
rename to flyway/src/main/resources/application.properties
diff --git a/flyway/flyway-callbacks/src/main/resources/db/callbacks/beforeEachMigrate.sql b/flyway/src/main/resources/db/callbacks/beforeEachMigrate.sql
similarity index 100%
rename from flyway/flyway-callbacks/src/main/resources/db/callbacks/beforeEachMigrate.sql
rename to flyway/src/main/resources/db/callbacks/beforeEachMigrate.sql
diff --git a/flyway/flyway-callbacks/src/main/resources/db/callbacks/beforeMigrate.sql b/flyway/src/main/resources/db/callbacks/beforeMigrate.sql
similarity index 100%
rename from flyway/flyway-callbacks/src/main/resources/db/callbacks/beforeMigrate.sql
rename to flyway/src/main/resources/db/callbacks/beforeMigrate.sql
diff --git a/flyway/flyway-callbacks/src/main/resources/db/migration/V1_0__add_table_one.sql b/flyway/src/main/resources/db/migration/V1_0__add_table_one.sql
similarity index 100%
rename from flyway/flyway-callbacks/src/main/resources/db/migration/V1_0__add_table_one.sql
rename to flyway/src/main/resources/db/migration/V1_0__add_table_one.sql
diff --git a/flyway/flyway-callbacks/src/main/resources/db/migration/V1_1__add_table_two.sql b/flyway/src/main/resources/db/migration/V1_1__add_table_two.sql
similarity index 100%
rename from flyway/flyway-callbacks/src/main/resources/db/migration/V1_1__add_table_two.sql
rename to flyway/src/main/resources/db/migration/V1_1__add_table_two.sql
diff --git a/flyway/flyway-callbacks/src/main/resources/logback.xml b/flyway/src/main/resources/logback.xml
similarity index 100%
rename from flyway/flyway-callbacks/src/main/resources/logback.xml
rename to flyway/src/main/resources/logback.xml
diff --git a/flyway/flyway-callbacks/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java b/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java
similarity index 100%
rename from flyway/flyway-callbacks/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java
rename to flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java
diff --git a/flyway/flyway-callbacks/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java b/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java
similarity index 100%
rename from flyway/flyway-callbacks/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java
rename to flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java
diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCacheUnitTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCacheUnitTest.java
index eb67d8af44..49ce6b1a09 100644
--- a/guava/src/test/java/org/baeldung/guava/GuavaCacheUnitTest.java
+++ b/guava/src/test/java/org/baeldung/guava/GuavaCacheUnitTest.java
@@ -89,7 +89,7 @@ public class GuavaCacheUnitTest {
cache.getUnchecked("hello");
assertEquals(1, cache.size());
cache.getUnchecked("hello");
- Thread.sleep(300);
+ Thread.sleep(3);
cache.getUnchecked("test");
assertEquals(1, cache.size());
assertNull(cache.getIfPresent("hello"));
@@ -106,7 +106,7 @@ public class GuavaCacheUnitTest {
final LoadingCache cache = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.MILLISECONDS).build(loader);
cache.getUnchecked("hello");
assertEquals(1, cache.size());
- Thread.sleep(300);
+ Thread.sleep(3);
cache.getUnchecked("test");
assertEquals(1, cache.size());
assertNull(cache.getIfPresent("hello"));
@@ -203,8 +203,9 @@ public class GuavaCacheUnitTest {
private String getSuffix(final String str) {
final int lastIndex = str.lastIndexOf('.');
- if (lastIndex == -1)
+ if (lastIndex == -1) {
return null;
+ }
return str.substring(lastIndex + 1);
}
diff --git a/hibernate5/README.md b/hibernate5/README.md
index d480a7455c..1eb090f05d 100644
--- a/hibernate5/README.md
+++ b/hibernate5/README.md
@@ -4,3 +4,4 @@
- [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers)
- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time)
- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance)
+- [A Guide to Multitenancy in Hibernate 5](http://www.baeldung.com/hibernate-5-multitenancy)
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java
new file mode 100644
index 0000000000..1d60ccb6c0
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java
@@ -0,0 +1,32 @@
+package com.baeldung.hibernate.interceptors;
+
+import java.io.Serializable;
+import java.util.Date;
+
+import org.hibernate.EmptyInterceptor;
+import org.hibernate.type.Type;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.baeldung.hibernate.interceptors.entity.User;
+
+public class CustomInterceptor extends EmptyInterceptor {
+ private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);
+
+ @Override
+ public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
+ if (entity instanceof User) {
+ logger.info(((User) entity).toString());
+ }
+ return super.onSave(entity, id, state, propertyNames, types);
+ }
+
+ @Override
+ public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object [] previousState, String[] propertyNames, Type[] types) {
+ if (entity instanceof User) {
+ ((User) entity).setLastModified(new Date());
+ logger.info(((User) entity).toString());
+ }
+ return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
+ }
+}
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java
new file mode 100644
index 0000000000..a84a981f7f
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java
@@ -0,0 +1,122 @@
+package com.baeldung.hibernate.interceptors;
+
+import java.io.Serializable;
+import java.util.Iterator;
+
+import org.hibernate.CallbackException;
+import org.hibernate.EntityMode;
+import org.hibernate.Interceptor;
+import org.hibernate.Transaction;
+import org.hibernate.type.Type;
+
+public class CustomInterceptorImpl implements Interceptor {
+
+ @Override
+ public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void onCollectionRemove(Object collection, Serializable key) throws CallbackException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preFlush(Iterator entities) throws CallbackException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postFlush(Iterator entities) throws CallbackException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public Boolean isTransient(Object entity) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getEntityName(Object object) throws CallbackException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Object getEntity(String entityName, Serializable id) throws CallbackException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public void afterTransactionBegin(Transaction tx) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void beforeTransactionCompletion(Transaction tx) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void afterTransactionCompletion(Transaction tx) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public String onPrepareStatement(String sql) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java
new file mode 100644
index 0000000000..11dce698ca
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java
@@ -0,0 +1,79 @@
+package com.baeldung.hibernate.interceptors;
+
+import org.apache.commons.lang3.StringUtils;
+import org.hibernate.Interceptor;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.boot.Metadata;
+import org.hibernate.boot.MetadataSources;
+import org.hibernate.boot.SessionFactoryBuilder;
+import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.service.ServiceRegistry;
+
+import com.baeldung.hibernate.interceptors.entity.User;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.util.Properties;
+
+public class HibernateUtil {
+ private static SessionFactory sessionFactory;
+ private static String PROPERTY_FILE_NAME;
+
+ public static SessionFactory getSessionFactory() throws IOException {
+ return getSessionFactory(null);
+ }
+
+ public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
+ PROPERTY_FILE_NAME = propertyFileName;
+ if (sessionFactory == null) {
+ ServiceRegistry serviceRegistry = configureServiceRegistry();
+ sessionFactory = getSessionFactoryBuilder(serviceRegistry).build();
+ }
+ return sessionFactory;
+ }
+
+ public static SessionFactory getSessionFactoryWithInterceptor(String propertyFileName, Interceptor interceptor) throws IOException {
+ PROPERTY_FILE_NAME = propertyFileName;
+ if (sessionFactory == null) {
+ ServiceRegistry serviceRegistry = configureServiceRegistry();
+ sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(interceptor)
+ .build();
+ }
+ return sessionFactory;
+ }
+
+ public static Session getSessionWithInterceptor(Interceptor interceptor) throws IOException {
+ return getSessionFactory().withOptions()
+ .interceptor(interceptor)
+ .openSession();
+ }
+
+ private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
+ MetadataSources metadataSources = new MetadataSources(serviceRegistry);
+ metadataSources.addPackage("com.baeldung.hibernate.interceptors");
+ metadataSources.addAnnotatedClass(User.class);
+
+ Metadata metadata = metadataSources.buildMetadata();
+ return metadata.getSessionFactoryBuilder();
+
+ }
+
+ private static ServiceRegistry configureServiceRegistry() throws IOException {
+ Properties properties = getProperties();
+ return new StandardServiceRegistryBuilder().applySettings(properties)
+ .build();
+ }
+
+ private static Properties getProperties() throws IOException {
+ Properties properties = new Properties();
+ URL propertiesURL = Thread.currentThread()
+ .getContextClassLoader()
+ .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate-interceptors.properties"));
+ try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
+ properties.load(inputStream);
+ }
+ return properties;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java
new file mode 100644
index 0000000000..2b1dbe702b
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java
@@ -0,0 +1,64 @@
+package com.baeldung.hibernate.interceptors.entity;
+
+import java.util.Date;
+
+import javax.persistence.Basic;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+
+@Entity(name = "hbi_user")
+public class User {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ private long id;
+ private String name;
+ private String about;
+ @Basic
+ @Temporal(TemporalType.DATE)
+ private Date lastModified;
+
+ public User() {
+ }
+
+ public User(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Date getLastModified() {
+ return lastModified;
+ }
+
+ public void setLastModified(Date lastModified) {
+ this.lastModified = lastModified;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public String getAbout() {
+ return about;
+ }
+
+ public void setAbout(String about) {
+ this.about = about;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("ID: %d\nName: %s\nLast Modified: %s\nAbout: %s\n", getId(), getName(), getLastModified(), getAbout());
+ }
+}
diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorTest.java
new file mode 100644
index 0000000000..cbf28497bb
--- /dev/null
+++ b/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorTest.java
@@ -0,0 +1,62 @@
+package com.baeldung.hibernate.interceptors;
+
+import java.io.IOException;
+import java.io.Serializable;
+
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.baeldung.hibernate.interceptors.entity.User;
+
+public class HibernateInterceptorTest {
+ private static SessionFactory sessionFactory;
+ private static Serializable userId;
+
+ @Before
+ public void init() throws IOException {
+ sessionFactory = HibernateUtil.getSessionFactoryWithInterceptor(null, new CustomInterceptor());
+ }
+
+ @AfterClass
+ public static void finish() {
+ if(userId != null) {
+ Session session = sessionFactory.getCurrentSession();
+ Transaction transaction = session.beginTransaction();
+ User user = session.load(User.class, userId);
+ if(user != null) {
+ session.delete(user);
+ }
+ transaction.commit();
+ session.close();
+ }
+ }
+
+ @Test
+ public void givenHibernateInterceptorAndSessionScoped_whenUserCreated_shouldSucceed() {
+ Session session = sessionFactory.withOptions().interceptor(new CustomInterceptor()).openSession();
+ User user = new User("Benjamin Franklin");
+ Transaction transaction = session.beginTransaction();
+ userId = session.save(user);
+ transaction.commit();
+ session.close();
+ }
+
+ @Test
+ public void givenHibernateInterceptorAndSessionFactoryScoped_whenUserModified_shouldSucceed() {
+ Session session = sessionFactory.openSession();
+ Transaction transaction = session.beginTransaction();
+ User user = session.load(User.class, userId);
+ if(user != null) {
+ user.setAbout("I am a scientist.");
+ session.update(user);
+ }
+ transaction.commit();
+ session.close();
+ }
+
+}
diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java b/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java
index 5045c3ee8e..601eba651c 100644
--- a/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java
+++ b/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java
@@ -8,12 +8,15 @@ import java.util.Properties;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
-import org.junit.Assert;
@SuppressWarnings("serial")
public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider {
- private final ConnectionProvider connectionProvider = initConnectionProvider();
+ private final ConnectionProvider connectionProvider;
+
+ public SchemaMultiTenantConnectionProvider() throws IOException {
+ connectionProvider = initConnectionProvider();
+ }
@Override
protected ConnectionProvider getAnyConnectionProvider() {
@@ -33,13 +36,9 @@ public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConn
return connection;
}
- private ConnectionProvider initConnectionProvider() {
+ private ConnectionProvider initConnectionProvider() throws IOException {
Properties properties = new Properties();
- try {
- properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties"));
- } catch (IOException e) {
- Assert.fail("Error loading resource. Cause: " + e.getMessage());
- }
+ properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties"));
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
connectionProvider.configure(properties);
diff --git a/hibernate5/src/test/resources/hibernate-interceptors.properties b/hibernate5/src/test/resources/hibernate-interceptors.properties
new file mode 100644
index 0000000000..58b55d0a09
--- /dev/null
+++ b/hibernate5/src/test/resources/hibernate-interceptors.properties
@@ -0,0 +1,10 @@
+hibernate.connection.driver_class=org.h2.Driver
+hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
+hibernate.connection.username=sa
+hibernate.connection.autocommit=true
+jdbc.password=
+
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.show_sql=true
+hibernate.hbm2ddl.auto=create-drop
+hibernate.current_session_context_class=org.hibernate.context.internal.ThreadLocalSessionContext
\ No newline at end of file
diff --git a/hystrix/pom.xml b/hystrix/pom.xml
index 58e09816ea..9e4b2bb082 100644
--- a/hystrix/pom.xml
+++ b/hystrix/pom.xml
@@ -7,10 +7,10 @@
hystrix
- parent-boot-4
+ parent-boot-5
com.baeldung
0.0.1-SNAPSHOT
- ../parent-boot-4
+ ../parent-boot-5
diff --git a/java-lite/README.md b/java-lite/README.md
new file mode 100644
index 0000000000..bcb84e186e
--- /dev/null
+++ b/java-lite/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [RESTFul CRUD application with JavaLite] ()
\ No newline at end of file
diff --git a/java-lite/pom.xml b/java-lite/pom.xml
new file mode 100644
index 0000000000..eb18bc40a5
--- /dev/null
+++ b/java-lite/pom.xml
@@ -0,0 +1,96 @@
+
+
+ 4.0.0
+
+ org.baeldung
+ java-lite
+ 1.0-SNAPSHOT
+ war
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+ 9.4.8.v20171121
+ 1.4.13
+ 1.15
+ 5.1.45
+ 1.7.0
+ 1.8.2
+ 4.11
+
+
+
+
+
+ org.eclipse.jetty
+ jetty-maven-plugin
+ ${jetty.maven.plugin.version}
+
+
+
+ activejdbc.log
+
+
+
+ active_reload
+ true
+
+
+ activeweb.log.request
+ true
+
+
+
+
+
+
+ org.javalite
+ activejdbc-instrumentation
+ ${activejdbc.version}
+
+
+ process-classes
+
+ instrument
+
+
+
+
+
+
+
+
+
+ org.javalite
+ activeweb
+ ${activeweb.version}
+
+
+
+ mysql
+ mysql-connector-java
+ ${mysql.connector.java.version}
+
+
+
+ com.sun
+ tools
+ ${sun.tools.version}
+ system
+ ${java.home}/../lib/tools.jar
+
+
+
+ junit
+ junit
+ ${junit.version}
+
+
+
+
\ No newline at end of file
diff --git a/java-lite/src/main/java/app/config/AppBootstrap.java b/java-lite/src/main/java/app/config/AppBootstrap.java
new file mode 100644
index 0000000000..7a87c2d0a7
--- /dev/null
+++ b/java-lite/src/main/java/app/config/AppBootstrap.java
@@ -0,0 +1,9 @@
+package app.config;
+
+import org.javalite.activeweb.AppContext;
+import org.javalite.activeweb.Bootstrap;
+
+public class AppBootstrap extends Bootstrap {
+ public void init(AppContext context) {
+ }
+}
diff --git a/java-lite/src/main/java/app/config/AppControllerConfig.java b/java-lite/src/main/java/app/config/AppControllerConfig.java
new file mode 100644
index 0000000000..da30c08ab2
--- /dev/null
+++ b/java-lite/src/main/java/app/config/AppControllerConfig.java
@@ -0,0 +1,15 @@
+package app.config;
+
+import app.controllers.ProductsController;
+import org.javalite.activeweb.AbstractControllerConfig;
+import org.javalite.activeweb.AppContext;
+import org.javalite.activeweb.controller_filters.DBConnectionFilter;
+import org.javalite.activeweb.controller_filters.TimingFilter;
+
+public class AppControllerConfig extends AbstractControllerConfig {
+ @Override
+ public void init(AppContext appContext) {
+ addGlobalFilters(new TimingFilter());
+ add(new DBConnectionFilter()).to(ProductsController.class);
+ }
+}
diff --git a/java-lite/src/main/java/app/config/DbConfig.java b/java-lite/src/main/java/app/config/DbConfig.java
new file mode 100644
index 0000000000..75de248619
--- /dev/null
+++ b/java-lite/src/main/java/app/config/DbConfig.java
@@ -0,0 +1,11 @@
+package app.config;
+
+import org.javalite.activeweb.AbstractDBConfig;
+import org.javalite.activeweb.AppContext;
+
+public class DbConfig extends AbstractDBConfig {
+ @Override
+ public void init(AppContext appContext) {
+ this.configFile("/database.properties");
+ }
+}
diff --git a/java-lite/src/main/java/app/controllers/ProductsController.java b/java-lite/src/main/java/app/controllers/ProductsController.java
new file mode 100644
index 0000000000..746d77e24a
--- /dev/null
+++ b/java-lite/src/main/java/app/controllers/ProductsController.java
@@ -0,0 +1,103 @@
+package app.controllers;
+
+import app.models.Product;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.javalite.activeweb.AppController;
+import org.javalite.activeweb.annotations.RESTful;
+
+import java.util.Map;
+
+@RESTful
+public class ProductsController extends AppController {
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ public void index() {
+ try {
+ view("products", Product.findAll());
+ render().contentType("application/json");
+ } catch (Exception e) {
+ view("message", "There was an error.", "code", 200);
+ render("message");
+ }
+ }
+
+ public void create() {
+ try {
+ Map payload = mapper.readValue(getRequestString(), Map.class);
+ Product p = new Product();
+ p.fromMap(payload);
+ p.saveIt();
+ view("message", "Successfully saved product id " + p.get("id"), "code", 200);
+ render("message");
+ } catch (Exception e) {
+ view("message", "There was an error.", "code", 200);
+ render("message");
+ }
+ }
+
+ public void update() {
+ try {
+ Map payload = mapper.readValue(getRequestString(), Map.class);
+ String id = getId();
+ Product p = Product.findById(id);
+ if (p == null) {
+ view("message", "Product id " + id + " not found.", "code", 200);
+ render("message");
+ return;
+ }
+ p.fromMap(payload);
+ p.saveIt();
+ view("message", "Successfully updated product id " + id, "code", 200);
+ render("message");
+ } catch (Exception e) {
+ view("message", "There was an error.", "code", 200);
+ render("message");
+ }
+ }
+
+ public void show() {
+ try {
+ String id = getId();
+ Product p = Product.findById(id);
+ if (p == null) {
+ view("message", "Product id " + id + " not found.", "code", 200);
+ render("message");
+ return;
+ }
+ view("product", p);
+ render("_product");
+ } catch (Exception e) {
+ view("message", "There was an error.", "code", 200);
+ render("message");
+ }
+ }
+
+ public void destroy() {
+ try {
+ String id = getId();
+ Product p = Product.findById(id);
+ if (p == null) {
+ view("message", "Product id " + id + " not found.", "code", 200);
+ render("message");
+ return;
+ }
+ p.delete();
+ view("message", "Successfully deleted product id " + id, "code", 200);
+ render("message");
+ } catch (Exception e) {
+ view("message", "There was an error.", "code", 200);
+ render("message");
+ }
+ }
+
+ @Override
+ protected String getContentType() {
+ return "application/json";
+ }
+
+ @Override
+ protected String getLayout() {
+ return null;
+ }
+}
diff --git a/java-lite/src/main/java/app/models/Product.java b/java-lite/src/main/java/app/models/Product.java
new file mode 100644
index 0000000000..7fa32b75d9
--- /dev/null
+++ b/java-lite/src/main/java/app/models/Product.java
@@ -0,0 +1,7 @@
+package app.models;
+
+import org.javalite.activejdbc.Model;
+
+public class Product extends Model {
+
+}
diff --git a/java-lite/src/main/resources/database.properties b/java-lite/src/main/resources/database.properties
new file mode 100644
index 0000000000..55b3851d33
--- /dev/null
+++ b/java-lite/src/main/resources/database.properties
@@ -0,0 +1,4 @@
+development.driver=com.mysql.jdbc.Driver
+development.username=user
+development.password=password
+development.url=jdbc:mysql://localhost/dbname
\ No newline at end of file
diff --git a/java-lite/src/main/webapp/WEB-INF/views/products/_comma.ftl b/java-lite/src/main/webapp/WEB-INF/views/products/_comma.ftl
new file mode 100644
index 0000000000..41622b4720
--- /dev/null
+++ b/java-lite/src/main/webapp/WEB-INF/views/products/_comma.ftl
@@ -0,0 +1 @@
+,
\ No newline at end of file
diff --git a/java-lite/src/main/webapp/WEB-INF/views/products/_product.ftl b/java-lite/src/main/webapp/WEB-INF/views/products/_product.ftl
new file mode 100644
index 0000000000..562af0499e
--- /dev/null
+++ b/java-lite/src/main/webapp/WEB-INF/views/products/_product.ftl
@@ -0,0 +1,4 @@
+{
+"id" : ${product.id},
+"name" : "${product.name}"
+}
\ No newline at end of file
diff --git a/java-lite/src/main/webapp/WEB-INF/views/products/index.ftl b/java-lite/src/main/webapp/WEB-INF/views/products/index.ftl
new file mode 100644
index 0000000000..c343f20910
--- /dev/null
+++ b/java-lite/src/main/webapp/WEB-INF/views/products/index.ftl
@@ -0,0 +1 @@
+[<@render partial="product" collection=products spacer="comma"/>]
\ No newline at end of file
diff --git a/java-lite/src/main/webapp/WEB-INF/views/products/message.ftl b/java-lite/src/main/webapp/WEB-INF/views/products/message.ftl
new file mode 100644
index 0000000000..3e7faf1459
--- /dev/null
+++ b/java-lite/src/main/webapp/WEB-INF/views/products/message.ftl
@@ -0,0 +1,4 @@
+{
+"message" : "${message}",
+"code" : ${code}
+}
\ No newline at end of file
diff --git a/java-lite/src/main/webapp/WEB-INF/web.xml b/java-lite/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000..c285876c86
--- /dev/null
+++ b/java-lite/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,25 @@
+
+
+
+
+
+ dispatcher
+ org.javalite.activeweb.RequestDispatcher
+
+ exclusions
+ css,images,js,ico
+
+
+ encoding
+ UTF-8
+
+
+
+
+
+ dispatcher
+ /*
+
+
+
diff --git a/java-lite/src/test/java/app/models/ProductTest.java b/java-lite/src/test/java/app/models/ProductTest.java
new file mode 100644
index 0000000000..5e5c6e8845
--- /dev/null
+++ b/java-lite/src/test/java/app/models/ProductTest.java
@@ -0,0 +1,25 @@
+package app.models;
+
+import org.javalite.activejdbc.Base;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class ProductTest {
+
+ //@Test
+ public void givenSavedProduct_WhenFindFirst_ThenSavedProductIsReturned() {
+ //Open DB connection
+ Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/dbname", "user", "password");
+
+ //Create a product and save it
+ Product toSaveProduct = new Product();
+ toSaveProduct.set("name", "Bread");
+ toSaveProduct.saveIt();
+
+ //Find product
+ Product savedProduct = Product.findFirst("name = ?", "Bread");
+
+ Assert.assertEquals(toSaveProduct.get("name"), savedProduct.get("name"));
+ }
+
+}
\ No newline at end of file
diff --git a/java-vavr-stream/pom.xml b/java-vavr-stream/pom.xml
new file mode 100644
index 0000000000..ca3807cd15
--- /dev/null
+++ b/java-vavr-stream/pom.xml
@@ -0,0 +1,20 @@
+
+
+ 4.0.0
+ com.baeldung.samples
+ java-vavr-stream
+ 1.0
+ jar
+
+ UTF-8
+ 1.8
+ 1.8
+
+
+
+ io.vavr
+ vavr
+ 0.9.2
+
+
+
\ No newline at end of file
diff --git a/java-vavr-stream/src/main/java/com/baeldung/samples/java/vavr/VavrSampler.java b/java-vavr-stream/src/main/java/com/baeldung/samples/java/vavr/VavrSampler.java
new file mode 100644
index 0000000000..d539342f69
--- /dev/null
+++ b/java-vavr-stream/src/main/java/com/baeldung/samples/java/vavr/VavrSampler.java
@@ -0,0 +1,98 @@
+package com.baeldung.samples.java.vavr;
+
+import io.vavr.collection.Stream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.IntStream;
+
+/**
+ *
+ * @author baeldung
+ */
+public class VavrSampler {
+
+ static int[] intArray = new int[]{1, 2, 4};
+ static List intList = new ArrayList();
+ static int[][] intOfInts = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
+
+ public static void main(String[] args) {
+ vavrStreamElementAccess();
+ System.out.println("====================================");
+ vavrParallelStreamAccess();
+ System.out.println("====================================");
+ jdkFlatMapping();
+ System.out.println("====================================");
+ vavrStreamManipulation();
+ System.out.println("====================================");
+ vavrStreamDistinct();
+ }
+
+ public static void vavrStreamElementAccess() {
+ System.out.println("Vavr Element Access");
+ System.out.println("====================================");
+ Stream vavredStream = Stream.ofAll(intArray);
+ System.out.println("Vavr index access: " + vavredStream.get(2));
+ System.out.println("Vavr head element access: " + vavredStream.get());
+
+ Stream vavredStringStream = Stream.of("foo", "bar", "baz");
+ System.out.println("Find foo " + vavredStringStream.indexOf("foo"));
+ }
+
+ public static void vavrParallelStreamAccess() {
+ try {
+ System.out.println("Vavr Stream Concurrent Modification");
+ System.out.println("====================================");
+ Stream vavrStream = Stream.ofAll(intList);
+ intList.add(5);
+ vavrStream.forEach(i -> System.out.println("in a Vavr Stream: " + i));
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+
+ Stream wrapped = Stream.ofAll(intArray);
+ intArray[2] = 5;
+ wrapped.forEach(i -> System.out.println("Vavr looped " + i));
+ }
+
+ public static void jdkFlatMapping() {
+ System.out.println("JDK FlatMap -> Uncomment line 68 to test");
+ System.out.println("====================================");
+ int[][] intOfInts = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
+
+ IntStream mapToInt = Arrays.stream(intOfInts)
+ .map(intArr -> Arrays.stream(intArr))
+ .flatMapToInt(val -> val.map(n -> {
+ return n * n;
+ }))
+ .peek(n -> System.out.println("Peeking at " + n));
+ //Uncomment to execute pipeline
+ //mapToInt.forEach(n -> System.out.println("FlatMapped Result "+n));
+ }
+
+ public static void vavrStreamManipulation() {
+ System.out.println("Vavr Stream Manipulation");
+ System.out.println("====================================");
+ List stringList = new ArrayList<>();
+ stringList.add("foo");
+ stringList.add("bar");
+ stringList.add("baz");
+ Stream vavredStream = Stream.ofAll(stringList);
+ vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item));
+ Stream vavredStream2 = vavredStream.insert(2, "buzz");
+ vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item));
+ stringList.forEach(item -> System.out.println("List item after stream addition: " + item));
+ Stream deletionStream = vavredStream.remove("bar");
+ deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item));
+
+ }
+
+ public static void vavrStreamDistinct() {
+ Stream vavredStream = Stream.of("foo", "bar", "baz", "buxx", "bar", "bar", "foo");
+ Stream distinctVavrStream = vavredStream.distinctBy((y, z) -> {
+ return y.compareTo(z);
+ });
+ distinctVavrStream.forEach(item -> System.out.println("Vavr Stream item after distinct query " + item));
+
+ }
+}
diff --git a/jjwt/pom.xml b/jjwt/pom.xml
index 83a1131211..cd2dd9f97e 100644
--- a/jjwt/pom.xml
+++ b/jjwt/pom.xml
@@ -12,10 +12,10 @@
Exercising the JJWT
- parent-boot-4
+ parent-boot-5
com.baeldung
0.0.1-SNAPSHOT
- ../parent-boot-4
+ ../parent-boot-5
diff --git a/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java b/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java
index df147232d9..846445ab2b 100644
--- a/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java
+++ b/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java
@@ -2,12 +2,12 @@ package io.jsonwebtoken.jjwtfun;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.springframework.boot.test.SpringApplicationConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
-@SpringApplicationConfiguration(classes = JJWTFunApplication.class)
+@SpringBootTest(classes = JJWTFunApplication.class)
@WebAppConfiguration
public class DemoApplicationIntegrationTest {
diff --git a/libraries/pom.xml b/libraries/pom.xml
index 712a7df786..09c8cb8335 100644
--- a/libraries/pom.xml
+++ b/libraries/pom.xml
@@ -107,7 +107,7 @@
maven-compiler-plugin
- 3.7.0
+ 3.7.0
1.8
@@ -639,6 +639,33 @@
${googleclient.version}
+
+
+ com.github.docker-java
+ docker-java
+ ${docker.version}
+
+
+ org.slf4j
+ slf4j-log4j12
+
+
+ org.slf4j
+ jcl-over-slf4j
+
+
+ ch.qos.logback
+ logback-classic
+
+
+
+
+ com.sun.jersey
+ jersey-client
+ 1.19.4
+
+
+
com.google.api-client
@@ -758,5 +785,6 @@
1.23.0
v4-rev493-1.21.0
1.0.0
+ 3.0.14
\ No newline at end of file
diff --git a/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java
new file mode 100644
index 0000000000..531e7e7c5b
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java
@@ -0,0 +1,165 @@
+package com.baeldung.dockerapi;
+
+import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.command.CreateContainerResponse;
+import com.github.dockerjava.api.command.InspectContainerResponse;
+import com.github.dockerjava.api.model.Container;
+import com.github.dockerjava.api.model.PortBinding;
+import com.github.dockerjava.core.DockerClientBuilder;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.List;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.core.Is.is;
+
+public class ContainerLiveTest {
+
+ private static DockerClient dockerClient;
+
+ @BeforeClass
+ public static void setup() {
+ dockerClient = DockerClientBuilder.getInstance().build();
+ }
+
+ @Test
+ public void whenListingRunningContainers_thenReturnNonEmptyList() {
+
+ //when
+ List containers = dockerClient.listContainersCmd().exec();
+
+ //then
+ assertThat(containers.size(), is(not(0)));
+ }
+
+ @Test
+ public void whenListingExitedContainers_thenReturnNonEmptyList() {
+
+ //when
+ List containers = dockerClient.listContainersCmd()
+ .withShowSize(true)
+ .withShowAll(true)
+ .withStatusFilter("exited")
+ .exec();
+
+ //then
+ assertThat(containers.size(), is(not(0)));
+ }
+
+ @Test
+ public void whenCreatingContainer_thenMustReturnContainerId() {
+
+ //when
+ CreateContainerResponse container
+ = dockerClient.createContainerCmd("mongo:3.6")
+ .withCmd("--bind_ip_all")
+ .withName("mongo")
+ .withHostName("baeldung")
+ .withEnv("MONGO_LATEST_VERSION=3.6")
+ .withPortBindings(PortBinding.parse("9999:27017"))
+ .exec();
+
+ //then
+ assertThat(container.getId(), is(not(null)));
+ }
+
+
+ @Test
+ public void whenHavingContainer_thenRunContainer() throws InterruptedException {
+
+ //when
+ CreateContainerResponse container
+ = dockerClient.createContainerCmd("alpine:3.6")
+ .withCmd("sleep", "10000")
+ .exec();
+
+ Thread.sleep(3000);
+ //then
+ dockerClient.startContainerCmd(container.getId())
+ .exec();
+
+ dockerClient.stopContainerCmd(container.getId())
+ .exec();
+ }
+
+ @Test
+ public void whenRunningContainer_thenStopContainer() throws InterruptedException {
+
+ //when
+ CreateContainerResponse container
+ = dockerClient.createContainerCmd("alpine:3.6")
+ .withCmd("sleep", "10000")
+ .exec();
+
+ Thread.sleep(3000);
+ dockerClient.startContainerCmd(container.getId())
+ .exec();
+
+ //then
+ dockerClient.stopContainerCmd(container.getId())
+ .exec();
+ }
+
+ @Test
+ public void whenRunningContainer_thenKillContainer() throws InterruptedException {
+
+ //when
+ CreateContainerResponse container
+ = dockerClient.createContainerCmd("alpine:3.6")
+ .withCmd("sleep", "10000")
+ .exec();
+
+ dockerClient.startContainerCmd(container.getId())
+ .exec();
+
+ Thread.sleep(3000);
+ dockerClient.stopContainerCmd(container.getId())
+ .exec();
+
+ //then
+ dockerClient.killContainerCmd(container.getId())
+ .exec();
+ }
+
+ @Test
+ public void whenHavingContainer_thenInspectContainer() {
+
+ //when
+ CreateContainerResponse container
+ = dockerClient.createContainerCmd("alpine:3.6")
+ .withCmd("sleep", "10000")
+ .exec();
+
+ //then
+ InspectContainerResponse containerResponse
+ = dockerClient.inspectContainerCmd(container.getId())
+ .exec();
+
+ assertThat(containerResponse.getId(), is(container.getId()));
+ }
+
+
+ @Test
+ public void givenContainer_whenCommittingContainer_thenMustReturnImageId() {
+
+ //given
+ CreateContainerResponse container
+ = dockerClient.createContainerCmd("alpine:3.6")
+ .withCmd("sleep", "10000")
+ .exec();
+
+ //when
+ String imageId = dockerClient.commitCmd(container.getId())
+ .withEnv("SNAPSHOT_YEAR=2018")
+ .withMessage("add git support")
+ .withCmd("sleep", "10000")
+ .withRepository("alpine")
+ .withTag("3.6.v2").exec();
+
+ //then
+ assertThat(imageId, is(not(null)));
+ }
+
+}
diff --git a/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java
new file mode 100644
index 0000000000..1023298e25
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java
@@ -0,0 +1,83 @@
+package com.baeldung.dockerapi;
+
+import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.core.DefaultDockerClientConfig;
+import com.github.dockerjava.core.DockerClientBuilder;
+import org.junit.Test;
+
+import java.util.Properties;
+
+import static org.junit.Assert.assertNotNull;
+
+public class DockerClientLiveTest {
+
+ @Test
+ public void whenCreatingDockerClient_thenReturnDefaultInstance() {
+
+ //when
+ DefaultDockerClientConfig.Builder config
+ = DefaultDockerClientConfig.createDefaultConfigBuilder();
+ DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
+
+ //then
+ assertNotNull(dockerClient);
+ }
+
+ @Test
+ public void whenCreatingDockerClientWithDockerHost_thenReturnInstance() {
+ //when
+ DockerClient dockerClient
+ = DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375")
+ .build();
+
+ //then
+ assertNotNull(dockerClient);
+ }
+
+ @Test
+ public void whenCreatingAdvanceDockerClient_thenReturnInstance() {
+
+ //when
+ DefaultDockerClientConfig config
+ = DefaultDockerClientConfig.createDefaultConfigBuilder()
+ .withRegistryEmail("info@bealdung.com")
+ .withRegistryUrl("register.bealdung.io/v2/")
+ .withRegistryPassword("strongpassword")
+ .withRegistryUsername("bealdung")
+ .withDockerCertPath("/home/bealdung/public/.docker/certs")
+ .withDockerConfig("/home/bealdung/public/.docker/")
+ .withDockerTlsVerify("1")
+ .withDockerHost("tcp://docker.beauldung.com:2376")
+ .build();
+
+ DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
+
+ //then
+ assertNotNull(dockerClient);
+ }
+
+ @Test
+ public void whenCreatingDockerClientWithProperties_thenReturnInstance() {
+
+ //when
+ Properties properties = new Properties();
+ properties.setProperty("registry.email", "info@bealdung.com");
+ properties.setProperty("registry.url", "register.bealdung.io/v2/");
+ properties.setProperty("registry.password", "strongpassword");
+ properties.setProperty("registry.username", "bealdung");
+ properties.setProperty("DOCKER_CERT_PATH", "/home/bealdung/public/.docker/certs");
+ properties.setProperty("DOCKER_CONFIG", "/home/bealdung/public/.docker/");
+ properties.setProperty("DOCKER_TLS_VERIFY", "1");
+ properties.setProperty("DOCKER_HOST", "tcp://docker.bealdung.com:2376");
+
+ DefaultDockerClientConfig config
+ = DefaultDockerClientConfig.createDefaultConfigBuilder()
+ .withProperties(properties)
+ .build();
+
+ DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
+
+ //then
+ assertNotNull(dockerClient);
+ }
+}
diff --git a/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java
new file mode 100644
index 0000000000..ef894b2773
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java
@@ -0,0 +1,155 @@
+package com.baeldung.dockerapi;
+
+import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.command.InspectImageResponse;
+import com.github.dockerjava.api.model.Image;
+import com.github.dockerjava.api.model.SearchItem;
+import com.github.dockerjava.core.DockerClientBuilder;
+import com.github.dockerjava.core.command.BuildImageResultCallback;
+import com.github.dockerjava.core.command.PullImageResultCallback;
+import com.github.dockerjava.core.command.PushImageResultCallback;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.io.File;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.hamcrest.Matchers.lessThan;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.core.Is.is;
+
+public class ImageLiveTest {
+
+ private static DockerClient dockerClient;
+
+ @BeforeClass
+ public static void setup() {
+ dockerClient = DockerClientBuilder.getInstance().build();
+ }
+
+ @Test
+ public void whenListingImages_thenReturnNonEmptyList() {
+
+ //when
+ List images = dockerClient.listImagesCmd().exec();
+
+ //then
+ assertThat(images.size(), is(not(0)));
+ }
+
+ @Test
+ public void whenListingImagesWithIntermediateImages_thenReturnNonEmptyList() {
+
+ //when
+ List images = dockerClient.listImagesCmd()
+ .withShowAll(true).exec();
+
+ //then
+ assertThat(images.size(), is(not(0)));
+ }
+
+ @Test
+ public void whenListingDanglingImages_thenReturnNonNullList() {
+
+ //when
+ List images = dockerClient.listImagesCmd()
+ .withDanglingFilter(true).exec();
+
+ //then
+ assertThat(images, is(not(null)));
+ }
+
+ @Test
+ public void whenBuildingImage_thenMustReturnImageId() {
+
+ //when
+ String imageId = dockerClient.buildImageCmd()
+ .withDockerfile(new File("src/test/resources/dockerapi/Dockerfile"))
+ .withPull(true)
+ .withNoCache(true)
+ .withTag("alpine:git")
+ .exec(new BuildImageResultCallback())
+ .awaitImageId();
+
+ //then
+ assertThat(imageId, is(not(null)));
+ }
+
+ @Test
+ public void givenListOfImages_whenInspectImage_thenMustReturnObject() {
+
+ //given
+ List images = dockerClient.listImagesCmd().exec();
+ Image image = images.get(0);
+
+ //when
+ InspectImageResponse imageResponse
+ = dockerClient.inspectImageCmd(image.getId()).exec();
+
+ //then
+ assertThat(imageResponse.getId(), is(image.getId()));
+ }
+
+ @Test
+ public void givenListOfImages_whenTagImage_thenListMustIncrement() {
+
+ //given
+ List images = dockerClient.listImagesCmd().exec();
+ Image image = images.get(0);
+
+ //when
+ dockerClient.tagImageCmd(image.getId(), "baeldung/alpine", "3.6.v2").exec();
+
+ //then
+ List imagesNow = dockerClient.listImagesCmd().exec();
+ assertThat(imagesNow.size(), is(greaterThan(images.size())));
+ }
+
+ public void pushingAnImage() throws InterruptedException {
+
+ dockerClient.pushImageCmd("baeldung/alpine")
+ .withTag("3.6.v2")
+ .exec(new PushImageResultCallback())
+ .awaitCompletion(90, TimeUnit.SECONDS);
+ }
+
+ @Test
+ public void whenPullingImage_thenImageListNotEmpty() throws InterruptedException {
+
+ //when
+ dockerClient.pullImageCmd("alpine")
+ .withTag("latest")
+ .exec(new PullImageResultCallback())
+ .awaitCompletion(30, TimeUnit.SECONDS);
+
+ //then
+ List images = dockerClient.listImagesCmd().exec();
+ assertThat(images.size(), is(not(0)));
+ }
+
+ @Test
+ public void whenRemovingImage_thenImageListDecrease() {
+
+ //when
+ List images = dockerClient.listImagesCmd().exec();
+ Image image = images.get(0);
+ dockerClient.removeImageCmd(image.getId()).exec();
+
+ //then
+ List imagesNow = dockerClient.listImagesCmd().exec();
+ assertThat(imagesNow.size(), is(lessThan(images.size())));
+ }
+
+ @Test
+ public void whenSearchingImage_thenMustReturn25Items() {
+
+ //when
+ List items = dockerClient.searchImagesCmd("Java").exec();
+
+ //then
+ assertThat(items.size(), is(25));
+ }
+}
diff --git a/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java
new file mode 100644
index 0000000000..2031a3ebb4
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java
@@ -0,0 +1,91 @@
+package com.baeldung.dockerapi;
+
+import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.command.CreateNetworkResponse;
+import com.github.dockerjava.api.model.Network;
+import com.github.dockerjava.api.model.Network.Ipam;
+import com.github.dockerjava.core.DockerClientBuilder;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.List;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.core.Is.is;
+
+public class NetworkLiveTest {
+
+ private static DockerClient dockerClient;
+
+ @BeforeClass
+ public static void setup() {
+ dockerClient = DockerClientBuilder.getInstance().build();
+ }
+
+ @Test
+ public void whenListingNetworks_thenSizeMustBeGreaterThanZero() {
+
+ //when
+ List networks = dockerClient.listNetworksCmd().exec();
+
+ //then
+ assertThat(networks.size(), is(greaterThan(0)));
+ }
+
+ @Test
+ public void whenCreatingNetwork_thenRetrieveResponse() {
+
+ //when
+ CreateNetworkResponse networkResponse
+ = dockerClient.createNetworkCmd()
+ .withName("baeldungDefault")
+ .withDriver("bridge").exec();
+
+ //then
+ assertThat(networkResponse, is(not(null)));
+ }
+
+ @Test
+ public void whenCreatingAdvanceNetwork_thenRetrieveResponse() {
+
+ //when
+ CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd()
+ .withName("baeldungAdvanced")
+ .withIpam(new Ipam()
+ .withConfig(new Ipam.Config()
+ .withSubnet("172.36.0.0/16")
+ .withIpRange("172.36.5.0/24")))
+ .withDriver("bridge").exec();
+
+ //then
+ assertThat(networkResponse, is(not(null)));
+ }
+
+ @Test
+ public void whenInspectingNetwork_thenSizeMustBeGreaterThanZero() {
+
+ //when
+ String networkName = "bridge";
+ Network network
+ = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec();
+
+ //then
+ assertThat(network.getName(), is(networkName));
+ }
+
+ @Test
+ public void whenCreatingNetwork_thenRemove() throws InterruptedException {
+
+ //when
+ CreateNetworkResponse networkResponse
+ = dockerClient.createNetworkCmd()
+ .withName("baeldungDefault")
+ .withDriver("bridge").exec();
+
+ //then
+ Thread.sleep(4000);
+ dockerClient.removeNetworkCmd(networkResponse.getId()).exec();
+ }
+}
diff --git a/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java
new file mode 100644
index 0000000000..060af0728c
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java
@@ -0,0 +1,86 @@
+package com.baeldung.dockerapi;
+
+import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.command.CreateVolumeResponse;
+import com.github.dockerjava.api.command.InspectVolumeResponse;
+import com.github.dockerjava.api.command.ListVolumesResponse;
+import com.github.dockerjava.core.DockerClientBuilder;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.List;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.core.Is.is;
+
+public class VolumeLiveTest {
+
+ private static DockerClient dockerClient;
+
+ @BeforeClass
+ public static void setup() {
+ dockerClient = DockerClientBuilder.getInstance().build();
+ }
+
+ @Test
+ public void whenListingVolumes_thenSizeMustBeGreaterThanZero() {
+
+ //when
+ ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec();
+
+ //then
+ List volumes = volumesResponse.getVolumes();
+ assertThat(volumes.size(), is(greaterThan(0)));
+ }
+
+ @Test
+ public void givenVolumes_whenInspectingVolume_thenReturnNonNullResponse() {
+
+ //given
+ ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec();
+ List volumes = volumesResponse.getVolumes();
+ InspectVolumeResponse volume = volumes.get(0);
+
+ //when
+ InspectVolumeResponse volumeResponse
+ = dockerClient.inspectVolumeCmd(volume.getName()).exec();
+
+ //then
+ assertThat(volumeResponse, is(not(null)));
+ }
+
+ @Test
+ public void whenCreatingUnnamedVolume_thenGetVolumeId() {
+
+ //when
+ CreateVolumeResponse unnamedVolume = dockerClient.createVolumeCmd().exec();
+
+ //then
+ assertThat(unnamedVolume.getName(), is(not(null)));
+ }
+
+ @Test
+ public void whenCreatingNamedVolume_thenGetVolumeId() {
+
+ //when
+ CreateVolumeResponse namedVolume
+ = dockerClient.createVolumeCmd().withName("myNamedVolume").exec();
+
+ //then
+ assertThat(namedVolume.getName(), is(not(null)));
+ }
+
+ @Test
+ public void whenGettingNamedVolume_thenRemove() throws InterruptedException {
+
+ //when
+ CreateVolumeResponse namedVolume
+ = dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec();
+
+ //then
+ Thread.sleep(4000);
+ dockerClient.removeVolumeCmd(namedVolume.getName()).exec();
+ }
+}
diff --git a/libraries/src/test/resources/dockerapi/Dockerfile b/libraries/src/test/resources/dockerapi/Dockerfile
new file mode 100644
index 0000000000..f9ad47f032
--- /dev/null
+++ b/libraries/src/test/resources/dockerapi/Dockerfile
@@ -0,0 +1,8 @@
+FROM alpine:3.6
+
+RUN apk --update add git openssh && \
+ rm -rf /var/lib/apt/lists/* && \
+ rm /var/cache/apk/*
+
+ENTRYPOINT ["git"]
+CMD ["--help"]
\ No newline at end of file
diff --git a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java
index 826e06d598..b76dc40ba0 100644
--- a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java
+++ b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java
@@ -1,27 +1,40 @@
package com.baeldung.metrics.micrometer;
-import com.netflix.spectator.atlas.AtlasConfig;
+import static org.hamcrest.CoreMatchers.allOf;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.collection.IsMapContaining.hasEntry;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
import io.micrometer.atlas.AtlasMeterRegistry;
-import io.micrometer.core.instrument.*;
+import io.micrometer.core.instrument.Clock;
+import io.micrometer.core.instrument.Counter;
+import io.micrometer.core.instrument.DistributionSummary;
+import io.micrometer.core.instrument.Gauge;
+import io.micrometer.core.instrument.LongTaskTimer;
+import io.micrometer.core.instrument.Measurement;
+import io.micrometer.core.instrument.Meter.Type;
+import io.micrometer.core.instrument.MeterRegistry;
+import io.micrometer.core.instrument.Metrics;
+import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.micrometer.core.instrument.stats.hist.Histogram;
import io.micrometer.core.instrument.stats.quantile.WindowSketchQuantiles;
-import org.junit.Before;
-import org.junit.Test;
import java.time.Duration;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
-import static io.micrometer.core.instrument.Meter.Type;
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.collection.IsMapContaining.hasEntry;
-import static org.hamcrest.core.IsCollectionContaining.hasItems;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.netflix.spectator.atlas.AtlasConfig;
/**
* @author aiet
@@ -135,15 +148,15 @@ public class MicrometerAtlasTest {
Timer timer = registry.timer("app.event");
timer.record(() -> {
try {
- TimeUnit.MILLISECONDS.sleep(1500);
+ TimeUnit.MILLISECONDS.sleep(15);
} catch (InterruptedException ignored) {
}
});
- timer.record(3000, TimeUnit.MILLISECONDS);
+ timer.record(30, TimeUnit.MILLISECONDS);
assertTrue(2 == timer.count());
- assertTrue(4510 > timer.totalTime(TimeUnit.MILLISECONDS) && 4500 <= timer.totalTime(TimeUnit.MILLISECONDS));
+ assertTrue(50 > timer.totalTime(TimeUnit.MILLISECONDS) && 45 <= timer.totalTime(TimeUnit.MILLISECONDS));
}
@Test
@@ -155,12 +168,12 @@ public class MicrometerAtlasTest {
long currentTaskId = longTaskTimer.start();
try {
- TimeUnit.SECONDS.sleep(2);
+ TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException ignored) {
}
long timeElapsed = longTaskTimer.stop(currentTaskId);
- assertTrue(timeElapsed / (int) 1e9 == 2);
+ assertTrue(timeElapsed / (int) 1e6 == 2);
}
@Test
diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java
index 99009f8d84..237092b1c3 100644
--- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java
+++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java
@@ -1,5 +1,19 @@
package com.baeldung.metrics.servo;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static java.util.stream.Collectors.toMap;
+import static org.hamcrest.Matchers.allOf;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.hasEntry;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+import java.util.Map;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
import com.netflix.servo.monitor.BasicCounter;
import com.netflix.servo.monitor.BasicGauge;
import com.netflix.servo.monitor.BasicInformational;
@@ -17,18 +31,6 @@ import com.netflix.servo.monitor.StatsTimer;
import com.netflix.servo.monitor.StepCounter;
import com.netflix.servo.monitor.Stopwatch;
import com.netflix.servo.stats.StatsConfig;
-import org.junit.Ignore;
-import org.junit.Test;
-
-import java.util.Map;
-
-import static java.util.concurrent.TimeUnit.SECONDS;
-import static java.util.stream.Collectors.toMap;
-import static org.hamcrest.Matchers.allOf;
-import static org.hamcrest.Matchers.containsInAnyOrder;
-import static org.hamcrest.Matchers.hasEntry;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
public class MetricTypeTest {
@@ -104,17 +106,18 @@ public class MetricTypeTest {
public void givenTimer_whenExecuteTask_thenTimerUpdated() throws Exception {
BasicTimer timer = new BasicTimer(MonitorConfig
.builder("test")
- .build(), SECONDS);
+ .build(), MILLISECONDS);
Stopwatch stopwatch = timer.start();
- SECONDS.sleep(1);
- timer.record(2, SECONDS);
+ MILLISECONDS.sleep(1);
+ timer.record(2, MILLISECONDS);
stopwatch.stop();
- assertEquals("timer should count 1 second", 1, timer
+ assertEquals("timer should count 1 millisecond", 1, timer
.getValue()
.intValue());
- assertEquals("timer should count 3 seconds in total", 3.0, timer.getTotalTime(), 0.01);
+ assertEquals("timer should count 3 millisecond in total", 3, timer.getTotalTime()
+ .intValue());
assertEquals("timer should record 2 updates", 2, timer
.getCount()
.intValue());
@@ -158,6 +161,7 @@ public class MetricTypeTest {
}
@Test
+ //==
public void givenStatsTimer_whenExecuteTask_thenStatsCalculated() throws Exception {
System.setProperty("netflix.servo", "1000");
StatsTimer timer = new StatsTimer(MonitorConfig
@@ -171,20 +175,20 @@ public class MetricTypeTest {
.withPublishMean(true)
.withPublishStdDev(true)
.withPublishVariance(true)
- .build(), SECONDS);
+ .build(), MILLISECONDS);
Stopwatch stopwatch = timer.start();
- SECONDS.sleep(1);
- timer.record(3, SECONDS);
+ MILLISECONDS.sleep(1);
+ timer.record(3, MILLISECONDS);
stopwatch.stop();
stopwatch = timer.start();
- timer.record(6, SECONDS);
- SECONDS.sleep(2);
+ timer.record(6, MILLISECONDS);
+ MILLISECONDS.sleep(2);
stopwatch.stop();
- assertEquals("timer should count 12 seconds in total", 12, timer.getTotalTime());
- assertEquals("timer should count 12 seconds in total", 12, timer.getTotalMeasurement());
+ assertEquals("timer should count 12 milliseconds in total", 12, timer.getTotalTime());
+ assertEquals("timer should count 12 milliseconds in total", 12, timer.getTotalMeasurement());
assertEquals("timer should record 4 updates", 4, timer.getCount());
assertEquals("stats timer value time-cost/update should be 2", 3, timer
.getValue()
diff --git a/flyway/flyway-callbacks/.gitignore b/mvn-wrapper/.gitignore
similarity index 100%
rename from flyway/flyway-callbacks/.gitignore
rename to mvn-wrapper/.gitignore
diff --git a/mvn-wrapper/.mvn/wrapper/maven-wrapper.jar b/mvn-wrapper/.mvn/wrapper/maven-wrapper.jar
new file mode 100755
index 0000000000..f775b1c04c
Binary files /dev/null and b/mvn-wrapper/.mvn/wrapper/maven-wrapper.jar differ
diff --git a/mvn-wrapper/.mvn/wrapper/maven-wrapper.properties b/mvn-wrapper/.mvn/wrapper/maven-wrapper.properties
new file mode 100755
index 0000000000..a447c9fa81
--- /dev/null
+++ b/mvn-wrapper/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1 @@
+distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip
\ No newline at end of file
diff --git a/mvn-wrapper/README.md b/mvn-wrapper/README.md
new file mode 100644
index 0000000000..bd299d41ed
--- /dev/null
+++ b/mvn-wrapper/README.md
@@ -0,0 +1,22 @@
+Setting up the Maven Wrapper on an Application
+==============================================
+
+This is the code that shows the configurations of maven wrapper on a SpringBoot project.
+
+### Requirements
+
+- Maven
+- JDK 7
+
+### Running
+
+To build and start the server simply type
+
+```bash
+$ ./mvn clean install
+$ ./mvn spring-boot:run
+```
+
+Now with default configurations it will be available at: [http://localhost:8080](http://localhost:8080)
+
+Enjoy it :)
\ No newline at end of file
diff --git a/mvn-wrapper/mvnw b/mvn-wrapper/mvnw
new file mode 100755
index 0000000000..e96ccd5fbb
--- /dev/null
+++ b/mvn-wrapper/mvnw
@@ -0,0 +1,227 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Maven2 Start Up Batch script
+#
+# Required ENV vars:
+# ------------------
+# JAVA_HOME - location of a JDK home dir
+#
+# Optional ENV vars
+# -----------------
+# M2_HOME - location of maven2's installed home dir
+# MAVEN_OPTS - parameters passed to the Java VM when running Maven
+# e.g. to debug Maven itself, use
+# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+# ----------------------------------------------------------------------------
+
+if [ -z "$MAVEN_SKIP_RC" ] ; then
+
+ if [ -f /etc/mavenrc ] ; then
+ . /etc/mavenrc
+ fi
+
+ if [ -f "$HOME/.mavenrc" ] ; then
+ . "$HOME/.mavenrc"
+ fi
+
+fi
+
+# OS specific support. $var _must_ be set to either true or false.
+cygwin=false;
+darwin=false;
+mingw=false
+case "`uname`" in
+ CYGWIN*) cygwin=true ;;
+ MINGW*) mingw=true;;
+ Darwin*) darwin=true
+ # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
+ # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
+ if [ -z "$JAVA_HOME" ]; then
+ if [ -x "/usr/libexec/java_home" ]; then
+ export JAVA_HOME="`/usr/libexec/java_home`"
+ else
+ export JAVA_HOME="/Library/Java/Home"
+ fi
+ fi
+ ;;
+esac
+
+if [ -z "$JAVA_HOME" ] ; then
+ if [ -r /etc/gentoo-release ] ; then
+ JAVA_HOME=`java-config --jre-home`
+ fi
+fi
+
+if [ -z "$M2_HOME" ] ; then
+ ## resolve links - $0 may be a link to maven's home
+ PRG="$0"
+
+ # need this for relative symlinks
+ while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG="`dirname "$PRG"`/$link"
+ fi
+ done
+
+ saveddir=`pwd`
+
+ M2_HOME=`dirname "$PRG"`/..
+
+ # make it fully qualified
+ M2_HOME=`cd "$M2_HOME" && pwd`
+
+ cd "$saveddir"
+ # echo Using m2 at $M2_HOME
+fi
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched
+if $cygwin ; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME=`cygpath --unix "$M2_HOME"`
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+ [ -n "$CLASSPATH" ] &&
+ CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
+fi
+
+# For Mingw, ensure paths are in UNIX format before anything is touched
+if $mingw ; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME="`(cd "$M2_HOME"; pwd)`"
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
+ # TODO classpath?
+fi
+
+if [ -z "$JAVA_HOME" ]; then
+ javaExecutable="`which javac`"
+ if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
+ # readlink(1) is not available as standard on Solaris 10.
+ readLink=`which readlink`
+ if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
+ if $darwin ; then
+ javaHome="`dirname \"$javaExecutable\"`"
+ javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
+ else
+ javaExecutable="`readlink -f \"$javaExecutable\"`"
+ fi
+ javaHome="`dirname \"$javaExecutable\"`"
+ javaHome=`expr "$javaHome" : '\(.*\)/bin'`
+ JAVA_HOME="$javaHome"
+ export JAVA_HOME
+ fi
+ fi
+fi
+
+if [ -z "$JAVACMD" ] ; then
+ if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ else
+ JAVACMD="`which java`"
+ fi
+fi
+
+if [ ! -x "$JAVACMD" ] ; then
+ echo "Error: JAVA_HOME is not defined correctly." >&2
+ echo " We cannot execute $JAVACMD" >&2
+ exit 1
+fi
+
+if [ -z "$JAVA_HOME" ] ; then
+ echo "Warning: JAVA_HOME environment variable is not set."
+fi
+
+CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
+
+# traverses directory structure from process work directory to filesystem root
+# first directory with .mvn subdirectory is considered project base directory
+find_maven_basedir() {
+
+ if [ -z "$1" ]
+ then
+ echo "Path not specified to find_maven_basedir"
+ return 1
+ fi
+
+ basedir="$1"
+ wdir="$1"
+ while [ "$wdir" != '/' ] ; do
+ if [ -d "$wdir"/.mvn ] ; then
+ basedir=$wdir
+ break
+ fi
+ # workaround for JBEAP-8937 (on Solaris 10/Sparc)
+ if [ -d "${wdir}" ]; then
+ wdir=`cd "$wdir/.."; pwd`
+ fi
+ # end of workaround
+ done
+ echo "${basedir}"
+}
+
+# concatenates all lines of a file
+concat_lines() {
+ if [ -f "$1" ]; then
+ echo "$(tr -s '\n' ' ' < "$1")"
+ fi
+}
+
+BASE_DIR=`find_maven_basedir "$(pwd)"`
+if [ -z "$BASE_DIR" ]; then
+ exit 1;
+fi
+
+export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
+if [ "$MVNW_VERBOSE" = true ]; then
+ echo $MAVEN_PROJECTBASEDIR
+fi
+MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME=`cygpath --path --windows "$M2_HOME"`
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
+ [ -n "$CLASSPATH" ] &&
+ CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
+ [ -n "$MAVEN_PROJECTBASEDIR" ] &&
+ MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
+fi
+
+WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+exec "$JAVACMD" \
+ $MAVEN_OPTS \
+ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
+ "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
+ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
diff --git a/mvn-wrapper/mvnw.cmd b/mvn-wrapper/mvnw.cmd
new file mode 100755
index 0000000000..4f0b068a03
--- /dev/null
+++ b/mvn-wrapper/mvnw.cmd
@@ -0,0 +1,145 @@
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements. See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership. The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License. You may obtain a copy of the License at
+@REM
+@REM http://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied. See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Maven2 Start Up Batch script
+@REM
+@REM Required ENV vars:
+@REM JAVA_HOME - location of a JDK home dir
+@REM
+@REM Optional ENV vars
+@REM M2_HOME - location of maven2's installed home dir
+@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
+@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
+@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
+@REM e.g. to debug Maven itself, use
+@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+@REM ----------------------------------------------------------------------------
+
+@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
+@echo off
+@REM set title of command window
+title %0
+@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
+@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
+
+@REM set %HOME% to equivalent of $HOME
+if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
+
+@REM Execute a user defined script before this one
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
+@REM check for pre script, once with legacy .bat ending and once with .cmd ending
+if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
+if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
+:skipRcPre
+
+@setlocal
+
+set ERROR_CODE=0
+
+@REM To isolate internal variables from possible post scripts, we use another setlocal
+@setlocal
+
+@REM ==== START VALIDATION ====
+if not "%JAVA_HOME%" == "" goto OkJHome
+
+echo.
+echo Error: JAVA_HOME not found in your environment. >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+:OkJHome
+if exist "%JAVA_HOME%\bin\java.exe" goto init
+
+echo.
+echo Error: JAVA_HOME is set to an invalid directory. >&2
+echo JAVA_HOME = "%JAVA_HOME%" >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+@REM ==== END VALIDATION ====
+
+:init
+
+@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
+@REM Fallback to current working directory if not found.
+
+set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
+IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
+
+set EXEC_DIR=%CD%
+set WDIR=%EXEC_DIR%
+:findBaseDir
+IF EXIST "%WDIR%"\.mvn goto baseDirFound
+cd ..
+IF "%WDIR%"=="%CD%" goto baseDirNotFound
+set WDIR=%CD%
+goto findBaseDir
+
+:baseDirFound
+set MAVEN_PROJECTBASEDIR=%WDIR%
+cd "%EXEC_DIR%"
+goto endDetectBaseDir
+
+:baseDirNotFound
+set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
+cd "%EXEC_DIR%"
+
+:endDetectBaseDir
+
+IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
+
+@setlocal EnableExtensions EnableDelayedExpansion
+for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
+@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
+
+:endReadAdditionalConfig
+
+SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
+
+set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
+set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
+if ERRORLEVEL 1 goto error
+goto end
+
+:error
+set ERROR_CODE=1
+
+:end
+@endlocal & set ERROR_CODE=%ERROR_CODE%
+
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
+@REM check for post script, once with legacy .bat ending and once with .cmd ending
+if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
+if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
+:skipRcPost
+
+@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
+if "%MAVEN_BATCH_PAUSE%" == "on" pause
+
+if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
+
+exit /B %ERROR_CODE%
diff --git a/mvn-wrapper/pom.xml b/mvn-wrapper/pom.xml
new file mode 100644
index 0000000000..209c4b9403
--- /dev/null
+++ b/mvn-wrapper/pom.xml
@@ -0,0 +1,45 @@
+
+
+ 4.0.0
+
+ mvn-wrapper
+ 0.0.1-SNAPSHOT
+ jar
+
+ mvn-wrapper
+ Setting up the Maven Wrapper
+
+
+ parent-boot-5
+ com.baeldung
+ 0.0.1-SNAPSHOT
+ ../parent-boot-5
+
+
+
+ UTF-8
+ UTF-8
+ 1.8
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
diff --git a/mvn-wrapper/src/main/java/com/baeldung/MvnWrapperApplication.java b/mvn-wrapper/src/main/java/com/baeldung/MvnWrapperApplication.java
new file mode 100644
index 0000000000..3007d24ed0
--- /dev/null
+++ b/mvn-wrapper/src/main/java/com/baeldung/MvnWrapperApplication.java
@@ -0,0 +1,11 @@
+package com.baeldung;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class MvnWrapperApplication {
+ public static void main(String[] args) {
+ SpringApplication.run(MvnWrapperApplication.class, args);
+ }
+}
diff --git a/spring-rest-docs/src/main/resources/application.properties b/mvn-wrapper/src/main/resources/application.properties
similarity index 100%
rename from spring-rest-docs/src/main/resources/application.properties
rename to mvn-wrapper/src/main/resources/application.properties
diff --git a/parent-boot-4/README.md b/parent-boot-4/README.md
deleted file mode 100644
index ff12555376..0000000000
--- a/parent-boot-4/README.md
+++ /dev/null
@@ -1 +0,0 @@
-## Relevant articles:
diff --git a/parent-boot-4/pom.xml b/parent-boot-4/pom.xml
deleted file mode 100644
index 51ef9f4854..0000000000
--- a/parent-boot-4/pom.xml
+++ /dev/null
@@ -1,81 +0,0 @@
-
- 4.0.0
- com.baeldung
- parent-boot-4
- 0.0.1-SNAPSHOT
- pom
- Parent Boot 4
- Parent for all spring boot 1.4 modules
-
-
- UTF-8
- UTF-8
- 1.8
- 3.0.1
-
- 2.19.1
- 3.7.0
-
-
-
- spring-boot-starter-parent
- org.springframework.boot
- 1.4.4.RELEASE
-
-
-
-
-
- junit
- junit
- test
-
-
- 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
- **/*LongRunningUnitTest.java
- **/*ManualTest.java
- **/JdbcTest.java
- **/*LiveTest.java
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
-
- 1.8
-
-
-
-
-
-
\ No newline at end of file
diff --git a/parent-boot-5/pom.xml b/parent-boot-5/pom.xml
index 6b1445fcdd..55ac0957ff 100644
--- a/parent-boot-5/pom.xml
+++ b/parent-boot-5/pom.xml
@@ -12,16 +12,16 @@
UTF-8
UTF-8
1.8
- 3.0.1
+ 3.0.6
- 2.19.1
+ 2.20.1
3.7.0
spring-boot-starter-parent
org.springframework.boot
- 1.5.3.RELEASE
+ 1.5.9.RELEASE
diff --git a/persistence-modules/java-cockroachdb/README.md b/persistence-modules/java-cockroachdb/README.md
new file mode 100644
index 0000000000..3bab6faa29
--- /dev/null
+++ b/persistence-modules/java-cockroachdb/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Guide to CockroachDB in Java](http://www.baeldung.com/cockroachdb-java)
diff --git a/persistence-modules/java-cockroachdb/pom.xml b/persistence-modules/java-cockroachdb/pom.xml
new file mode 100644
index 0000000000..2b6f9651bc
--- /dev/null
+++ b/persistence-modules/java-cockroachdb/pom.xml
@@ -0,0 +1,74 @@
+
+
+
+
+ parent-modules
+ com.baeldung
+ 1.0.0-SNAPSHOT
+ ../../
+
+
+ 4.0.0
+
+ com.baeldung
+ java-cockroachdb
+ 1.0-SNAPSHOT
+
+
+ 42.1.4
+
+
+
+
+ org.postgresql
+ postgresql
+ ${postgresql.version}
+
+
+
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*ManualTest.java
+
+
+ **/*IntegrationTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
+
+
+
+ Central
+ Central
+ http://repo1.maven.org/maven2/
+ default
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/domain/Article.java b/persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/domain/Article.java
new file mode 100644
index 0000000000..dcc9dfb5b7
--- /dev/null
+++ b/persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/domain/Article.java
@@ -0,0 +1,43 @@
+package com.baeldung.cockroachdb.domain;
+
+import java.util.UUID;
+
+public class Article {
+
+ private UUID id;
+
+ private String title;
+
+ private String author;
+
+ public Article(UUID id, String title, String author) {
+ this.id = id;
+ this.title = title;
+ this.author = author;
+ }
+
+ public UUID getId() {
+ return id;
+ }
+
+ public void setId(UUID id) {
+ this.id = 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/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/repository/ArticleRepository.java b/persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/repository/ArticleRepository.java
new file mode 100644
index 0000000000..a37c19e397
--- /dev/null
+++ b/persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/repository/ArticleRepository.java
@@ -0,0 +1,172 @@
+package com.baeldung.cockroachdb.repository;
+
+import com.baeldung.cockroachdb.domain.Article;
+
+import java.sql.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+/**
+ * Repository for the articles table related operations
+ */
+public class ArticleRepository {
+
+ private static final String TABLE_NAME = "articles";
+ private Connection connection;
+
+ public ArticleRepository(Connection connection) {
+ this.connection = connection;
+ }
+
+ /**
+ * Creates the articles table.
+ */
+ public void createTable() throws SQLException {
+ StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS ").append(TABLE_NAME)
+ .append("(id uuid PRIMARY KEY, ")
+ .append("title string,")
+ .append("author string)");
+
+ final String query = sb.toString();
+ Statement stmt = connection.createStatement();
+ stmt.execute(query);
+ }
+
+ /**
+ * Alter the articles table adding a column
+ *
+ * @param columnName Column name of the additional column
+ * @param columnType Column type of the additional column
+ * @throws SQLException
+ */
+ public void alterTable(String columnName, String columnType) throws SQLException {
+ StringBuilder sb = new StringBuilder("ALTER TABLE ").append(TABLE_NAME)
+ .append(" ADD ")
+ .append(columnName)
+ .append(" ")
+ .append(columnType);
+
+ final String query = sb.toString();
+ Statement stmt = connection.createStatement();
+ stmt.execute(query);
+ }
+
+ /**
+ * Insert a new article in the articles table
+ *
+ * @param article New article to insert
+ * @throws SQLException
+ */
+ public void insertArticle(Article article) throws SQLException {
+ StringBuilder sb = new StringBuilder("INSERT INTO ").append(TABLE_NAME)
+ .append("(id, title, author) ")
+ .append("VALUES (?,?,?)");
+
+ final String query = sb.toString();
+ PreparedStatement preparedStatement = connection.prepareStatement(query);
+ preparedStatement.setString(1, article.getId().toString());
+ preparedStatement.setString(2, article.getTitle());
+ preparedStatement.setString(3, article.getAuthor());
+ preparedStatement.execute();
+ }
+
+ /**
+ * Select article by Title
+ *
+ * @param title title of the article to retrieve
+ * @return article with the given title
+ * @throws SQLException
+ */
+ public Article selectByTitle(String title) throws SQLException {
+ StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME)
+ .append(" WHERE title = ?");
+
+ final String query = sb.toString();
+ PreparedStatement preparedStatement = connection.prepareStatement(query);
+ preparedStatement.setString(1, title);
+
+ try (ResultSet rs = preparedStatement.executeQuery()) {
+
+ List articles = new ArrayList<>();
+
+ while (rs.next()) {
+ Article article = new Article(
+ UUID.fromString(rs.getString("id")),
+ rs.getString("title"),
+ rs.getString("author")
+ );
+ articles.add(article);
+ }
+ return articles.get(0);
+ }
+
+ }
+
+ /**
+ * Select all the articles
+ *
+ * @return list of all articles
+ * @throws SQLException
+ */
+ public List selectAll() throws SQLException {
+ StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME);
+
+ final String query = sb.toString();
+ PreparedStatement preparedStatement = connection.prepareStatement(query);
+ try (ResultSet rs = preparedStatement.executeQuery()) {
+
+ List articles = new ArrayList<>();
+
+ while (rs.next()) {
+ Article article = new Article(
+ UUID.fromString(rs.getString("id")),
+ rs.getString("title"),
+ rs.getString("author")
+ );
+ articles.add(article);
+ }
+ return articles;
+ }
+ }
+
+ /**
+ * Delete article by title
+ *
+ * @param title title of the article to delete
+ * @throws SQLException
+ */
+ public void deleteArticleByTitle(String title) throws SQLException {
+ StringBuilder sb = new StringBuilder("DELETE FROM ").append(TABLE_NAME)
+ .append(" WHERE title = ?");
+
+ final String query = sb.toString();
+ PreparedStatement preparedStatement = connection.prepareStatement(query);
+ preparedStatement.setString(1, title);
+ preparedStatement.execute();
+ }
+
+ /**
+ * Delete all rows in the table
+ *
+ * @throws SQLException
+ */
+ public void truncateTable() throws SQLException {
+ StringBuilder sb = new StringBuilder("TRUNCATE TABLE ").append(TABLE_NAME);
+
+ final String query = sb.toString();
+ Statement stmt = connection.createStatement();
+ stmt.execute(query);
+ }
+
+ /**
+ * Delete table
+ */
+ public void deleteTable() throws SQLException {
+ StringBuilder sb = new StringBuilder("DROP TABLE IF EXISTS ").append(TABLE_NAME);
+
+ final String query = sb.toString();
+ Statement stmt = connection.createStatement();
+ stmt.execute(query);
+ }
+}
diff --git a/persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryIntegrationTest.java b/persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryIntegrationTest.java
new file mode 100644
index 0000000000..9eb00b3651
--- /dev/null
+++ b/persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryIntegrationTest.java
@@ -0,0 +1,208 @@
+package com.baeldung.cockroachdb;
+
+import com.baeldung.cockroachdb.domain.Article;
+import com.baeldung.cockroachdb.repository.ArticleRepository;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.postgresql.util.PSQLException;
+
+import java.sql.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class ArticleRepositoryIntegrationTest {
+
+ private static final String TABLE_NAME = "articles";
+
+ private Connection con;
+ private ArticleRepository articleRepository;
+
+ @Before
+ public void connect() throws Exception {
+ Class.forName("org.postgresql.Driver");
+ con = DriverManager.getConnection("jdbc:postgresql://localhost:26257/testdb", "user17", "qwerty");
+
+ articleRepository = new ArticleRepository(con);
+ }
+
+ @Test
+ public void whenCreatingTable_thenCreatedCorrectly() throws Exception {
+ articleRepository.deleteTable();
+ articleRepository.createTable();
+
+ PreparedStatement preparedStatement = con.prepareStatement("SHOW TABLES");
+ ResultSet resultSet = preparedStatement.executeQuery();
+ List tables = new ArrayList<>();
+ while (resultSet.next()) {
+ tables.add(resultSet.getString("Table"));
+ }
+
+ assertTrue(tables.stream().anyMatch(t -> t.equals(TABLE_NAME)));
+ }
+
+ @Test
+ public void whenAlteringTheTable_thenColumnAddedCorrectly() throws SQLException {
+ articleRepository.deleteTable();
+ articleRepository.createTable();
+
+ String columnName = "creationdate";
+ articleRepository.alterTable(columnName, "DATE");
+
+ String query = "SHOW COLUMNS FROM " + TABLE_NAME;
+ PreparedStatement preparedStatement = con.prepareStatement(query);
+ ResultSet resultSet = preparedStatement.executeQuery();
+ List columns = new ArrayList<>();
+ while (resultSet.next()) {
+ columns.add(resultSet.getString("Field"));
+ }
+
+ assertTrue(columns.stream().anyMatch(c -> c.equals(columnName)));
+ }
+
+ @Test
+ public void whenInsertingNewArticle_thenArticleExists() throws SQLException {
+ articleRepository.deleteTable();
+ articleRepository.createTable();
+
+ String title = "Guide to CockroachDB in Java";
+ String author = "baeldung";
+ Article article = new Article(UUID.randomUUID(), title, author);
+ articleRepository.insertArticle(article);
+
+ Article savedArticle = articleRepository.selectByTitle(title);
+ assertEquals(article.getTitle(), savedArticle.getTitle());
+ }
+
+ @Test
+ public void whenSelectingAllArticles_thenAllArticlesAreReturned() throws SQLException {
+ articleRepository.deleteTable();
+ articleRepository.createTable();
+
+ Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung");
+ articleRepository.insertArticle(article);
+
+ article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung");
+ articleRepository.insertArticle(article);
+
+ List savedArticles = articleRepository.selectAll();
+
+ assertEquals(2, savedArticles.size());
+ assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("Guide to CockroachDB in Java")));
+ assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("A Guide to MongoDB with Java")));
+ }
+
+ @Test
+ public void whenDeletingArticleByTtile_thenArticleIsDeleted() throws SQLException {
+ articleRepository.deleteTable();
+ articleRepository.createTable();
+
+ Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung");
+ articleRepository.insertArticle(article);
+
+ article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung");
+ articleRepository.insertArticle(article);
+
+ articleRepository.deleteArticleByTitle("A Guide to MongoDB with Java");
+
+ List savedArticles = articleRepository.selectAll();
+ assertEquals(1, savedArticles.size());
+ assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("Guide to CockroachDB in Java")));
+ assertFalse(savedArticles.stream().anyMatch(a -> a.getTitle().equals("A Guide to MongoDB with Java")));
+ }
+
+ @Test(expected = PSQLException.class)
+ public void whenDeletingATable_thenExceptionIfAccessed() throws SQLException {
+ articleRepository.createTable();
+ articleRepository.deleteTable();
+
+ StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME);
+
+ final String query = sb.toString();
+ PreparedStatement preparedStatement = con.prepareStatement(query);
+ preparedStatement.executeQuery();
+ }
+
+ @Test
+ public void whenTruncatingATable_thenEmptyTable() throws SQLException {
+ articleRepository.deleteTable();
+ articleRepository.createTable();
+
+ Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung");
+ articleRepository.insertArticle(article);
+
+ article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung");
+ articleRepository.insertArticle(article);
+
+ articleRepository.truncateTable();
+
+ List savedArticles = articleRepository.selectAll();
+ assertEquals(0, savedArticles.size());
+ }
+
+ @Test
+ public void whenInsertingTwoArticlesWithSamePrimaryKeyInASingleTransaction_thenRollback() throws SQLException {
+ articleRepository.deleteTable();
+ articleRepository.createTable();
+
+ try {
+ con.setAutoCommit(false);
+
+ UUID articleId = UUID.randomUUID();
+
+ Article article = new Article(articleId, "Guide to CockroachDB in Java", "baeldung");
+ articleRepository.insertArticle(article);
+
+ article = new Article(articleId, "A Guide to MongoDB with Java", "baeldung");
+ articleRepository.insertArticle(article);
+
+ con.commit();
+ } catch (Exception e) {
+ con.rollback();
+ } finally {
+ con.setAutoCommit(true);
+ }
+
+ List savedArticles = articleRepository.selectAll();
+ assertEquals(0, savedArticles.size());
+ }
+
+ @Test
+ public void whenInsertingTwoArticlesInASingleTransaction_thenInserted() throws SQLException {
+ articleRepository.deleteTable();
+ articleRepository.createTable();
+
+ try {
+ con.setAutoCommit(false);
+
+ Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung");
+ articleRepository.insertArticle(article);
+
+ article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung");
+ articleRepository.insertArticle(article);
+
+ con.commit();
+ } catch (Exception e) {
+ con.rollback();
+ } finally {
+ con.setAutoCommit(true);
+ }
+
+ List savedArticles = articleRepository.selectAll();
+ assertEquals(2, savedArticles.size());
+ assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("Guide to CockroachDB in Java")));
+ assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("A Guide to MongoDB with Java")));
+ }
+
+ @After
+ public void disconnect() throws SQLException {
+ articleRepository = null;
+ con.close();
+ con = null;
+ }
+}
diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryIntegrationTest.java
similarity index 95%
rename from persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java
rename to persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryIntegrationTest.java
index 1a7c28df6c..636f91cf8e 100644
--- a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java
+++ b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryIntegrationTest.java
@@ -14,13 +14,10 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
-/**
- * Created by adam.
- */
@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
-public class PersonsRepositoryTest {
+public class PersonsRepositoryIntegrationTest {
@Autowired
private PersonsRepository personsRepository;
diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml
index 88db38b2fc..86e952c0e4 100644
--- a/persistence-modules/spring-hibernate-5/pom.xml
+++ b/persistence-modules/spring-hibernate-5/pom.xml
@@ -179,7 +179,7 @@
- 4.3.10.RELEASE
+ 5.0.2.RELEASE
1.10.6.RELEASE
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java
new file mode 100644
index 0000000000..5fc932b256
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java
@@ -0,0 +1,39 @@
+package com.baeldung.hibernate.bootstrap;
+
+import com.baeldung.hibernate.bootstrap.model.TestEntity;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+public abstract class BarHibernateDAO {
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ public TestEntity findEntity(int id) {
+
+ return getCurrentSession().find(TestEntity.class, 1);
+ }
+
+ public void createEntity(TestEntity entity) {
+
+ getCurrentSession().save(entity);
+ }
+
+ public void createEntity(int id, String newDescription) {
+
+ TestEntity entity = findEntity(id);
+ entity.setDescription(newDescription);
+ getCurrentSession().save(entity);
+ }
+
+ public void deleteEntity(int id) {
+
+ TestEntity entity = findEntity(id);
+ getCurrentSession().delete(entity);
+ }
+
+ protected Session getCurrentSession() {
+ return sessionFactory.getCurrentSession();
+ }
+}
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java
new file mode 100644
index 0000000000..150e3778af
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java
@@ -0,0 +1,61 @@
+package com.baeldung.hibernate.bootstrap;
+
+import com.google.common.base.Preconditions;
+import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.core.env.Environment;
+import org.springframework.orm.hibernate5.HibernateTransactionManager;
+import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import javax.sql.DataSource;
+import java.util.Properties;
+
+@Configuration
+@EnableTransactionManagement
+@PropertySource({ "classpath:persistence-h2.properties" })
+public class HibernateConf {
+
+ @Autowired
+ private Environment env;
+
+ @Bean
+ public LocalSessionFactoryBean sessionFactory() {
+ final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
+ sessionFactory.setDataSource(dataSource());
+ sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.bootstrap.model" });
+ sessionFactory.setHibernateProperties(hibernateProperties());
+
+ return sessionFactory;
+ }
+
+ @Bean
+ public DataSource dataSource() {
+ final BasicDataSource dataSource = new BasicDataSource();
+ 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 hibernateTransactionManager() {
+ final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
+ transactionManager.setSessionFactory(sessionFactory().getObject());
+ return transactionManager;
+ }
+
+ 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"));
+
+ return hibernateProperties;
+ }
+}
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java
new file mode 100644
index 0000000000..b3e979478f
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java
@@ -0,0 +1,24 @@
+package com.baeldung.hibernate.bootstrap;
+
+import com.google.common.base.Preconditions;
+import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.core.env.Environment;
+import org.springframework.orm.hibernate5.HibernateTransactionManager;
+import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import javax.sql.DataSource;
+import java.util.Properties;
+
+@Configuration
+@EnableTransactionManagement
+@ImportResource({ "classpath:hibernate5Configuration.xml" })
+public class HibernateXMLConf {
+
+}
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java
new file mode 100644
index 0000000000..cae41db831
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java
@@ -0,0 +1,29 @@
+package com.baeldung.hibernate.bootstrap.model;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+public class TestEntity {
+
+ private int id;
+
+ private String description;
+
+ @Id
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+}
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
index 6f359054b6..5dace1f742 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
+++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
@@ -10,8 +10,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
-import org.springframework.orm.hibernate4.HibernateTransactionManager;
-import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
+import org.springframework.orm.hibernate5.HibernateTransactionManager;
+import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/hibernate5Configuration.xml b/persistence-modules/spring-hibernate-5/src/main/resources/hibernate5Configuration.xml
new file mode 100644
index 0000000000..cb6cf0aa5c
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/main/resources/hibernate5Configuration.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+ ${hibernate.hbm2ddl.auto}
+ ${hibernate.dialect}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties
index 915bc4317b..0325174b67 100644
--- a/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties
+++ b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties
@@ -2,6 +2,7 @@
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.eventGeneratedId=sa
+jdbc.user=sa
jdbc.pass=sa
# hibernate.X
diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java
new file mode 100644
index 0000000000..ffe82b7ced
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java
@@ -0,0 +1,38 @@
+package com.baeldung.hibernate.bootstrap;
+
+import com.baeldung.hibernate.bootstrap.model.TestEntity;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+import org.springframework.transaction.annotation.Transactional;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = { HibernateConf.class })
+@Transactional
+public class HibernateBootstrapIntegrationTest {
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ @Test
+ public void whenBootstrapHibernateSession_thenNoException() {
+
+ Session session = sessionFactory.getCurrentSession();
+
+ TestEntity newEntity = new TestEntity();
+ newEntity.setId(1);
+ session.save(newEntity);
+
+ TestEntity searchEntity = session.find(TestEntity.class, 1);
+
+ Assert.assertNotNull(searchEntity);
+ }
+
+}
diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java
new file mode 100644
index 0000000000..5b811ad576
--- /dev/null
+++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.hibernate.bootstrap;
+
+import com.baeldung.hibernate.bootstrap.model.TestEntity;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.transaction.annotation.Transactional;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = { HibernateXMLConf.class })
+@Transactional
+public class HibernateXMLBootstrapIntegrationTest {
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ @Test
+ public void whenBootstrapHibernateSession_thenNoException() {
+
+ Session session = sessionFactory.getCurrentSession();
+
+ TestEntity newEntity = new TestEntity();
+ newEntity.setId(1);
+ session.save(newEntity);
+
+ TestEntity searchEntity = session.find(TestEntity.class, 1);
+
+ Assert.assertNotNull(searchEntity);
+ }
+
+}
diff --git a/pom.xml b/pom.xml
index 8906b1c8d2..73f1b27f7e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -28,6 +28,7 @@
+ parent-boot-5
asm
atomix
apache-cayenne
@@ -85,6 +86,8 @@
jackson
vavr
+ java-lite
+ java-vavr-stream
javax-servlets
javaxval
jaxb
@@ -115,6 +118,7 @@
testing-modules/mockito-2
testing-modules/mocks
mustache
+ mvn-wrapper
noexception
orientdb
osgi
@@ -152,10 +156,13 @@
spring-boot
spring-boot-keycloak
spring-boot-bootstrap
+ spring-boot-admin
+ spring-boot-security
spring-cloud-data-flow
spring-cloud
spring-core
spring-cucumber
+ spring-ejb
spring-aop
persistence-modules/spring-data-cassandra
spring-data-couchbase-2
@@ -197,7 +204,6 @@
spring-protobuf
spring-quartz
spring-rest-angular
- spring-rest-docs
spring-rest-full
spring-rest-query-language
spring-rest
@@ -263,9 +269,9 @@
vertx-and-rxjava
saas
deeplearning4j
- spring-boot-admin
lucene
vraptor
+ persistence-modules/java-cockroachdb
diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java
index 712f07324c..bc59f72fd9 100644
--- a/rxjava/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java
+++ b/rxjava/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java
@@ -194,6 +194,7 @@ public class SchedulersLiveTest {
}
@Test
+ @Ignore
public void givenObservable_whenComputationScheduling_thenReturnThreadName() throws InterruptedException {
System.out.println("computation");
Observable.just("computation")
diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml
index 5d7cf0d7e5..e5b35de2f5 100644
--- a/spring-5-reactive/pom.xml
+++ b/spring-5-reactive/pom.xml
@@ -28,7 +28,7 @@
org.springframework.boot
- spring-boot-starter-web
+ spring-boot-starter-tomcat
org.springframework.boot
diff --git a/spring-5/src/main/java/com/baeldung/web/PathPatternController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/PathPatternController.java
similarity index 93%
rename from spring-5/src/main/java/com/baeldung/web/PathPatternController.java
rename to spring-5-reactive/src/main/java/com/baeldung/reactive/controller/PathPatternController.java
index 6fd972f2a4..f5a5d9e769 100644
--- a/spring-5/src/main/java/com/baeldung/web/PathPatternController.java
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/PathPatternController.java
@@ -1,4 +1,4 @@
-package com.baeldung.web;
+package com.baeldung.reactive.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/Actor.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/Actor.java
new file mode 100644
index 0000000000..ee06b94be7
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/Actor.java
@@ -0,0 +1,23 @@
+package com.baeldung.reactive.urlmatch;
+
+class Actor {
+ private String firstname;
+ private String lastname;
+
+ public Actor() {
+ }
+
+ public Actor(String firstname, String lastname) {
+ this.firstname = firstname;
+ this.lastname = lastname;
+ }
+
+ public String getFirstname() {
+ return firstname;
+ }
+
+ public String getLastname() {
+ return lastname;
+ }
+
+}
diff --git a/spring-5/src/main/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java
similarity index 98%
rename from spring-5/src/main/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctions.java
rename to spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java
index 2a6d04538c..78f40be57a 100644
--- a/spring-5/src/main/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctions.java
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java
@@ -1,4 +1,4 @@
-package com.baeldung.functional;
+package com.baeldung.reactive.urlmatch;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java
new file mode 100644
index 0000000000..0781230379
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java
@@ -0,0 +1,41 @@
+package com.baeldung.reactive.urlmatch;
+
+import org.springframework.core.io.buffer.DataBuffer;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.reactive.function.server.ServerRequest;
+import org.springframework.web.reactive.function.server.ServerResponse;
+import reactor.core.publisher.Mono;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+
+import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers;
+import static org.springframework.web.reactive.function.BodyExtractors.toFormData;
+import static org.springframework.web.reactive.function.BodyInserters.fromObject;
+import static org.springframework.web.reactive.function.server.ServerResponse.ok;
+
+public class FormHandler {
+
+ Mono handleLogin(ServerRequest request) {
+ return request.body(toFormData())
+ .map(MultiValueMap::toSingleValueMap)
+ .filter(formData -> "baeldung".equals(formData.get("user")))
+ .filter(formData -> "you_know_what_to_do".equals(formData.get("token")))
+ .flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class))
+ .switchIfEmpty(ServerResponse.badRequest()
+ .build());
+ }
+
+ Mono handleUpload(ServerRequest request) {
+ return request.body(toDataBuffers())
+ .collectList()
+ .flatMap(dataBuffers -> ok().body(fromObject(extractData(dataBuffers).toString())));
+ }
+
+ private AtomicLong extractData(List dataBuffers) {
+ AtomicLong atomicLong = new AtomicLong(0);
+ dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
+ .array().length));
+ return atomicLong;
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java
new file mode 100644
index 0000000000..2ea5420a2b
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java
@@ -0,0 +1,80 @@
+package com.baeldung.reactive.urlmatch;
+
+import static org.springframework.web.reactive.function.BodyInserters.fromObject;
+import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
+import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
+import static org.springframework.web.reactive.function.server.RequestPredicates.path;
+import static org.springframework.web.reactive.function.server.RouterFunctions.route;
+import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
+import static org.springframework.web.reactive.function.server.ServerResponse.ok;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import org.apache.catalina.Context;
+import org.apache.catalina.startup.Tomcat;
+import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
+import org.springframework.boot.web.server.WebServer;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.http.server.reactive.HttpHandler;
+import org.springframework.http.server.reactive.ServletHttpHandlerAdapter;
+import org.springframework.web.reactive.function.server.RouterFunction;
+import org.springframework.web.reactive.function.server.RouterFunctions;
+import org.springframework.web.reactive.function.server.ServerResponse;
+import org.springframework.web.server.WebHandler;
+import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
+
+import reactor.core.publisher.Flux;
+
+public class FunctionalWebApplication {
+
+ private static final Actor BRAD_PITT = new Actor("Brad", "Pitt");
+ private static final Actor TOM_HANKS = new Actor("Tom", "Hanks");
+ private static final List actors = new CopyOnWriteArrayList<>(Arrays.asList(BRAD_PITT, TOM_HANKS));
+
+ private RouterFunction routingFunction() {
+ FormHandler formHandler = new FormHandler();
+
+ RouterFunction restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
+ .doOnNext(actors::add)
+ .then(ok().build()));
+
+ return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
+ .andRoute(POST("/upload"), formHandler::handleUpload)
+ .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
+ .andNest(path("/actor"), restfulRouter)
+ .filter((request, next) -> {
+ System.out.println("Before handler invocation: " + request.path());
+ return next.handle(request);
+ });
+ }
+
+ WebServer start() throws Exception {
+ WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
+ HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
+ .filter(new IndexRewriteFilter())
+ .build();
+
+ Tomcat tomcat = new Tomcat();
+ tomcat.setHostname("localhost");
+ tomcat.setPort(9090);
+ Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
+ ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
+ Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
+ rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
+
+ TomcatWebServer server = new TomcatWebServer(tomcat);
+ server.start();
+ return server;
+
+ }
+
+ public static void main(String[] args) {
+ try {
+ new FunctionalWebApplication().start();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/IndexRewriteFilter.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/IndexRewriteFilter.java
new file mode 100644
index 0000000000..2eb252ed2b
--- /dev/null
+++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/IndexRewriteFilter.java
@@ -0,0 +1,27 @@
+package com.baeldung.reactive.urlmatch;
+
+import org.springframework.http.server.reactive.ServerHttpRequest;
+import org.springframework.web.server.ServerWebExchange;
+import org.springframework.web.server.WebFilter;
+import org.springframework.web.server.WebFilterChain;
+import reactor.core.publisher.Mono;
+
+class IndexRewriteFilter implements WebFilter {
+
+ @Override
+ public Mono filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
+ ServerHttpRequest request = serverWebExchange.getRequest();
+ if (request.getURI()
+ .getPath()
+ .equals("/")) {
+ return webFilterChain.filter(serverWebExchange.mutate()
+ .request(builder -> builder.method(request.getMethod())
+ .contextPath(request.getPath()
+ .toString())
+ .path("/test"))
+ .build());
+ }
+ return webFilterChain.filter(serverWebExchange);
+ }
+
+}
diff --git a/spring-5-reactive/src/main/resources/files/hello.txt b/spring-5-reactive/src/main/resources/files/hello.txt
new file mode 100644
index 0000000000..b6fc4c620b
--- /dev/null
+++ b/spring-5-reactive/src/main/resources/files/hello.txt
@@ -0,0 +1 @@
+hello
\ No newline at end of file
diff --git a/spring-5-reactive/src/main/resources/files/test/test.txt b/spring-5-reactive/src/main/resources/files/test/test.txt
new file mode 100644
index 0000000000..30d74d2584
--- /dev/null
+++ b/spring-5-reactive/src/main/resources/files/test/test.txt
@@ -0,0 +1 @@
+test
\ No newline at end of file
diff --git a/spring-5/src/test/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctionsTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java
similarity index 93%
rename from spring-5/src/test/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctionsTest.java
rename to spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java
index 7a38fa697f..21ba11616d 100644
--- a/spring-5/src/test/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctionsTest.java
+++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.functional;
+package com.baeldung.reactive.urlmatch;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -6,7 +6,9 @@ import org.junit.Test;
import org.springframework.boot.web.server.WebServer;
import org.springframework.test.web.reactive.server.WebTestClient;
-public class ExploreSpring5URLPatternUsingRouterFunctionsTest {
+import com.baeldung.reactive.urlmatch.ExploreSpring5URLPatternUsingRouterFunctions;
+
+public class ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest {
private static WebTestClient client;
private static WebServer server;
diff --git a/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java
similarity index 92%
rename from spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java
rename to spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java
index c2ed8ff071..9f31608ff7 100644
--- a/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java
+++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java
@@ -1,6 +1,5 @@
-package com.baeldung.web;
+package com.baeldung.reactive.urlmatch;
-import com.baeldung.Spring5Application;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -8,8 +7,11 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
+import com.baeldung.reactive.Spring5ReactiveApplication;
+import com.baeldung.reactive.controller.PathPatternController;
+
@RunWith(SpringRunner.class)
-@SpringBootTest(classes = Spring5Application.class)
+@SpringBootTest(classes = Spring5ReactiveApplication.class)
public class PathPatternsUsingHandlerMethodIntegrationTest {
private static WebTestClient client;
diff --git a/spring-5/README.md b/spring-5/README.md
index 400e343263..8249fe3813 100644
--- a/spring-5/README.md
+++ b/spring-5/README.md
@@ -12,4 +12,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans)
- [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config)
- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive)
-- [Spring 5 Testing with @EnabledIf Annotation](https://github.com/eugenp/tutorials/tree/master/spring-5)
+- [Spring 5 Testing with @EnabledIf Annotation](http://www.baeldung.com/sring-5-enabledif)
+- [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs)
diff --git a/spring-5/pom.xml b/spring-5/pom.xml
index 7acee1878f..4c2df68f1b 100644
--- a/spring-5/pom.xml
+++ b/spring-5/pom.xml
@@ -39,6 +39,10 @@
org.springframework.boot
spring-boot-starter-webflux
+
+ org.springframework.boot
+ spring-boot-starter-hateoas
+
org.springframework.boot
spring-boot-starter-actuator
@@ -139,6 +143,23 @@
${junit.platform.version}
test
+
+
+ org.springframework.restdocs
+ spring-restdocs-mockmvc
+ test
+
+
+ org.springframework.restdocs
+ spring-restdocs-webtestclient
+ test
+
+
+ org.springframework.restdocs
+ spring-restdocs-restassured
+ test
+
+
@@ -167,6 +188,29 @@
+
+ org.asciidoctor
+ asciidoctor-maven-plugin
+ ${asciidoctor-plugin.version}
+
+
+ generate-docs
+ package
+
+ process-asciidoc
+
+
+ html
+ book
+
+ ${snippetsDirectory}
+
+ src/docs/asciidocs
+ target/generated-docs
+
+
+
+