diff --git a/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceBase.java b/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceBase.java index e884c576c1..ec66621928 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceBase.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceBase.java @@ -1,22 +1,15 @@ package com.baeldung.algorithms.editdistance; +import java.util.Arrays; + public class EditDistanceBase { - public static int costOfSubstitution(char a, char b) { - if (a == b) { - return 0; - } - return 1; + static int costOfSubstitution(char a, char b) { + return a == b ? 0 : 1; } - public static int min(int... numbers) { - int min = Integer.MAX_VALUE; - - for (int x : numbers) { - if (x < min) - min = x; - } - - return min; + static int min(int... numbers) { + return Arrays.stream(numbers) + .min().orElse(Integer.MAX_VALUE); } } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceDynamicProgramming.java b/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceDynamicProgramming.java index 163714002b..1f8824c4f4 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceDynamicProgramming.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceDynamicProgramming.java @@ -2,7 +2,7 @@ package com.baeldung.algorithms.editdistance; public class EditDistanceDynamicProgramming extends EditDistanceBase { - public static int calculate(String x, String y) { + static int calculate(String x, String y) { int[][] dp = new int[x.length() + 1][y.length() + 1]; for (int i = 0; i <= x.length(); i++) { @@ -14,12 +14,13 @@ public class EditDistanceDynamicProgramming extends EditDistanceBase { dp[i][j] = i; else { - dp[i][j] = min(dp[i - 1][j - 1] + costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)), dp[i - 1][j] + 1, dp[i][j - 1] + 1); + dp[i][j] = min(dp[i - 1][j - 1] + + costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)), + dp[i - 1][j] + 1, dp[i][j - 1] + 1); } } } return dp[x.length()][y.length()]; } - } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceRecursive.java b/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceRecursive.java index 68e470147e..8ed48dc554 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceRecursive.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceRecursive.java @@ -2,13 +2,15 @@ package com.baeldung.algorithms.editdistance; public class EditDistanceRecursive extends EditDistanceBase { - public static int calculate(String x, String y) { + static int calculate(String x, String y) { - if (x.isEmpty()) + if (x.isEmpty()) { return y.length(); + } - if (y.isEmpty()) + if (y.isEmpty()) { return x.length(); + } int substitution = calculate(x.substring(1), y.substring(1)) + costOfSubstitution(x.charAt(0), y.charAt(0)); int insertion = calculate(x, y.substring(1)) + 1; @@ -16,5 +18,4 @@ public class EditDistanceRecursive extends EditDistanceBase { return min(substitution, insertion, deletion); } - } diff --git a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java b/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java index 1594f73a73..bab2f480a5 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java @@ -1,16 +1,17 @@ package com.baeldung.algorithms.editdistance; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import static org.junit.Assert.assertEquals; + @RunWith(Parameterized.class) public class EditDistanceTest extends EditDistanceDataProvider { - String x; - String y; - int result; + private String x; + private String y; + private int result; public EditDistanceTest(String a, String b, int res) { super(); @@ -21,11 +22,11 @@ public class EditDistanceTest extends EditDistanceDataProvider { @Test public void testEditDistance_RecursiveImplementation() { - Assert.assertEquals(result, EditDistanceRecursive.calculate(x, y)); + assertEquals(result, EditDistanceRecursive.calculate(x, y)); } @Test public void testEditDistance_givenDynamicProgrammingImplementation() { - Assert.assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y)); + assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y)); } } diff --git a/apache-spark/src/main/java/com/baeldung/WordCount.java b/apache-spark/src/main/java/com/baeldung/WordCount.java index ec1dedcb69..bc73b05536 100644 --- a/apache-spark/src/main/java/com/baeldung/WordCount.java +++ b/apache-spark/src/main/java/com/baeldung/WordCount.java @@ -17,37 +17,24 @@ import scala.Tuple2; public class WordCount { private static final Pattern SPACE = Pattern.compile(" "); - + public static void main(String[] args) throws Exception { - if (args.length < 1) { - System.err.println("Usage: JavaWordCount "); - System.exit(1); + if (args.length < 1) { + System.err.println("Usage: JavaWordCount "); + System.exit(1); + } + SparkConf sparkConf = new SparkConf().setAppName("JavaWordCount") + .setMaster("local"); + JavaSparkContext ctx = new JavaSparkContext(sparkConf); + JavaRDD lines = ctx.textFile(args[0], 1); + + JavaRDD words = lines.flatMap(s -> Arrays.asList(SPACE.split(s)).iterator()); + JavaPairRDD wordAsTuple = words.mapToPair(word -> new Tuple2<>(word, 1)); + JavaPairRDD wordWithCount = wordAsTuple.reduceByKey((Integer i1, Integer i2)->i1 + i2); + List> output = wordWithCount.collect(); + for (Tuple2 tuple : output) { + System.out.println(tuple._1() + ": " + tuple._2()); + } + ctx.stop(); } - SparkConf sparkConf = new SparkConf().setAppName("JavaWordCount").setMaster("local"); - JavaSparkContext ctx = new JavaSparkContext(sparkConf); - JavaRDD lines = ctx.textFile(args[0], 1); - - JavaRDD words = lines.flatMap(s -> Arrays.asList(SPACE.split(s)).iterator()); - JavaPairRDD ones = words.mapToPair( - new PairFunction() { - @Override - public Tuple2 call(String s) { - return new Tuple2<>(s, 1); - } - }); - - JavaPairRDD counts = ones.reduceByKey( - new Function2() { - @Override - public Integer call(Integer i1, Integer i2) { - return i1 + i2; - } - }); - - List> output = counts.collect(); - for (Tuple2 tuple : output) { - System.out.println(tuple._1() + ": " + tuple._2()); - } - ctx.stop(); -} } diff --git a/cas-secured-app/README.md b/cas-secured-app/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/cas-secured-app/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/cas/cas-secured-app/.gitignore b/cas/cas-secured-app/.gitignore new file mode 100644 index 0000000000..cd4878159f --- /dev/null +++ b/cas/cas-secured-app/.gitignore @@ -0,0 +1,27 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ +/.mvn/ +/mvnw +/mvnw.cmd \ No newline at end of file diff --git a/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml similarity index 100% rename from cas-secured-app/pom.xml rename to cas/cas-secured-app/pom.xml diff --git a/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java similarity index 100% rename from cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java rename to cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java diff --git a/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java similarity index 100% rename from cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java rename to cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java diff --git a/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java similarity index 100% rename from cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java rename to cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java diff --git a/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java similarity index 100% rename from cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java rename to cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java diff --git a/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java similarity index 100% rename from cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java rename to cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java diff --git a/cas-secured-app/src/main/resources/application.properties b/cas/cas-secured-app/src/main/resources/application.properties similarity index 100% rename from cas-secured-app/src/main/resources/application.properties rename to cas/cas-secured-app/src/main/resources/application.properties diff --git a/cas-secured-app/src/main/resources/templates/auth/logout.ftl b/cas/cas-secured-app/src/main/resources/templates/auth/logout.ftl similarity index 100% rename from cas-secured-app/src/main/resources/templates/auth/logout.ftl rename to cas/cas-secured-app/src/main/resources/templates/auth/logout.ftl diff --git a/cas-secured-app/src/main/resources/templates/index.ftl b/cas/cas-secured-app/src/main/resources/templates/index.ftl similarity index 100% rename from cas-secured-app/src/main/resources/templates/index.ftl rename to cas/cas-secured-app/src/main/resources/templates/index.ftl diff --git a/cas-secured-app/src/main/resources/templates/secure/index.ftl b/cas/cas-secured-app/src/main/resources/templates/secure/index.ftl similarity index 100% rename from cas-secured-app/src/main/resources/templates/secure/index.ftl rename to cas/cas-secured-app/src/main/resources/templates/secure/index.ftl diff --git a/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java similarity index 100% rename from cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java rename to cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java diff --git a/cas-server/.gitignore b/cas/cas-server/.gitignore similarity index 100% rename from cas-server/.gitignore rename to cas/cas-server/.gitignore diff --git a/cas-server/LICENSE.txt b/cas/cas-server/LICENSE.txt similarity index 100% rename from cas-server/LICENSE.txt rename to cas/cas-server/LICENSE.txt diff --git a/cas-server/README.md b/cas/cas-server/README.md similarity index 100% rename from cas-server/README.md rename to cas/cas-server/README.md diff --git a/cas-server/build.cmd b/cas/cas-server/build.cmd similarity index 100% rename from cas-server/build.cmd rename to cas/cas-server/build.cmd diff --git a/cas-server/build.sh b/cas/cas-server/build.sh similarity index 100% rename from cas-server/build.sh rename to cas/cas-server/build.sh diff --git a/cas-server/etc/cas/config/application.yml b/cas/cas-server/etc/cas/config/application.yml similarity index 100% rename from cas-server/etc/cas/config/application.yml rename to cas/cas-server/etc/cas/config/application.yml diff --git a/cas-server/etc/cas/config/cas.properties b/cas/cas-server/etc/cas/config/cas.properties similarity index 100% rename from cas-server/etc/cas/config/cas.properties rename to cas/cas-server/etc/cas/config/cas.properties diff --git a/cas-server/etc/cas/config/log4j2.xml b/cas/cas-server/etc/cas/config/log4j2.xml similarity index 100% rename from cas-server/etc/cas/config/log4j2.xml rename to cas/cas-server/etc/cas/config/log4j2.xml diff --git a/cas-server/etc/cas/thekeystore b/cas/cas-server/etc/cas/thekeystore similarity index 100% rename from cas-server/etc/cas/thekeystore rename to cas/cas-server/etc/cas/thekeystore diff --git a/cas-server/etc/cas/thekeystore.crt b/cas/cas-server/etc/cas/thekeystore.crt similarity index 100% rename from cas-server/etc/cas/thekeystore.crt rename to cas/cas-server/etc/cas/thekeystore.crt diff --git a/cas-server/maven/maven-wrapper.properties b/cas/cas-server/maven/maven-wrapper.properties similarity index 100% rename from cas-server/maven/maven-wrapper.properties rename to cas/cas-server/maven/maven-wrapper.properties diff --git a/cas-server/mvnw b/cas/cas-server/mvnw similarity index 100% rename from cas-server/mvnw rename to cas/cas-server/mvnw diff --git a/cas-server/mvnw.bat b/cas/cas-server/mvnw.bat similarity index 100% rename from cas-server/mvnw.bat rename to cas/cas-server/mvnw.bat diff --git a/cas-server/pom.xml b/cas/cas-server/pom.xml similarity index 100% rename from cas-server/pom.xml rename to cas/cas-server/pom.xml diff --git a/cas-server/src/main/resources/application.properties b/cas/cas-server/src/main/resources/application.properties similarity index 100% rename from cas-server/src/main/resources/application.properties rename to cas/cas-server/src/main/resources/application.properties diff --git a/cas-server/src/main/resources/cas.properties b/cas/cas-server/src/main/resources/cas.properties similarity index 100% rename from cas-server/src/main/resources/cas.properties rename to cas/cas-server/src/main/resources/cas.properties diff --git a/cas-server/src/main/resources/services/casSecuredApp.json b/cas/cas-server/src/main/resources/services/casSecuredApp.json similarity index 100% rename from cas-server/src/main/resources/services/casSecuredApp.json rename to cas/cas-server/src/main/resources/services/casSecuredApp.json diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java new file mode 100644 index 0000000000..d742d3a55f --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java @@ -0,0 +1,20 @@ +package com.baeldung.concurrent.daemon; + +public class NewThread extends Thread { + + public void run() { + + long startTime = System.currentTimeMillis(); + while (true) { + for (int i = 0; i < 10; i++) { + System.out.println("New Thread is running..." + i); + } + + // prevent the Thread to run forever. It will finish it's execution after 2 seconds + if (System.currentTimeMillis() - startTime > 2000) { + Thread.currentThread().interrupt(); + break; + } + } + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java new file mode 100644 index 0000000000..3ca69d8847 --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java @@ -0,0 +1,31 @@ +package com.baeldung.concurrent.daemon; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Ignore; +import org.junit.Test; + +public class DaemonThreadTest { + + @Test + @Ignore + public void whenCallIsDaemon_thenCorrect() { + NewThread daemonThread = new NewThread(); + NewThread userThread = new NewThread(); + daemonThread.setDaemon(true); + daemonThread.start(); + userThread.start(); + + assertTrue(daemonThread.isDaemon()); + assertFalse(userThread.isDaemon()); + } + + @Test(expected = IllegalThreadStateException.class) + @Ignore + public void givenUserThread_whenSetDaemonWhileRunning_thenIllegalThreadStateException() { + NewThread daemonThread = new NewThread(); + daemonThread.start(); + daemonThread.setDaemon(true); + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadTest.java new file mode 100644 index 0000000000..4bd4848905 --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadTest.java @@ -0,0 +1,138 @@ +package com.baeldung.concurrent.runnable; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.apache.commons.lang3.RandomUtils; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RunnableVsThreadTest { + + private static Logger log = + LoggerFactory.getLogger(RunnableVsThreadTest.class); + + private static ExecutorService executorService; + + @BeforeClass + public static void setup() { + executorService = Executors.newCachedThreadPool(); + } + + @Test + public void givenARunnable_whenRunIt_thenResult() throws Exception{ + Thread thread = new Thread(new SimpleRunnable( + "SimpleRunnable executed using Thread")); + thread.start(); + thread.join(); + } + + @Test + public void givenARunnable_whenSubmitToES_thenResult() throws Exception{ + + executorService.submit(new SimpleRunnable( + "SimpleRunnable executed using ExecutorService")).get(); + } + + @Test + public void givenARunnableLambda_whenSubmitToES_thenResult() + throws Exception{ + + executorService.submit(()-> + log.info("Lambda runnable executed!!!")).get(); + } + + @Test + public void givenAThread_whenRunIt_thenResult() throws Exception{ + Thread thread = new SimpleThread( + "SimpleThread executed using Thread"); + thread.start(); + thread.join(); + } + + @Test + public void givenAThread_whenSubmitToES_thenResult() throws Exception{ + + executorService.submit(new SimpleThread( + "SimpleThread executed using ExecutorService")).get(); + } + + @Test + public void givenACallable_whenSubmitToES_thenResult() throws Exception { + + Future future = executorService.submit( + new SimpleCallable()); + log.info("Result from callable: {}", future.get()); + } + + @Test + public void givenACallableAsLambda_whenSubmitToES_thenResult() + throws Exception { + + Future future = executorService.submit(() -> { + return RandomUtils.nextInt(0, 100); + }); + + log.info("Result from callable: {}", future.get()); + } + + @AfterClass + public static void tearDown() { + if ( executorService != null && !executorService.isShutdown()) { + executorService.shutdown(); + } + } +} + +class SimpleThread extends Thread{ + + private static final Logger log = + LoggerFactory.getLogger(SimpleThread.class); + + private String message; + + public SimpleThread(String message) { + this.message = message; + } + + @Override + public void run() { + log.info(message); + } +} + +class SimpleRunnable implements Runnable { + + private static final Logger log = + LoggerFactory.getLogger(SimpleRunnable.class); + + private String message; + + public SimpleRunnable(String message) { + this.message = message; + } + + + @Override + public void run() { + log.info(message); + } +} + +class SimpleCallable implements Callable { + + @Override + public Integer call() throws Exception { + return RandomUtils.nextInt(0, 100); + } + +} + diff --git a/core-java/src/main/java/com/baeldung/array/ArrayInitializer.java b/core-java/src/main/java/com/baeldung/array/ArrayInitializer.java index fd00c74e7f..0ba6c342d9 100644 --- a/core-java/src/main/java/com/baeldung/array/ArrayInitializer.java +++ b/core-java/src/main/java/com/baeldung/array/ArrayInitializer.java @@ -2,73 +2,77 @@ package com.baeldung.array; import java.util.Arrays; +import org.apache.commons.lang.ArrayUtils; + public class ArrayInitializer { - public static int[] initializeArrayInLoop() { + static int[] initializeArrayInLoop() { int array[] = new int[5]; - for (int i = 0; i < array.length; i++) + for (int i = 0; i < array.length; i++) { array[i] = i + 2; + } return array; } - public static int[][] initializeMultiDimensionalArrayInLoop() { + static int[][] initializeMultiDimensionalArrayInLoop() { int array[][] = new int[2][5]; - for (int i = 0; i < 2; i++) - for (int j = 0; j < 5; j++) + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 5; j++) { array[i][j] = j + 1; + } + } + return array; } - public static String[] initializeArrayAtTimeOfDeclarationMethod1() { + static String[] initializeArrayAtTimeOfDeclarationMethod1() { String array[] = new String[] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" }; return array; } - public static int[] initializeArrayAtTimeOfDeclarationMethod2() { + static int[] initializeArrayAtTimeOfDeclarationMethod2() { int[] array = new int[] { 1, 2, 3, 4, 5 }; return array; } - public static int[] initializeArrayAtTimeOfDeclarationMethod3() { + static int[] initializeArrayAtTimeOfDeclarationMethod3() { int array[] = { 1, 2, 3, 4, 5 }; return array; } - public static long[] initializeArrayUsingArraysFill() { + static long[] initializeArrayUsingArraysFill() { long array[] = new long[5]; Arrays.fill(array, 30); return array; } - public static int[] initializeArrayRangeUsingArraysFill() { + static int[] initializeArrayRangeUsingArraysFill() { int array[] = new int[5]; Arrays.fill(array, 0, 3, -50); return array; } - public static int[] initializeArrayUsingArraysCopy() { + static int[] initializeArrayUsingArraysCopy() { int array[] = { 1, 2, 3, 4, 5 }; int[] copy = Arrays.copyOf(array, 5); return copy; } - public static int[] initializeLargerArrayUsingArraysCopy() { + static int[] initializeLargerArrayUsingArraysCopy() { int array[] = { 1, 2, 3, 4, 5 }; int[] copy = Arrays.copyOf(array, 6); return copy; } - public static int[] initializeArrayUsingArraysSetAll() { + static int[] initializeArrayUsingArraysSetAll() { int[] array = new int[20]; - for (int i = 0; i < 20; i++) { - Arrays.setAll(array, p -> { - if (p > 9) - return 0; - else - return p; - }); - } + Arrays.setAll(array, p -> p > 9 ? 0 : p); return array; } + + static char[] initializeArrayUsingArraysUtilClone() { + char[] array = new char[] { 'a', 'b', 'c' }; + return ArrayUtils.clone(array); + } } diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java index 2ed9a27c4c..7c1e291646 100644 --- a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java @@ -13,6 +13,8 @@ import java.util.Set; public class EchoServer { + private static final String POISON_PILL = "POISON_PILL"; + public static void main(String[] args) throws IOException { Selector selector = Selector.open(); ServerSocketChannel serverSocket = ServerSocketChannel.open(); @@ -30,23 +32,36 @@ public class EchoServer { SelectionKey key = iter.next(); if (key.isAcceptable()) { - SocketChannel client = serverSocket.accept(); - client.configureBlocking(false); - client.register(selector, SelectionKey.OP_READ); + register(selector, serverSocket); } if (key.isReadable()) { - SocketChannel client = (SocketChannel) key.channel(); - client.read(buffer); - buffer.flip(); - client.write(buffer); - buffer.clear(); + answerWithEcho(buffer, key); } iter.remove(); } } } + private static void answerWithEcho(ByteBuffer buffer, SelectionKey key) throws IOException { + SocketChannel client = (SocketChannel) key.channel(); + client.read(buffer); + if (new String(buffer.array()).trim().equals(POISON_PILL)) { + client.close(); + System.out.println("Not accepting client messages anymore"); + } + + buffer.flip(); + client.write(buffer); + buffer.clear(); + } + + private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException { + SocketChannel client = serverSocket.accept(); + client.configureBlocking(false); + client.register(selector, SelectionKey.OP_READ); + } + public static Process start() throws IOException, InterruptedException { String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; diff --git a/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java b/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java index d3afad7b00..7265fa20e5 100644 --- a/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java +++ b/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java @@ -8,6 +8,7 @@ import static com.baeldung.array.ArrayInitializer.initializeArrayRangeUsingArray import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysCopy; import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysFill; import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysSetAll; +import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysUtilClone; import static com.baeldung.array.ArrayInitializer.initializeLargerArrayUsingArraysCopy; import static com.baeldung.array.ArrayInitializer.initializeMultiDimensionalArrayInLoop; import static org.junit.Assert.assertArrayEquals; @@ -65,4 +66,9 @@ public class ArrayInitializerTest { public void whenInitializeLargerArrayRangeUsingArraysSetAll_thenCorrect() { assertArrayEquals(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, initializeArrayUsingArraysSetAll()); } + + @Test + public void whenInitializeArrayUsingArraysUtilClone_thenCorrect() { + assertArrayEquals(new char[] { 'a', 'b', 'c' }, initializeArrayUsingArraysUtilClone()); + } } diff --git a/core-java/src/test/java/com/baeldung/string/StringTest.java b/core-java/src/test/java/com/baeldung/string/StringTest.java index 0e325950b0..fe1a69aa23 100644 --- a/core-java/src/test/java/com/baeldung/string/StringTest.java +++ b/core-java/src/test/java/com/baeldung/string/StringTest.java @@ -5,6 +5,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.IllegalFormatException; import java.util.regex.PatternSyntaxException; @@ -29,11 +30,17 @@ public class StringTest { } @Test - public void whenGetBytes_thenCorrect() { - byte[] byteArray = "abcd".getBytes(); - byte[] expected = new byte[] { 97, 98, 99, 100 }; + public void whenGetBytes_thenCorrect() throws UnsupportedEncodingException { + byte[] byteArray1 = "abcd".getBytes(); + byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII); + byte[] byteArray3 = "ijkl".getBytes("UTF-8"); + byte[] expected1 = new byte[] { 97, 98, 99, 100 }; + byte[] expected2 = new byte[] { 101, 102, 103, 104 }; + byte[] expected3 = new byte[] { 105, 106, 107, 108 }; - assertArrayEquals(expected, byteArray); + assertArrayEquals(expected1, byteArray1); + assertArrayEquals(expected2, byteArray2); + assertArrayEquals(expected3, byteArray3); } @Test @@ -123,6 +130,7 @@ public class StringTest { @Test public void whenCallLastIndexOf_thenCorrect() { assertEquals(2, "foo".lastIndexOf("o")); + assertEquals(2, "foo".lastIndexOf(111)); } @Test diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseDuration.kt b/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseDuration.kt new file mode 100644 index 0000000000..40fb161c08 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseDuration.kt @@ -0,0 +1,15 @@ +package com.baeldung.datetime + +import java.time.Duration +import java.time.LocalTime + +class UseDuration { + + fun modifyDates(localTime: LocalTime, duration: Duration): LocalTime { + return localTime.plus(duration) + } + + fun getDifferenceBetweenDates(localTime1: LocalTime, localTime2: LocalTime): Duration { + return Duration.between(localTime1, localTime2) + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDate.kt b/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDate.kt new file mode 100644 index 0000000000..250c071bbe --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDate.kt @@ -0,0 +1,42 @@ +package com.baeldung.datetime + +import java.time.DayOfWeek +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.temporal.ChronoUnit +import java.time.temporal.TemporalAdjusters + +class UseLocalDate { + + fun getLocalDateUsingFactoryOfMethod(year: Int, month: Int, dayOfMonth: Int): LocalDate { + return LocalDate.of(year, month, dayOfMonth) + } + + fun getLocalDateUsingParseMethod(representation: String): LocalDate { + return LocalDate.parse(representation) + } + + fun getLocalDateFromClock(): LocalDate { + return LocalDate.now() + } + + fun getNextDay(localDate: LocalDate): LocalDate { + return localDate.plusDays(1) + } + + fun getPreviousDay(localDate: LocalDate): LocalDate { + return localDate.minus(1, ChronoUnit.DAYS) + } + + fun getDayOfWeek(localDate: LocalDate): DayOfWeek { + return localDate.dayOfWeek + } + + fun getFirstDayOfMonth(): LocalDate { + return LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()) + } + + fun getStartOfDay(localDate: LocalDate): LocalDateTime { + return localDate.atStartOfDay() + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDateTime.kt b/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDateTime.kt new file mode 100644 index 0000000000..ab7bbfcee1 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalDateTime.kt @@ -0,0 +1,10 @@ +package com.baeldung.datetime + +import java.time.LocalDateTime + +class UseLocalDateTime { + + fun getLocalDateTimeUsingParseMethod(representation: String): LocalDateTime { + return LocalDateTime.parse(representation) + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalTime.kt b/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalTime.kt new file mode 100644 index 0000000000..152515621f --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseLocalTime.kt @@ -0,0 +1,32 @@ +package com.baeldung.datetime + +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.temporal.ChronoUnit + +class UseLocalTime { + + fun getLocalTimeUsingFactoryOfMethod(hour: Int, min: Int, seconds: Int): LocalTime { + return LocalTime.of(hour, min, seconds) + } + + fun getLocalTimeUsingParseMethod(timeRepresentation: String): LocalTime { + return LocalTime.parse(timeRepresentation) + } + + fun getLocalTimeFromClock(): LocalTime { + return LocalTime.now() + } + + fun addAnHour(localTime: LocalTime): LocalTime { + return localTime.plus(1, ChronoUnit.HOURS) + } + + fun getHourFromLocalTime(localTime: LocalTime): Int { + return localTime.hour + } + + fun getLocalTimeWithMinuteSetToValue(localTime: LocalTime, minute: Int): LocalTime { + return localTime.withMinute(minute) + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UsePeriod.kt b/core-kotlin/src/main/kotlin/com/baeldung/datetime/UsePeriod.kt new file mode 100644 index 0000000000..df66a3d546 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datetime/UsePeriod.kt @@ -0,0 +1,15 @@ +package com.baeldung.datetime + +import java.time.LocalDate +import java.time.Period + +class UsePeriod { + + fun modifyDates(localDate: LocalDate, period: Period): LocalDate { + return localDate.plus(period) + } + + fun getDifferenceBetweenDates(localDate1: LocalDate, localDate2: LocalDate): Period { + return Period.between(localDate1, localDate2) + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseZonedDateTime.kt b/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseZonedDateTime.kt new file mode 100644 index 0000000000..fd1838bd2d --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datetime/UseZonedDateTime.kt @@ -0,0 +1,12 @@ +package com.baeldung.datetime + +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.ZonedDateTime + +class UseZonedDateTime { + + fun getZonedDateTime(localDateTime: LocalDateTime, zoneId: ZoneId): ZonedDateTime { + return ZonedDateTime.of(localDateTime, zoneId) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateTimeUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateTimeUnitTest.kt new file mode 100644 index 0000000000..8f9f8374ed --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateTimeUnitTest.kt @@ -0,0 +1,23 @@ +package com.baeldung.kotlin.datetime + +import com.baeldung.datetime.UseLocalDateTime +import java.time.LocalDate +import java.time.LocalTime +import java.time.Month + +import org.junit.Test + +import org.junit.Assert.assertEquals + +class UseLocalDateTimeUnitTest { + + var useLocalDateTime = UseLocalDateTime() + + @Test + fun givenString_whenUsingParse_thenLocalDateTime() { + assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") + .toLocalDate()) + assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") + .toLocalTime()) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateUnitTest.kt new file mode 100644 index 0000000000..ac42e91c6c --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalDateUnitTest.kt @@ -0,0 +1,59 @@ +package com.baeldung.kotlin.datetime + +import com.baeldung.datetime.UseLocalDate +import org.junit.Assert +import org.junit.Test +import java.time.DayOfWeek +import java.time.LocalDate +import java.time.LocalDateTime + +class UseLocalDateUnitTest { + + var useLocalDate = UseLocalDate() + + @Test + fun givenValues_whenUsingFactoryOf_thenLocalDate() { + Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10) + .toString()) + } + + @Test + fun givenString_whenUsingParse_thenLocalDate() { + Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10") + .toString()) + } + + @Test + fun whenUsingClock_thenLocalDate() { + Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock()) + } + + @Test + fun givenDate_whenUsingPlus_thenNextDay() { + Assert.assertEquals(LocalDate.now() + .plusDays(1), useLocalDate.getNextDay(LocalDate.now())) + } + + @Test + fun givenDate_whenUsingMinus_thenPreviousDay() { + Assert.assertEquals(LocalDate.now() + .minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())) + } + + @Test + fun givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() { + Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22"))) + } + + @Test + fun givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() { + Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth() + .dayOfMonth.toLong()) + } + + @Test + fun givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() { + Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22"))) + } + +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalTimeUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalTimeUnitTest.kt new file mode 100644 index 0000000000..83fc57f850 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseLocalTimeUnitTest.kt @@ -0,0 +1,37 @@ +package com.baeldung.kotlin.datetime + +import com.baeldung.datetime.UseLocalTime +import java.time.LocalTime + +import org.junit.Assert +import org.junit.Test + +class UseLocalTimeUnitTest { + + internal var useLocalTime = UseLocalTime() + + @Test + fun givenValues_whenUsingFactoryOf_thenLocalTime() { + Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString()) + } + + @Test + fun givenString_whenUsingParse_thenLocalTime() { + Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString()) + } + + @Test + fun givenTime_whenAddHour_thenLocalTime() { + Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString()) + } + + @Test + fun getHourFromLocalTime() { + Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1, 1)).toLong()) + } + + @Test + fun getLocalTimeWithMinuteSetToValue() { + Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10, 10), 20)) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UsePeriodUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UsePeriodUnitTest.kt new file mode 100644 index 0000000000..48be72feb0 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UsePeriodUnitTest.kt @@ -0,0 +1,28 @@ +package com.baeldung.kotlin.datetime + +import com.baeldung.datetime.UsePeriod +import java.time.LocalDate +import java.time.Period + +import org.junit.Assert +import org.junit.Test + +class UsePeriodUnitTest { + + var usingPeriod = UsePeriod() + + @Test + fun givenPeriodAndLocalDate_thenCalculateModifiedDate() { + val period = Period.ofDays(1) + val localDate = LocalDate.parse("2007-05-10") + Assert.assertEquals(localDate.plusDays(1), usingPeriod.modifyDates(localDate, period)) + } + + @Test + fun givenDates_thenGetPeriod() { + val localDate1 = LocalDate.parse("2007-05-10") + val localDate2 = LocalDate.parse("2007-05-15") + + Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2)) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseZonedDateTimeUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseZonedDateTimeUnitTest.kt new file mode 100644 index 0000000000..a9d7d973ef --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/datetime/UseZonedDateTimeUnitTest.kt @@ -0,0 +1,19 @@ +package com.baeldung.kotlin.datetime + +import com.baeldung.datetime.UseZonedDateTime +import org.junit.Assert +import org.junit.Test +import java.time.LocalDateTime +import java.time.ZoneId + +class UseZonedDateTimeUnitTest { + + internal var zonedDateTime = UseZonedDateTime() + + @Test + fun givenZoneId_thenZonedDateTime() { + val zoneId = ZoneId.of("Europe/Paris") + val zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId) + Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime)) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt index dd35805044..40cd9adc99 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/CalculatorTest5.kt @@ -7,12 +7,12 @@ class CalculatorTest5 { private val calculator = Calculator() @Test - fun testAddition() { + fun whenAdding1and3_thenAnswerIs4() { Assertions.assertEquals(4, calculator.add(1, 3)) } @Test - fun testDivideByZero() { + fun whenDividingBy0_thenErrorOccurs() { val exception = Assertions.assertThrows(DivideByZeroException::class.java) { calculator.divide(5, 0) } @@ -21,7 +21,7 @@ class CalculatorTest5 { } @Test - fun testSquares() { + fun whenSquaringNumbers_thenCorrectAnswerGiven() { Assertions.assertAll( Executable { Assertions.assertEquals(1, calculator.square(1)) }, Executable { Assertions.assertEquals(4, calculator.square(2)) }, @@ -31,9 +31,9 @@ class CalculatorTest5 { @TestFactory fun testSquaresFactory() = listOf( - DynamicTest.dynamicTest("1 squared") { Assertions.assertEquals(1,calculator.square(1))}, - DynamicTest.dynamicTest("2 squared") { Assertions.assertEquals(4,calculator.square(2))}, - DynamicTest.dynamicTest("3 squared") { Assertions.assertEquals(9,calculator.square(3))} + DynamicTest.dynamicTest("when I calculate 1^2 then I get 1") { Assertions.assertEquals(1,calculator.square(1))}, + DynamicTest.dynamicTest("when I calculate 2^2 then I get 4") { Assertions.assertEquals(4,calculator.square(2))}, + DynamicTest.dynamicTest("when I calculate 3^2 then I get 9") { Assertions.assertEquals(9,calculator.square(3))} ) @TestFactory @@ -44,7 +44,7 @@ class CalculatorTest5 { 4 to 16, 5 to 25) .map { (input, expected) -> - DynamicTest.dynamicTest("$input squared") { + DynamicTest.dynamicTest("when I calculate $input^2 then I get $expected") { Assertions.assertEquals(expected, calculator.square(input)) } } @@ -59,14 +59,14 @@ class CalculatorTest5 { @TestFactory fun testSquaresFactory3() = squaresTestData .map { (input, expected) -> - DynamicTest.dynamicTest("$input squared") { + DynamicTest.dynamicTest("when I calculate $input^2 then I get $expected") { Assertions.assertEquals(expected, calculator.square(input)) } } @TestFactory fun testSquareRootsFactory3() = squaresTestData .map { (expected, input) -> - DynamicTest.dynamicTest("Square root of $input") { + DynamicTest.dynamicTest("I calculate the square root of $input then I get $expected") { Assertions.assertEquals(expected.toDouble(), calculator.squareRoot(input)) } } @@ -76,7 +76,7 @@ class CalculatorTest5 { Tag("logarithms") ) @Test - fun testLogarithms() { + fun whenIcalculateLog2Of8_thenIget3() { Assertions.assertEquals(3.0, calculator.log(2, 8)) } } diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt index c04ab568f7..70d3fb90bf 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/junit5/SimpleTest5.kt @@ -6,14 +6,14 @@ import org.junit.jupiter.api.Test class SimpleTest5 { @Test - fun testEmpty() { + fun whenEmptyList_thenListIsEmpty() { val list = listOf() Assertions.assertTrue(list::isEmpty) } @Test @Disabled - fun testMessage() { + fun when3equals4_thenTestFails() { Assertions.assertEquals(3, 4) { "Three does not equal four" } diff --git a/drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java b/drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java new file mode 100644 index 0000000000..1c1d258b47 --- /dev/null +++ b/drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java @@ -0,0 +1,33 @@ +package com.baeldung.drools; + +import org.kie.api.KieServices; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.KieSession; + +import com.baeldung.drools.model.Fact; +import com.baeldung.drools.model.Result; + +public class BackwardChaining { + public static void main(String[] args) { + Result result = new BackwardChaining().backwardChaining(); + System.out.println(result.getValue()); + result.getFacts().stream().forEach(System.out::println); + } + + public Result backwardChaining() { + Result result = new Result(); + KieServices ks = KieServices.Factory.get(); + KieContainer kContainer = ks.getKieClasspathContainer(); + KieSession ksession = kContainer.newKieSession("ksession-backward-chaining"); + ksession.setGlobal("result", result); + ksession.insert(new Fact("Asia", "Planet Earth")); +// ksession.insert(new Fact("China", "Asia")); + ksession.insert(new Fact("Great Wall of China", "China")); + + ksession.fireAllRules(); + + return result; + + } + +} \ No newline at end of file diff --git a/drools/backward-chaining/src/main/java/com/baeldung/drools/model/Fact.java b/drools/backward-chaining/src/main/java/com/baeldung/drools/model/Fact.java new file mode 100644 index 0000000000..62b44b9d92 --- /dev/null +++ b/drools/backward-chaining/src/main/java/com/baeldung/drools/model/Fact.java @@ -0,0 +1,69 @@ +package com.baeldung.drools.model; + +import org.kie.api.definition.type.Position; + +public class Fact { + + @Position(0) + private String element; + + @Position(1) + private String place; + + public Fact(String element, String place) { + this.element = element; + this.place = place; + } + + public String getElement() { + return element; + } + + public void setElement(String element) { + this.element = element; + } + + public String getPlace() { + return place; + } + + public void setPlace(String place) { + this.place = place; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((element == null) ? 0 : element.hashCode()); + result = prime * result + ((place == null) ? 0 : place.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Fact other = (Fact) obj; + if (element == null) { + if (other.element != null) + return false; + } else if (!element.equals(other.element)) + return false; + if (place == null) { + if (other.place != null) + return false; + } else if (!place.equals(other.place)) + return false; + return true; + } + + @Override + public String toString() { + return "Fact{" + "element='" + element + '\'' + ", place='" + place + '\'' + '}'; + } +} \ No newline at end of file diff --git a/drools/backward-chaining/src/main/java/com/baeldung/drools/model/Result.java b/drools/backward-chaining/src/main/java/com/baeldung/drools/model/Result.java new file mode 100644 index 0000000000..b22557832b --- /dev/null +++ b/drools/backward-chaining/src/main/java/com/baeldung/drools/model/Result.java @@ -0,0 +1,31 @@ +package com.baeldung.drools.model; + +import java.util.ArrayList; +import java.util.List; + +public class Result { + private String value; + private List facts = new ArrayList<>(); + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public List getFacts() { + return facts; + } + + public void setFacts(List facts) { + this.facts = facts; + } + + public void addFact(String fact) { + this.facts.add(fact); + } + + +} diff --git a/drools/backward-chaining/src/main/resources/META-INF/maven/pom.properties b/drools/backward-chaining/src/main/resources/META-INF/maven/pom.properties new file mode 100644 index 0000000000..26d8331732 --- /dev/null +++ b/drools/backward-chaining/src/main/resources/META-INF/maven/pom.properties @@ -0,0 +1,3 @@ +groupId=com.baeldung.drools +artifactId=DroosBackwardChaining +version=1.0.0-SNAPSHOT diff --git a/drools/backward-chaining/src/main/resources/backward_chaining/rules.drl b/drools/backward-chaining/src/main/resources/backward_chaining/rules.drl new file mode 100644 index 0000000000..abcf95b9f1 --- /dev/null +++ b/drools/backward-chaining/src/main/resources/backward_chaining/rules.drl @@ -0,0 +1,34 @@ +package com.baeldung + +import com.baeldung.drools.model.Fact; + +global com.baeldung.drools.model.Result result; + +dialect "mvel" + +query belongsTo(String x, String y) + Fact(x, y;) + or + (Fact(z, y;) and belongsTo(x, z;)) +end + +rule "Great Wall of China BELONGS TO Planet Earth" +when + belongsTo("Great Wall of China", "Planet Earth";) +then + result.setValue("Decision one taken: Great Wall of China BELONGS TO Planet Earth"); +end + +rule "Great Wall of China DOES NOT BELONG TO of Planet Earth" +when + not belongsTo("Great Wall of China", "Planet Earth";) +then + result.setValue("Decision two taken: Great Wall of China DOES NOT BELONG TO Planet Earth"); +end + +rule "print all facts" +when + belongsTo(element, place;) +then + result.addFact(element + " IS ELEMENT OF " + place); +end diff --git a/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java b/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java new file mode 100644 index 0000000000..676e941950 --- /dev/null +++ b/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java @@ -0,0 +1,57 @@ +package com.baeldung.test; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.kie.api.KieServices; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.KieSession; + +import com.baeldung.drools.model.Fact; +import com.baeldung.drools.model.Result; + +import static junit.framework.TestCase.assertEquals; + +@RunWith(value = JUnit4.class) +public class BackwardChainingTest { + private Result result; + private KieServices ks; + private KieContainer kContainer; + private KieSession ksession; + + @Before + public void before() { + result = new Result(); + ks = KieServices.Factory.get(); + kContainer = ks.getKieClasspathContainer(); + ksession = kContainer.newKieSession("ksession-backward-chaining"); + ksession.setGlobal("result", result); + } + + @Test + public void whenWallOfChinaIsGiven_ThenItBelongsToPlanetEarth() { + + ksession.setGlobal("result", result); + ksession.insert(new Fact("Asia", "Planet Earth")); + ksession.insert(new Fact("China", "Asia")); + ksession.insert(new Fact("Great Wall of China", "China")); + + ksession.fireAllRules(); + + // Assert Decision one + assertEquals(result.getValue(), "Decision one taken: Great Wall of China BELONGS TO Planet Earth"); + } + + @Test + public void whenChinaIsNotGiven_ThenWallOfChinaDoesNotBelongToPlanetEarth() { + ksession.insert(new Fact("Asia", "Planet Earth")); + // ksession.insert(new Location("China", "Asia")); // not provided to force Decision two + ksession.insert(new Fact("Great Wall of China", "China")); + + ksession.fireAllRules(); + + // Assert Decision two + assertEquals(result.getValue(), "Decision two taken: Great Wall of China DOES NOT BELONG TO Planet Earth"); + } +} diff --git a/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java b/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java index 62feb6b4b9..e86f52ff56 100644 --- a/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java +++ b/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java @@ -1,5 +1,6 @@ import java.io.IOException; +import java.io.PrintWriter; import java.util.List; import javax.ejb.EJB; @@ -15,19 +16,32 @@ import wildfly.beans.UserBeanLocal; * Servlet implementation class TestEJBServlet */ public class TestEJBServlet extends HttpServlet { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @EJB - private UserBeanLocal userBean; + @EJB + private UserBeanLocal userBean; - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - List users = userBean.getUsers(); + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + List users = userBean.getUsers(); - response.getWriter() - .append("The number of users is: " + users.size()); - } + PrintWriter out = response.getWriter(); - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - doGet(request, response); - } + out.println(""); + out.println("Users"); + out.println(""); + out.println("

List of users:

"); + out.println(""); + for (User user : users) { + out.println(""); + out.print(""); + out.print(""); + out.println(""); + } + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + doGet(request, response); + } } diff --git a/ejb/wildfly/wildfly-jpa/src/main/resources/META-INF/persistence.xml b/ejb/wildfly/wildfly-jpa/src/main/resources/META-INF/persistence.xml index 1a3fc32381..2aa6bc2cd7 100644 --- a/ejb/wildfly/wildfly-jpa/src/main/resources/META-INF/persistence.xml +++ b/ejb/wildfly/wildfly-jpa/src/main/resources/META-INF/persistence.xml @@ -3,7 +3,13 @@ xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> - java:/PostgresDS + java:/H2DS model.User + + + + + + diff --git a/ejb/wildfly/wildfly-jpa/src/main/resources/data.sql b/ejb/wildfly/wildfly-jpa/src/main/resources/data.sql new file mode 100644 index 0000000000..03eafa534e --- /dev/null +++ b/ejb/wildfly/wildfly-jpa/src/main/resources/data.sql @@ -0,0 +1 @@ +INSERT INTO users (username, email, postal_number) VALUES ('user1', 'user1@baeldung.com', 1000), ('user2', 'user2@baeldung.com', 2); \ No newline at end of file diff --git a/guest/spring-mvc/README.md b/guest/spring-mvc/README.md new file mode 100644 index 0000000000..9e5cd64a04 --- /dev/null +++ b/guest/spring-mvc/README.md @@ -0,0 +1,17 @@ +## Building + +To build the module, use Maven's `package` goal: + +``` +mvn clean package +``` + +## Running + +To run the application, use Spring Boot's `run` goal: + +``` +mvn spring-boot:run +``` + +The application will be accessible at [http://localhost:8080/](http://localhost:8080/) diff --git a/guest/spring-mvc/pom.xml b/guest/spring-mvc/pom.xml index 9974a76e8a..1f695a75a7 100644 --- a/guest/spring-mvc/pom.xml +++ b/guest/spring-mvc/pom.xml @@ -3,7 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.forketyfork.guest + com.stackify.guestspring-mvc0.0.1-SNAPSHOTjar diff --git a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/Spring5Application.java b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/Spring5Application.java similarity index 76% rename from guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/Spring5Application.java rename to guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/Spring5Application.java index d9af7c8ac9..42d40fa02d 100644 --- a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/Spring5Application.java +++ b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/Spring5Application.java @@ -1,11 +1,11 @@ -package com.forketyfork.guest.springmvc; +package com.stackify.guest.springmvc; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.boot.SpringApplication; @SpringBootApplication -@ComponentScan(basePackages = {"com.forketyfork.guest.springmvc"}) +@ComponentScan(basePackages = {"com.stackify.guest.springmvc"}) public class Spring5Application { public static void main(String[] args) { diff --git a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/model/LoginData.java b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/model/LoginData.java similarity index 89% rename from guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/model/LoginData.java rename to guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/model/LoginData.java index a9140da4f9..b1a0e86ef4 100644 --- a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/model/LoginData.java +++ b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/model/LoginData.java @@ -1,4 +1,4 @@ -package com.forketyfork.guest.springmvc.model; +package com.stackify.guest.springmvc.model; public class LoginData { diff --git a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/InternalsController.java b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/InternalsController.java similarity index 67% rename from guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/InternalsController.java rename to guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/InternalsController.java index c39da4e3e5..0bd8570eed 100644 --- a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/InternalsController.java +++ b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/InternalsController.java @@ -1,11 +1,14 @@ -package com.forketyfork.guest.springmvc.web; +package com.stackify.guest.springmvc.web; -import com.forketyfork.guest.springmvc.model.LoginData; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; +import com.stackify.guest.springmvc.model.LoginData; + import java.util.Collections; @Controller @@ -28,4 +31,10 @@ public class InternalsController { } } + @ResponseBody + @PostMapping("/message") + public MyOutputResource sendMessage(@RequestBody MyInputResource inputResource) { + return new MyOutputResource("Received: " + inputResource.getRequestMessage()); + } + } diff --git a/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyInputResource.java b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyInputResource.java new file mode 100644 index 0000000000..cf5815840a --- /dev/null +++ b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyInputResource.java @@ -0,0 +1,14 @@ +package com.stackify.guest.springmvc.web; + +public class MyInputResource { + + private String requestMessage; + + public String getRequestMessage() { + return requestMessage; + } + + public void setRequestMessage(String requestMessage) { + this.requestMessage = requestMessage; + } +} diff --git a/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyOutputResource.java b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyOutputResource.java new file mode 100644 index 0000000000..2d0e174243 --- /dev/null +++ b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyOutputResource.java @@ -0,0 +1,15 @@ +package com.stackify.guest.springmvc.web; + +public class MyOutputResource { + + private String responseMessage; + + public MyOutputResource(String responseMessage) { + this.responseMessage = responseMessage; + } + + public String getResponseMessage() { + return responseMessage; + } + +} diff --git a/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/RestfulWebServiceController.java b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/RestfulWebServiceController.java new file mode 100644 index 0000000000..edb35e6ecf --- /dev/null +++ b/guest/spring-mvc/src/main/java/com/stackify/guest/springmvc/web/RestfulWebServiceController.java @@ -0,0 +1,14 @@ +package com.stackify.guest.springmvc.web; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RestfulWebServiceController { + + @GetMapping("/message") + public MyOutputResource getMessage() { + return new MyOutputResource("Hello!"); + } + +} diff --git a/hibernate5/README.md b/hibernate5/README.md index ff12555376..9ef170a134 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -1 +1,3 @@ ## Relevant articles: + +- [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping) diff --git a/hibernate5/pom.xml b/hibernate5/pom.xml index c501b7f11d..8543d1dae3 100644 --- a/hibernate5/pom.xml +++ b/hibernate5/pom.xml @@ -22,13 +22,19 @@ org.hibernate hibernate-core - 5.2.9.Final + 5.2.12.Final junit junit 4.12 + + org.assertj + assertj-core + 3.8.0 + test + com.h2database h2 diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java index 5a10b2ba56..30f3c3cf53 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateMultiTenantUtil.java @@ -68,7 +68,7 @@ public class HibernateMultiTenantUtil { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() - .getResource("hibernate.properties"); + .getResource("hibernate-multitenancy.properties"); FileInputStream inputStream = new FileInputStream(propertiesURL.getFile()); properties.load(inputStream); System.out.println("LOADED PROPERTIES FROM hibernate.properties"); diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index c1f7301d46..0282673218 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,24 +1,60 @@ package com.baeldung.hibernate; +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.Phone; +import com.baeldung.hibernate.pojo.TemporalValues; import org.hibernate.SessionFactory; -import org.hibernate.cfg.Configuration; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +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 final SessionFactory sessionFactory; - - static { - try { - Configuration configuration = new Configuration().configure(); - sessionFactory = configuration.buildSessionFactory(); - - } catch (Throwable ex) { - System.err.println("Initial SessionFactory creation failed." + ex); - throw new ExceptionInInitializerError(ex); + public static SessionFactory getSessionFactory() throws IOException { + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = makeSessionFactory(serviceRegistry); } - } - - public static SessionFactory getSessionFactory() { return sessionFactory; } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Employee.class); + metadataSources.addAnnotatedClass(Phone.class); + metadataSources.addAnnotatedClass(EntityDescription.class); + metadataSources.addAnnotatedClass(TemporalValues.class); + + Metadata metadata = metadataSources.buildMetadata(); + return metadata.getSessionFactoryBuilder() + .build(); + + } + + 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("hibernate.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/pojo/Employee.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Employee.java new file mode 100644 index 0000000000..e9732b2b67 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Employee.java @@ -0,0 +1,87 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.*; + +import javax.persistence.Entity; +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Where(clause = "deleted = false") +@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int")) +@Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit") +public class Employee implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private long grossIncome; + + private int taxInPercents; + + private boolean deleted; + + public long getTaxJavaWay() { + return grossIncome * taxInPercents / 100; + } + + @Formula("grossIncome * taxInPercents / 100") + private long tax; + + @OneToMany + @JoinColumn(name = "employee_id") + @Where(clause = "deleted = false") + private Set phones = new HashSet<>(0); + + public Employee() { + } + + public Employee(long grossIncome, int taxInPercents) { + this.grossIncome = grossIncome; + this.taxInPercents = taxInPercents; + } + + public Integer getId() { + return id; + } + + public long getGrossIncome() { + return grossIncome; + } + + public int getTaxInPercents() { + return taxInPercents; + } + + public long getTax() { + return tax; + } + + public void setId(Integer id) { + this.id = id; + } + + public void setGrossIncome(long grossIncome) { + this.grossIncome = grossIncome; + } + + public void setTaxInPercents(int taxInPercents) { + this.taxInPercents = taxInPercents; + } + + public boolean getDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public Set getPhones() { + return phones; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java new file mode 100644 index 0000000000..131bb73a80 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java @@ -0,0 +1,55 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.Any; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class EntityDescription implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private String description; + + @Any( + metaDef = "EntityDescriptionMetaDef", + metaColumn = @Column(name = "entity_type") + ) + @JoinColumn(name = "entity_id") + private Serializable entity; + + public EntityDescription() { + } + + public EntityDescription(String description, Serializable entity) { + this.description = description; + this.entity = entity; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Serializable getEntity() { + return entity; + } + + public void setEntity(Serializable entity) { + this.entity = entity; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Phone.java new file mode 100644 index 0000000000..d923bda5de --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; + +@Entity +public class Phone implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private boolean deleted; + + private String number; + + public Phone() { + } + + public Phone(String number) { + this.number = number; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java new file mode 100644 index 0000000000..f3fe095cae --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java @@ -0,0 +1,195 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.*; +import java.io.Serializable; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.*; +import java.util.Calendar; + +@Entity +public class TemporalValues implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @Basic + private java.sql.Date sqlDate; + + @Basic + private java.sql.Time sqlTime; + + @Basic + private java.sql.Timestamp sqlTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Date utilDate; + + @Basic + @Temporal(TemporalType.TIME) + private java.util.Date utilTime; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Date utilTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Calendar calendarDate; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Calendar calendarTimestamp; + + @Basic + private java.time.LocalDate localDate; + + @Basic + private java.time.LocalTime localTime; + + @Basic + private java.time.OffsetTime offsetTime; + + @Basic + private java.time.Instant instant; + + @Basic + private java.time.LocalDateTime localDateTime; + + @Basic + private java.time.OffsetDateTime offsetDateTime; + + @Basic + private java.time.ZonedDateTime zonedDateTime; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Date getSqlDate() { + return sqlDate; + } + + public void setSqlDate(Date sqlDate) { + this.sqlDate = sqlDate; + } + + public Time getSqlTime() { + return sqlTime; + } + + public void setSqlTime(Time sqlTime) { + this.sqlTime = sqlTime; + } + + public Timestamp getSqlTimestamp() { + return sqlTimestamp; + } + + public void setSqlTimestamp(Timestamp sqlTimestamp) { + this.sqlTimestamp = sqlTimestamp; + } + + public java.util.Date getUtilDate() { + return utilDate; + } + + public void setUtilDate(java.util.Date utilDate) { + this.utilDate = utilDate; + } + + public java.util.Date getUtilTime() { + return utilTime; + } + + public void setUtilTime(java.util.Date utilTime) { + this.utilTime = utilTime; + } + + public java.util.Date getUtilTimestamp() { + return utilTimestamp; + } + + public void setUtilTimestamp(java.util.Date utilTimestamp) { + this.utilTimestamp = utilTimestamp; + } + + public Calendar getCalendarDate() { + return calendarDate; + } + + public void setCalendarDate(Calendar calendarDate) { + this.calendarDate = calendarDate; + } + + public Calendar getCalendarTimestamp() { + return calendarTimestamp; + } + + public void setCalendarTimestamp(Calendar calendarTimestamp) { + this.calendarTimestamp = calendarTimestamp; + } + + public LocalDate getLocalDate() { + return localDate; + } + + public void setLocalDate(LocalDate localDate) { + this.localDate = localDate; + } + + public LocalTime getLocalTime() { + return localTime; + } + + public void setLocalTime(LocalTime localTime) { + this.localTime = localTime; + } + + public OffsetTime getOffsetTime() { + return offsetTime; + } + + public void setOffsetTime(OffsetTime offsetTime) { + this.offsetTime = offsetTime; + } + + public Instant getInstant() { + return instant; + } + + public void setInstant(Instant instant) { + this.instant = instant; + } + + public LocalDateTime getLocalDateTime() { + return localDateTime; + } + + public void setLocalDateTime(LocalDateTime localDateTime) { + this.localDateTime = localDateTime; + } + + public OffsetDateTime getOffsetDateTime() { + return offsetDateTime; + } + + public void setOffsetDateTime(OffsetDateTime offsetDateTime) { + this.offsetDateTime = offsetDateTime; + } + + public ZonedDateTime getZonedDateTime() { + return zonedDateTime; + } + + public void setZonedDateTime(ZonedDateTime zonedDateTime) { + this.zonedDateTime = zonedDateTime; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/package-info.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/package-info.java new file mode 100644 index 0000000000..992cda7c1d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/package-info.java @@ -0,0 +1,9 @@ +@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int", + metaValues = { + @MetaValue(value = "Employee", targetEntity = Employee.class), + @MetaValue(value = "Phone", targetEntity = Phone.class) + }) +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.AnyMetaDef; +import org.hibernate.annotations.MetaValue; \ No newline at end of file diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java new file mode 100644 index 0000000000..b207d6630a --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java @@ -0,0 +1,164 @@ +package com.baeldung.hibernate; + +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.Phone; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DynamicMappingIntegrationTest { + + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory().openSession(); + transaction = session.beginTransaction(); + + session.createNativeQuery("delete from phone").executeUpdate(); + session.createNativeQuery("delete from employee").executeUpdate(); + + transaction.commit(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenEntity_whenFieldMappedWithFormula_thenFieldIsCalculated() { + Employee employee = new Employee(10_000L, 25); + assertThat(employee.getTaxJavaWay()).isEqualTo(2_500L); + + session.save(employee); + session.flush(); + session.clear(); + + employee = session.get(Employee.class, employee.getId()); + assertThat(employee.getTax()).isEqualTo(2_500L); + } + + @Test + public void givenEntityMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() { + Employee employee = new Employee(); + + session.save(employee); + session.clear(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee).isNotNull(); + + employee.setDeleted(true); + session.flush(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee).isNotNull(); + + session.clear(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee).isNull(); + + } + + @Test + public void givenCollectionMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() { + Employee employee = new Employee(); + Phone phone1 = new Phone("555-45-67"); + Phone phone2 = new Phone("555-89-01"); + employee.getPhones().add(phone1); + employee.getPhones().add(phone2); + + session.save(phone1); + session.save(phone2); + session.save(employee); + session.flush(); + session.clear(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee.getPhones()).hasSize(2); + + employee.getPhones().iterator().next().setDeleted(true); + session.flush(); + session.clear(); + + employee = session.find(Employee.class, employee.getId()); + assertThat(employee.getPhones()).hasSize(1); + + List fullPhoneList = session.createQuery("from Phone").getResultList(); + assertThat(fullPhoneList).hasSize(2); + + } + + @Test + public void givenFilterByIncome_whenIncomeLimitSet_thenFilterIsApplied() throws IOException { + session.save(new Employee(10_000, 25)); + session.save(new Employee(12_000, 25)); + session.save(new Employee(15_000, 25)); + + session.flush(); + session.clear(); + + session.enableFilter("incomeLevelFilter") + .setParameter("incomeLimit", 11_000); + + List employees = session.createQuery("from Employee").getResultList(); + + assertThat(employees).hasSize(2); + + Employee employee = session.get(Employee.class, 1); + assertThat(employee.getGrossIncome()).isEqualTo(10_000); + + session.close(); + + session = HibernateUtil.getSessionFactory().openSession(); + transaction = session.beginTransaction(); + + employees = session.createQuery("from Employee").getResultList(); + + assertThat(employees).hasSize(3); + + } + + @Test + public void givenMappingWithAny_whenDescriptionAddedToEntity_thenDescriptionCanReferAnyEntity() { + Employee employee = new Employee(); + Phone phone1 = new Phone("555-45-67"); + Phone phone2 = new Phone("555-89-01"); + employee.getPhones().add(phone1); + employee.getPhones().add(phone2); + + EntityDescription employeeDescription = new EntityDescription("Send to conference next year", employee); + EntityDescription phone1Description = new EntityDescription("Home phone (do not call after 10PM)", phone1); + EntityDescription phone2Description = new EntityDescription("Work phone", phone1); + + session.save(phone1); + session.save(phone2); + session.save(employee); + session.save(employeeDescription); + session.save(phone1Description); + session.save(phone2Description); + session.flush(); + session.clear(); + + List descriptions = session.createQuery("from EntityDescription").getResultList(); + + assertThat(Employee.class.isAssignableFrom(descriptions.get(0).getEntity().getClass())).isTrue(); + assertThat(Phone.class.isAssignableFrom(descriptions.get(1).getEntity().getClass())).isTrue(); + assertThat(Phone.class.isAssignableFrom(descriptions.get(2).getEntity().getClass())).isTrue(); + } + +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesTest.java new file mode 100644 index 0000000000..ec8afc8db2 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesTest.java @@ -0,0 +1,126 @@ +package com.baeldung.hibernate; + +import com.baeldung.hibernate.pojo.TemporalValues; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.time.*; +import java.util.Calendar; +import java.util.TimeZone; + +import static org.assertj.core.api.Assertions.assertThat; + +public class TemporalValuesTest { + + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory().withOptions() + .jdbcTimeZone(TimeZone.getTimeZone("UTC")) + .openSession(); + transaction = session.beginTransaction(); + session.createNativeQuery("delete from temporalvalues").executeUpdate(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenEntity_whenMappingSqlTypes_thenTemporalIsSelectedAutomatically() { + TemporalValues temporalValues = new TemporalValues(); + temporalValues.setSqlDate(java.sql.Date.valueOf("2017-11-15")); + temporalValues.setSqlTime(java.sql.Time.valueOf("15:30:14")); + temporalValues.setSqlTimestamp(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getSqlDate()).isEqualTo(java.sql.Date.valueOf("2017-11-15")); + assertThat(temporalValues.getSqlTime()).isEqualTo(java.sql.Time.valueOf("15:30:14")); + assertThat(temporalValues.getSqlTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); + + } + + @Test + public void givenEntity_whenMappingUtilDateType_thenTemporalIsSpecifiedExplicitly() throws Exception { + TemporalValues temporalValues = new TemporalValues(); + temporalValues.setUtilDate(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); + temporalValues.setUtilTime(new SimpleDateFormat("HH:mm:ss").parse("15:30:14")); + temporalValues.setUtilTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.332")); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getUtilDate()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); + assertThat(temporalValues.getUtilTime()).isEqualTo(new SimpleDateFormat("HH:mm:ss").parse("15:30:14")); + assertThat(temporalValues.getUtilTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); + + } + + @Test + public void givenEntity_whenMappingCalendarType_thenTemporalIsSpecifiedExplicitly() throws Exception { + TemporalValues temporalValues = new TemporalValues(); + + Calendar calendarDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + calendarDate.set(Calendar.YEAR, 2017); + calendarDate.set(Calendar.MONTH, 10); + calendarDate.set(Calendar.DAY_OF_MONTH, 15); + temporalValues.setCalendarDate(calendarDate); + + Calendar calendarTimestamp = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + calendarTimestamp.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322")); + temporalValues.setCalendarTimestamp(calendarTimestamp); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getCalendarDate().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); + assertThat(temporalValues.getCalendarTimestamp().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322")); + + } + + @Test + public void givenEntity_whenMappingJavaTimeTypes_thenTemporalIsSelectedAutomatically() { + TemporalValues temporalValues = new TemporalValues(); + + temporalValues.setLocalDate(LocalDate.parse("2017-11-15")); + temporalValues.setLocalTime(LocalTime.parse("15:30:18")); + temporalValues.setOffsetTime(OffsetTime.parse("08:22:12+01:00")); + temporalValues.setInstant(Instant.parse("2017-11-15T08:22:12Z")); + temporalValues.setLocalDateTime(LocalDateTime.parse("2017-11-15T08:22:12")); + temporalValues.setOffsetDateTime(OffsetDateTime.parse("2017-11-15T08:22:12+01:00")); + temporalValues.setZonedDateTime(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]")); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getLocalDate()).isEqualTo(LocalDate.parse("2017-11-15")); + assertThat(temporalValues.getLocalTime()).isEqualTo(LocalTime.parse("15:30:18")); + assertThat(temporalValues.getOffsetTime()).isEqualTo(OffsetTime.parse("08:22:12+01:00")); + assertThat(temporalValues.getInstant()).isEqualTo(Instant.parse("2017-11-15T08:22:12Z")); + assertThat(temporalValues.getLocalDateTime()).isEqualTo(LocalDateTime.parse("2017-11-15T08:22:12")); + assertThat(temporalValues.getOffsetDateTime()).isEqualTo(OffsetDateTime.parse("2017-11-15T08:22:12+01:00")); + assertThat(temporalValues.getZonedDateTime()).isEqualTo(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]")); + + } + +} diff --git a/hibernate5/src/test/resources/hibernate-multitenancy.properties b/hibernate5/src/test/resources/hibernate-multitenancy.properties new file mode 100644 index 0000000000..298ecd05d3 --- /dev/null +++ b/hibernate5/src/test/resources/hibernate-multitenancy.properties @@ -0,0 +1,9 @@ +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.multiTenancy=DATABASE diff --git a/hibernate5/src/test/resources/hibernate.properties b/hibernate5/src/test/resources/hibernate.properties index 298ecd05d3..7b8764637b 100644 --- a/hibernate5/src/test/resources/hibernate.properties +++ b/hibernate5/src/test/resources/hibernate.properties @@ -6,4 +6,4 @@ jdbc.password= hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=true -hibernate.multiTenancy=DATABASE +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/jackson/README.md b/jackson/README.md index a710a1689e..a05c95de94 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -35,3 +35,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Jackson – Unmarshall to Collection/Array](http://www.baeldung.com/jackson-collection-array) - [Jackson – Change Name of Field](http://www.baeldung.com/jackson-name-of-property) - [Serialize Only Fields that meet a Custom Criteria with Jackson](http://www.baeldung.com/jackson-serialize-field-custom-criteria) +- [Mapping Nested Values with Jackson](http://www.baeldung.com/jackson-nested-values) diff --git a/junit5/README.md b/junit5/README.md index a3bb8fc1be..d0fa19bd83 100644 --- a/junit5/README.md +++ b/junit5/README.md @@ -6,4 +6,4 @@ - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) - [Inject Parameters into JUnit Jupiter Unit Tests](http://www.baeldung.com/junit-5-parameters) - +- [Mockito and JUnit 5 – Using ExtendWith](http://www.baeldung.com/mockito-junit-5-extension) diff --git a/junit5/pom.xml b/junit5/pom.xml index 1fa4818447..b8a7622b3d 100644 --- a/junit5/pom.xml +++ b/junit5/pom.xml @@ -19,15 +19,17 @@ UTF-8 1.8 - 5.0.0-RC2 - 1.0.0-RC2 - 4.12.0-RC2 + 5.0.1 + 1.0.1 + 4.12.1 2.8.2 1.4.196 + 2.11.0 3.6.0 2.19.1 4.12 + 5.0.1.RELEASE @@ -110,6 +112,17 @@ ${junit4.version} test + + org.springframework + spring-test + ${spring.version} + test + + + org.springframework + spring-context + ${spring.version} + diff --git a/junit5/src/main/java/com/baeldung/junit5/Greetings.java b/junit5/src/main/java/com/baeldung/junit5/Greetings.java new file mode 100644 index 0000000000..f43269f646 --- /dev/null +++ b/junit5/src/main/java/com/baeldung/junit5/Greetings.java @@ -0,0 +1,9 @@ +package com.baeldung.junit5; + +public class Greetings { + + public static String sayHello() { + return "Hello"; + } + +} diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/User.java b/junit5/src/main/java/com/baeldung/junit5/mockito/User.java new file mode 100644 index 0000000000..4276fd62b9 --- /dev/null +++ b/junit5/src/main/java/com/baeldung/junit5/mockito/User.java @@ -0,0 +1,41 @@ +package com.baeldung.junit5.mockito; + +public class User { + + private Integer id; + private String name; + private int age; + + public User() { + } + + public User(String name, int age) { + this.name = name; + this.age = age; + } + + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public int getAge() { + return age; + } + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; + } + +} diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java b/junit5/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java new file mode 100644 index 0000000000..d10169ef7a --- /dev/null +++ b/junit5/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java @@ -0,0 +1,9 @@ +package com.baeldung.junit5.mockito.repository; + +import com.baeldung.junit5.mockito.User; + +public interface MailClient { + + void sendUserRegistrationMail(User user); + +} diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java b/junit5/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java new file mode 100644 index 0000000000..23ae8fa35c --- /dev/null +++ b/junit5/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.junit5.mockito.repository; + +public interface SettingRepository { + + int getUserMinAge(); + + int getUserNameMinLength(); + +} diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java b/junit5/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java new file mode 100644 index 0000000000..e1b84c774b --- /dev/null +++ b/junit5/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.junit5.mockito.repository; + +import com.baeldung.junit5.mockito.User; + +public interface UserRepository { + + User insert(User user); + boolean isUsernameAlreadyExists(String userName); + +} diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java b/junit5/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java new file mode 100644 index 0000000000..888edbd710 --- /dev/null +++ b/junit5/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java @@ -0,0 +1,46 @@ +package com.baeldung.junit5.mockito.service; + +import com.baeldung.junit5.mockito.User; +import com.baeldung.junit5.mockito.repository.MailClient; +import com.baeldung.junit5.mockito.repository.SettingRepository; +import com.baeldung.junit5.mockito.repository.UserRepository; + +public class DefaultUserService implements UserService { + + private UserRepository userRepository; + private SettingRepository settingRepository; + private MailClient mailClient; + + public DefaultUserService(UserRepository userRepository, SettingRepository settingRepository, MailClient mailClient) { + this.userRepository = userRepository; + this.settingRepository = settingRepository; + this.mailClient = mailClient; + } + + @Override + public User register(User user) { + validate(user); + User insertedUser = userRepository.insert(user); + mailClient.sendUserRegistrationMail(insertedUser); + return insertedUser; + } + + private void validate(User user) { + if(user.getName() == null) { + throw new RuntimeException(Errors.USER_NAME_REQUIRED); + } + + if(user.getName().length() < settingRepository.getUserNameMinLength()) { + throw new RuntimeException(Errors.USER_NAME_SHORT); + } + + if(user.getAge() < settingRepository.getUserMinAge()) { + throw new RuntimeException(Errors.USER_AGE_YOUNG); + } + + if(userRepository.isUsernameAlreadyExists(user.getName())) { + throw new RuntimeException(Errors.USER_NAME_DUPLICATE); + } + } + +} diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/service/Errors.java b/junit5/src/main/java/com/baeldung/junit5/mockito/service/Errors.java new file mode 100644 index 0000000000..28283754a3 --- /dev/null +++ b/junit5/src/main/java/com/baeldung/junit5/mockito/service/Errors.java @@ -0,0 +1,10 @@ +package com.baeldung.junit5.mockito.service; + +public class Errors { + + public static final String USER_NAME_REQUIRED = "user.name.required"; + public static final String USER_NAME_SHORT = "user.name.short"; + public static final String USER_AGE_YOUNG = "user.age.young"; + public static final String USER_NAME_DUPLICATE = "user.name.duplicate"; + +} diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/service/UserService.java b/junit5/src/main/java/com/baeldung/junit5/mockito/service/UserService.java new file mode 100644 index 0000000000..326d019b4a --- /dev/null +++ b/junit5/src/main/java/com/baeldung/junit5/mockito/service/UserService.java @@ -0,0 +1,9 @@ +package com.baeldung.junit5.mockito.service; + +import com.baeldung.junit5.mockito.User; + +public interface UserService { + + User register(User user); + +} diff --git a/junit5/src/test/java/com/baeldung/GreetingsTest.java b/junit5/src/test/java/com/baeldung/GreetingsTest.java new file mode 100644 index 0000000000..e894d5857c --- /dev/null +++ b/junit5/src/test/java/com/baeldung/GreetingsTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +import com.baeldung.junit5.Greetings; + +@RunWith(JUnitPlatform.class) +public class GreetingsTest { + + @Test + void whenCallingSayHello_thenReturnHello() { + assertTrue("Hello".equals(Greetings.sayHello())); + } + +} diff --git a/junit5/src/test/java/com/baeldung/junit5/mockito/MockitoExtension.java b/junit5/src/test/java/com/baeldung/junit5/mockito/MockitoExtension.java new file mode 100644 index 0000000000..5836ef46e6 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/junit5/mockito/MockitoExtension.java @@ -0,0 +1,75 @@ +/* + * Copyright 2015-2016 the original author or authors. + * + * All rights reserved. This program and the accompanying materials are + * made available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution and is available at + * + * http://www.eclipse.org/legal/epl-v10.html + */ + +package com.baeldung.junit5.mockito; + +import static org.mockito.Mockito.mock; + +import java.lang.reflect.Parameter; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ExtensionContext.Namespace; +import org.junit.jupiter.api.extension.ExtensionContext.Store; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolver; +import org.junit.jupiter.api.extension.TestInstancePostProcessor; +import org.mockito.MockitoAnnotations; +import org.mockito.Mock; + +/** + * {@code MockitoExtension} showcases the {@link TestInstancePostProcessor} + * and {@link ParameterResolver} extension APIs of JUnit 5 by providing + * dependency injection support at the field level and at the method parameter + * level via Mockito 2.x's {@link Mock @Mock} annotation. + * + * @since 5.0 + */ +public class MockitoExtension implements TestInstancePostProcessor, ParameterResolver { + + @Override + public void postProcessTestInstance(Object testInstance, ExtensionContext context) { + MockitoAnnotations.initMocks(testInstance); + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { + return parameterContext.getParameter().isAnnotationPresent(Mock.class); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { + return getMock(parameterContext.getParameter(), extensionContext); + } + + private Object getMock(Parameter parameter, ExtensionContext extensionContext) { + Class mockType = parameter.getType(); + Store mocks = extensionContext.getStore(Namespace.create(MockitoExtension.class, mockType)); + String mockName = getMockName(parameter); + + if (mockName != null) { + return mocks.getOrComputeIfAbsent(mockName, key -> mock(mockType, mockName)); + } + else { + return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(), key -> mock(mockType)); + } + } + + private String getMockName(Parameter parameter) { + String explicitMockName = parameter.getAnnotation(Mock.class).name().trim(); + if (!explicitMockName.isEmpty()) { + return explicitMockName; + } + else if (parameter.isNamePresent()) { + return parameter.getName(); + } + return null; + } + +} \ No newline at end of file diff --git a/junit5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java b/junit5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java new file mode 100644 index 0000000000..1ddab0531a --- /dev/null +++ b/junit5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java @@ -0,0 +1,122 @@ +package com.baeldung.junit5.mockito; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.baeldung.junit5.mockito.repository.MailClient; +import com.baeldung.junit5.mockito.repository.SettingRepository; +import com.baeldung.junit5.mockito.repository.UserRepository; +import com.baeldung.junit5.mockito.service.DefaultUserService; +import com.baeldung.junit5.mockito.service.Errors; +import com.baeldung.junit5.mockito.service.UserService; + +@RunWith(JUnitPlatform.class) +@ExtendWith(MockitoExtension.class) +public class UserServiceUnitTest { + + UserService userService; + @Mock UserRepository userRepository; + + User user; + + @BeforeEach + void init(@Mock SettingRepository settingRepository, @Mock MailClient mailClient) { + userService = new DefaultUserService(userRepository, settingRepository, mailClient); + when(settingRepository.getUserMinAge()).thenReturn(10); + when(settingRepository.getUserNameMinLength()).thenReturn(4); + when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(false); + } + + @Test + void givenValidUser_whenSaveUser_thenSucceed(@Mock MailClient mailClient) { + // Given + user = new User("Jerry", 12); + when(userRepository.insert(any(User.class))).then(new Answer() { + int sequence = 1; + + @Override + public User answer(InvocationOnMock invocation) throws Throwable { + User user = (User) invocation.getArgument(0); + user.setId(sequence++); + return user; + } + }); + + // When + User insertedUser = userService.register(user); + + // Then + verify(userRepository).insert(user); + Assertions.assertNotNull(user.getId()); + verify(mailClient).sendUserRegistrationMail(insertedUser); + } + + @Test + void givenShortName_whenSaveUser_thenGiveShortUsernameError() { + // Given + user = new User("tom", 12); + + // When + try { + userService.register(user); + fail("Should give an error"); + } catch(Exception ex) { + assertEquals(ex.getMessage(), Errors.USER_NAME_SHORT); + } + + // Then + verify(userRepository, never()).insert(user); + } + + @Test + void givenSmallAge_whenSaveUser_thenGiveYoungUserError() { + // Given + user = new User("jerry", 3); + + // When + try { + userService.register(user); + fail("Should give an error"); + } catch(Exception ex) { + assertEquals(ex.getMessage(), Errors.USER_AGE_YOUNG); + } + + // Then + verify(userRepository, never()).insert(user); + } + + @Test + void givenUserWithExistingName_whenSaveUser_thenGiveUsernameAlreadyExistsError() { + // Given + user = new User("jerry", 12); + Mockito.reset(userRepository); + when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(true); + + // When + try { + userService.register(user); + fail("Should give an error"); + } catch(Exception ex) { + assertEquals(ex.getMessage(), Errors.USER_NAME_DUPLICATE); + } + + // Then + verify(userRepository, never()).insert(user); + } + +} diff --git a/junit5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java b/junit5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java new file mode 100644 index 0000000000..e7a8a1c1e7 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java @@ -0,0 +1,21 @@ +package com.baeldung.junit5.spring; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.junit5.Greetings; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { SpringTestConfiguration.class }) +public class GreetingsSpringTest { + + @Test + void whenCallingSayHello_thenReturnHello() { + assertTrue("Hello".equals(Greetings.sayHello())); + } + +} diff --git a/junit5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java b/junit5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java new file mode 100644 index 0000000000..7651b2bd41 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java @@ -0,0 +1,8 @@ +package com.baeldung.junit5.spring; + +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SpringTestConfiguration { + +} diff --git a/libraries-data/src/test/java/com/baeldung/ormlite/ORMLiteTest.java b/libraries-data/src/test/java/com/baeldung/ormlite/ORMLiteIntegrationTest.java similarity index 99% rename from libraries-data/src/test/java/com/baeldung/ormlite/ORMLiteTest.java rename to libraries-data/src/test/java/com/baeldung/ormlite/ORMLiteIntegrationTest.java index 26eb481286..5a713902b4 100644 --- a/libraries-data/src/test/java/com/baeldung/ormlite/ORMLiteTest.java +++ b/libraries-data/src/test/java/com/baeldung/ormlite/ORMLiteIntegrationTest.java @@ -16,7 +16,7 @@ import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.jdbc.JdbcPooledConnectionSource; import com.j256.ormlite.table.TableUtils; -public class ORMLiteTest { +public class ORMLiteIntegrationTest { private static JdbcPooledConnectionSource connectionSource; private static Dao libraryDao; diff --git a/libraries-data/src/test/java/com/baeldung/reladomo/ReladomoTest.java b/libraries-data/src/test/java/com/baeldung/reladomo/ReladomoIntegrationTest.java similarity index 96% rename from libraries-data/src/test/java/com/baeldung/reladomo/ReladomoTest.java rename to libraries-data/src/test/java/com/baeldung/reladomo/ReladomoIntegrationTest.java index 61c29e8aa3..3660d9a8e1 100644 --- a/libraries-data/src/test/java/com/baeldung/reladomo/ReladomoTest.java +++ b/libraries-data/src/test/java/com/baeldung/reladomo/ReladomoIntegrationTest.java @@ -9,7 +9,7 @@ import org.junit.Test; import com.gs.fw.common.mithra.test.ConnectionManagerForTests; import com.gs.fw.common.mithra.test.MithraTestResource; -public class ReladomoTest { +public class ReladomoIntegrationTest { private MithraTestResource mithraTestResource; @Before diff --git a/libraries/pom.xml b/libraries/pom.xml index b519b9cd53..25c1113fea 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> parent-modules com.baeldung @@ -105,6 +105,13 @@ + + maven-compiler-plugin + + 1.8 + 1.8 + + @@ -326,6 +333,11 @@ datanucleus-xml 5.0.0-release + + org.datanucleus + datanucleus-jdo-query + 5.0.2 + net.openhft chronicle @@ -546,29 +558,29 @@ ${protonpack.version} - org.functionaljava - functionaljava - 4.7 - - - org.functionaljava - functionaljava-java8 - 4.7 + org.functionaljava + functionaljava + 4.7 - org.functionaljava - functionaljava-quickcheck - 4.7 - - - org.functionaljava - functionaljava-java-core - 4.7 + org.functionaljava + functionaljava-java8 + 4.7 - javax.cache - cache-api - ${cache.version} + org.functionaljava + functionaljava-quickcheck + 4.7 + + + org.functionaljava + functionaljava-java-core + 4.7 + + + javax.cache + cache-api + ${cache.version} com.hazelcast @@ -581,7 +593,7 @@ 1.0.1 - com.netopyr.wurmloch + com.netopyr.wurmloch wurmloch-crdt ${crdt.version} @@ -600,6 +612,16 @@ caffeine ${caffeine.version} + + org.bouncycastle + bcprov-jdk15on + 1.58 + + + org.bouncycastle + bcpkix-jdk15on + 1.58 + diff --git a/libraries/src/main/java/com/baeldung/bouncycastle/BouncyCastleCrypto.java b/libraries/src/main/java/com/baeldung/bouncycastle/BouncyCastleCrypto.java new file mode 100644 index 0000000000..5d8a7a6643 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/bouncycastle/BouncyCastleCrypto.java @@ -0,0 +1,111 @@ +package com.baeldung.bouncycastle; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.security.PrivateKey; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.cms.ContentInfo; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.jcajce.JcaCertStore; +import org.bouncycastle.cms.CMSAlgorithm; +import org.bouncycastle.cms.CMSEnvelopedData; +import org.bouncycastle.cms.CMSEnvelopedDataGenerator; +import org.bouncycastle.cms.CMSException; +import org.bouncycastle.cms.CMSProcessableByteArray; +import org.bouncycastle.cms.CMSSignedData; +import org.bouncycastle.cms.CMSSignedDataGenerator; +import org.bouncycastle.cms.CMSTypedData; +import org.bouncycastle.cms.KeyTransRecipientInformation; +import org.bouncycastle.cms.RecipientInformation; +import org.bouncycastle.cms.SignerInformation; +import org.bouncycastle.cms.SignerInformationStore; +import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; +import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder; +import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder; +import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient; +import org.bouncycastle.cms.jcajce.JceKeyTransRecipient; +import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.OutputEncryptor; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; +import org.bouncycastle.util.Store; + +public class BouncyCastleCrypto { + + public static byte[] signData(byte[] data, final X509Certificate signingCertificate, final PrivateKey signingKey) + throws CertificateEncodingException, OperatorCreationException, CMSException, IOException { + byte[] signedMessage = null; + List certList = new ArrayList(); + CMSTypedData cmsData = new CMSProcessableByteArray(data); + certList.add(signingCertificate); + Store certs = new JcaCertStore(certList); + CMSSignedDataGenerator cmsGenerator = new CMSSignedDataGenerator(); + ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey); + cmsGenerator.addSignerInfoGenerator( + new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()) + .build(contentSigner, signingCertificate)); + cmsGenerator.addCertificates(certs); + CMSSignedData cms = cmsGenerator.generate(cmsData, true); + signedMessage = cms.getEncoded(); + return signedMessage; + } + + public static boolean verifSignData(final byte[] signedData) + throws CMSException, IOException, OperatorCreationException, CertificateException { + ByteArrayInputStream bIn = new ByteArrayInputStream(signedData); + ASN1InputStream aIn = new ASN1InputStream(bIn); + CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); + aIn.close(); + bIn.close(); + Store certs = s.getCertificates(); + SignerInformationStore signers = s.getSignerInfos(); + Collection c = signers.getSigners(); + SignerInformation signer = c.iterator().next(); + Collection certCollection = certs.getMatches(signer.getSID()); + Iterator certIt = certCollection.iterator(); + X509CertificateHolder certHolder = certIt.next(); + boolean verifResult = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder)); + if (!verifResult) { + return false; + } + return true; + } + + public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) + throws CertificateEncodingException, CMSException, IOException { + byte[] encryptedData = null; + if (null != data && null != encryptionCertificate) { + CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator(); + JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate); + cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey); + CMSTypedData msg = new CMSProcessableByteArray(data); + OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC") + .build(); + CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor); + encryptedData = cmsEnvelopedData.getEncoded(); + } + return encryptedData; + } + + public static byte[] decryptData(final byte[] encryptedData, final PrivateKey decryptionKey) throws CMSException { + byte[] decryptedData = null; + if (null != encryptedData && null != decryptionKey) { + CMSEnvelopedData envelopedData = new CMSEnvelopedData(encryptedData); + Collection recip = envelopedData.getRecipientInfos().getRecipients(); + KeyTransRecipientInformation recipientInfo = (KeyTransRecipientInformation) recip.iterator().next(); + JceKeyTransRecipient recipient = new JceKeyTransEnvelopedRecipient(decryptionKey); + decryptedData = recipientInfo.getContent(recipient); + } + return decryptedData; + } +} diff --git a/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java b/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java new file mode 100644 index 0000000000..384dde48d1 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java @@ -0,0 +1,104 @@ +package com.baeldung.jdo.query; + +import java.util.List; + +import javax.jdo.JDOQLTypedQuery; +import javax.jdo.PersistenceManager; +import javax.jdo.PersistenceManagerFactory; +import javax.jdo.Query; + +import org.datanucleus.api.jdo.JDOPersistenceManagerFactory; +import org.datanucleus.metadata.PersistenceUnitMetaData; + +public class MyApp { + + private static PersistenceManagerFactory pmf; + private static PersistenceManager pm; + + public static void main(String[] args) { + + defineDynamicPersistentUnit(); + createTestData(); + queryUsingJDOQL(); + queryUsingTypedJDOQL(); + queryUsingSQL(); + queryUsingJPQL(); + + } + + public static void createTestData(){ + ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut",5); + ProductItem item2 = new ProductItem("pro2", "price less than 10","InStock", 8); + ProductItem item3 = new ProductItem("pro3", "price more than 10","SoldOut", 15); + + if( pm != null ){ + pm.makePersistent(item1); + pm.makePersistent(item2); + pm.makePersistent(item3); + } + } + + public static void defineDynamicPersistentUnit(){ + + PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); + pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db"); + pumd.addProperty("javax.jdo.option.ConnectionUserName", "root"); + pumd.addProperty("javax.jdo.option.ConnectionPassword", "admin"); + pumd.addProperty("javax.jdo.option.ConnectionDriverName", "com.mysql.jdbc.Driver"); + pumd.addProperty("datanucleus.schema.autoCreateAll", "true"); + + pmf = new JDOPersistenceManagerFactory(pumd, null); + pm = pmf.getPersistenceManager(); + } + + public static void queryUsingJDOQL(){ + + Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " + + "WHERE price < threshold PARAMETERS double threshold"); + List explicitParamResults = (List)query.execute(10); + + query = pm.newQuery("SELECT FROM " + + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); + query.setParameters("double threshold"); + List explicitParamResults2 = (List)query.execute(10); + + query = pm.newQuery("SELECT FROM " + + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); + List implicitParamResults = (List)query.execute(10); + + } + + public static void queryUsingTypedJDOQL(){ + + JDOQLTypedQuery tq = pm.newJDOQLTypedQuery(ProductItem.class); + QProductItem cand = QProductItem.candidate(); + tq=tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro"))); + List results = tq.executeList(); + + } + + public static void queryUsingSQL(){ + + Query query = pm.newQuery("javax.jdo.query.SQL","select * from " + + "product_item where price < ? and status = ?"); + query.setClass(ProductItem.class); + query.setParameters(10,"InStock"); + List results = query.executeList(); + + } + + public static void queryUsingJPQL(){ + Query query = pm.newQuery("JPQL","select i from " + + "com.baeldung.jdo.query.ProductItem i where i.price < 10" + + " and i.status = 'InStock'"); + List results = (List) query.execute(); + + } + + public static void namedQuery(){ + Query query = pm.newNamedQuery( + ProductItem.class, "PriceBelow10"); + List results = query.executeList(); + + } +} diff --git a/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java b/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java new file mode 100644 index 0000000000..52221a7d97 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java @@ -0,0 +1,68 @@ +package com.baeldung.jdo.query; + +import javax.jdo.annotations.IdGeneratorStrategy; +import javax.jdo.annotations.PersistenceAware; +import javax.jdo.annotations.PersistenceCapable; +import javax.jdo.annotations.Persistent; +import javax.jdo.annotations.PrimaryKey; + +@PersistenceCapable(table = "product_item") +public class ProductItem { + + @PrimaryKey + @Persistent(valueStrategy=IdGeneratorStrategy.INCREMENT) + int id; + String name; + String description; + String status; + double price; + + public ProductItem(){ + + } + + public ProductItem(String name,String description,String status,double price){ + this.name=name; + this.description = description; + this.status = status; + this.price = price; + } + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public double getPrice() { + return price; + } + public void setPrice(double price) { + this.price = price; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + +} diff --git a/libraries/src/main/resources/Baeldung.cer b/libraries/src/main/resources/Baeldung.cer new file mode 100644 index 0000000000..72d0918424 --- /dev/null +++ b/libraries/src/main/resources/Baeldung.cer @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDPjCCAiagAwIBAgIJAPvd1gx14C3CMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNV +BAYTAk1BMRAwDgYDVQQIEwdNb3JvY2NvMRMwEQYDVQQHEwpDYXNhYmxhbmNhMREw +DwYDVQQDEwhCYWVsZHVuZzAeFw0xNzEwMTIxMDQzMTRaFw0yNzEwMTMxMDQzMTRa +MEcxCzAJBgNVBAYTAk1BMRAwDgYDVQQIEwdNb3JvY2NvMRMwEQYDVQQHEwpDYXNh +YmxhbmNhMREwDwYDVQQDEwhCYWVsZHVuZzCCASIwDQYJKoZIhvcNAQEBBQADggEP +ADCCAQoCggEBAMyi5GmOeN4QaH/CP5gSOyHX8znb5TDHWV8wc+ZT7kNU8zt5tGMh +jozK6hax155/6tOsBDR0rSYBhL+Dm/+uCVS7qOlRHhf6cNGtzGF1gnNJB2WjI8oM +AYm24xpLj1WphKUwKrn3nTMPnQup5OoNAMYl99flANrRYVjjxrLQvDZDUio6Iujr +CZ2TtXGM0g/gP++28KT7g1KlUui3xtB0u33wx7UN8Fix3JmjOaPHGwxGpwP3VGSj +fs8cuhqVwRQaZpCOoHU/P8wpXKw80sSdhz+SRueMPtVYqK0CiLL5/O0h0Y3le4IV +whgg3KG1iTGOWn60UMFn1EYmQ18k5Nsma6UCAwEAAaMtMCswCQYDVR0TBAIwADAR +BglghkgBhvhCAQEEBAMCBPAwCwYDVR0PBAQDAgUgMA0GCSqGSIb3DQEBBQUAA4IB +AQC8DDBmJ3p4xytxBiE0s4p1715WT6Dm/QJHp0XC0hkSoyZKDh+XVmrzm+J3SiW1 +vpswb5hLgPo040YX9jnDmgOD+TpleTuKHxZRYj92UYWmdjkWLVtFMcvOh+gxBiAP +pHIqZsqo8lfcyAuh8Jx834IXbknfCUtERDLG/rU9P/3XJhrM2GC5qPQznrW4EYhU +CGPyIJXmvATMVvXMWCtfogAL+n42vjYXQXZoAWomHhLHoNbSJUErnNdWDOh4WoJt +XJCxA6U5LSBplqb3wB2hUTqw+0admKltvmy+KA1PD7OxoGiY7V544zeGqJam1qxU +ia7y5BL6uOa/4ShSV8pcJDYz +-----END CERTIFICATE----- diff --git a/libraries/src/main/resources/Baeldung.p12 b/libraries/src/main/resources/Baeldung.p12 new file mode 100644 index 0000000000..65ec8bc8fe Binary files /dev/null and b/libraries/src/main/resources/Baeldung.p12 differ diff --git a/libraries/src/main/resources/META-INF/package.jdo b/libraries/src/main/resources/META-INF/package.jdo index d30207e2e0..d3cf501bb6 100644 --- a/libraries/src/main/resources/META-INF/package.jdo +++ b/libraries/src/main/resources/META-INF/package.jdo @@ -16,6 +16,14 @@ - + + + + + + + + \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java index d17a7dcf1b..7ca656efbf 100644 --- a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java +++ b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.awaitility; -import org.awaitility.Awaitility; import org.awaitility.Duration; import org.junit.Before; import org.junit.Test; diff --git a/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java b/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java new file mode 100644 index 0000000000..3965eeecd4 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java @@ -0,0 +1,53 @@ +package com.baeldung.bouncycastle; + +import static org.junit.Assert.assertTrue; + +import java.io.FileInputStream; +import java.io.IOException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PrivateKey; +import java.security.Security; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +import org.bouncycastle.cms.CMSException; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.OperatorCreationException; +import org.junit.Test; + +public class BouncyCastleLiveTest { + + String certificatePath = "src/main/resources/Baeldung.cer"; + String privateKeyPath = "src/main/resources/Baeldung.p12"; + char[] p12Password = "password".toCharArray(); + char[] keyPassword = "password".toCharArray(); + + @Test + public void givenCryptographicResource_whenOperationSuccess_returnTrue() + throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException, + KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException { + Security.addProvider(new BouncyCastleProvider()); + + CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC"); + X509Certificate certificate = (X509Certificate) certFactory + .generateCertificate(new FileInputStream(certificatePath)); + KeyStore keystore = KeyStore.getInstance("PKCS12"); + keystore.load(new FileInputStream(privateKeyPath), p12Password); + PrivateKey privateKey = (PrivateKey) keystore.getKey("baeldung", keyPassword); + String secretMessage = "My password is 123456Seven"; + System.out.println("Original Message : " + secretMessage); + byte[] stringToEncrypt = secretMessage.getBytes(); + byte[] encryptedData = BouncyCastleCrypto.encryptData(stringToEncrypt, certificate); + byte[] rawData = BouncyCastleCrypto.decryptData(encryptedData, privateKey); + String decryptedMessage = new String(rawData); + assertTrue(decryptedMessage.equals(secretMessage)); + byte[] signedData = BouncyCastleCrypto.signData(rawData, certificate, privateKey); + Boolean check = BouncyCastleCrypto.verifSignData(signedData); + assertTrue(check); + } +} diff --git a/log4j/pom.xml b/log4j/pom.xml index 2e73baac49..20906c4c05 100644 --- a/log4j/pom.xml +++ b/log4j/pom.xml @@ -26,12 +26,6 @@ ${log4j.version} - - log4j - apache-log4j-extras - ${log4j.version} - - org.apache.logging.log4j diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java b/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java new file mode 100644 index 0000000000..4de9a88dcc --- /dev/null +++ b/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java @@ -0,0 +1,62 @@ +package org.baeldung.mockito; + +import org.junit.Test; +import org.junit.runner.RunWith; +import static org.junit.Assert.assertEquals; + +import static org.mockito.Mockito.*; +import org.mockito.ArgumentCaptor; +import static org.mockito.Matchers.any; +import org.mockito.stubbing.Answer; +import org.mockito.runners.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class MockitoVoidMethodsTest { + + @Test + public void whenAddCalledVerified() { + MyList mockVoid = mock(MyList.class); + mockVoid.add(0, ""); + verify(mockVoid, times(1)).add(0, ""); + } + + @Test(expected = Exception.class) + public void givenNull_addThrows() { + MyList mockVoid = mock(MyList.class); + doThrow().when(mockVoid).add(isA(Integer.class), isNull()); + mockVoid.add(0, null); + } + + @Test + public void whenAddCalledValueCaptured() { + MyList mockVoid = mock(MyList.class); + ArgumentCaptor valueCapture = ArgumentCaptor.forClass(String.class); + doNothing().when(mockVoid).add(any(Integer.class), valueCapture.capture()); + mockVoid.add(0, "captured"); + assertEquals("captured", valueCapture.getValue()); + } + + @Test + public void whenAddCalledAnswered() { + MyList mockVoid = mock(MyList.class); + doAnswer((Answer) invocation -> { + Object arg0 = invocation.getArgument(0); + Object arg1 = invocation.getArgument(1); + + //do something with the arguments here + assertEquals(3, arg0); + assertEquals("answer me", arg1); + + return null; + }).when(mockVoid).add(any(Integer.class), any(String.class)); + mockVoid.add(3, "answer me"); + } + + @Test + public void whenAddCalledRealMethodCalled() { + MyList mockVoid = mock(MyList.class); + doCallRealMethod().when(mockVoid).add(any(Integer.class), any(String.class)); + mockVoid.add(1, "real"); + verify(mockVoid, times(1)).add(1, "real"); + } +} diff --git a/mockito/src/test/java/org/baeldung/mockito/MyList.java b/mockito/src/test/java/org/baeldung/mockito/MyList.java index be69ef8a8a..0b501225ad 100644 --- a/mockito/src/test/java/org/baeldung/mockito/MyList.java +++ b/mockito/src/test/java/org/baeldung/mockito/MyList.java @@ -14,4 +14,9 @@ class MyList extends AbstractList { return 1; } + @Override + public void add(int index, String element) { + // no-op + } + } diff --git a/patterns/template-method/pom.xml b/patterns/template-method/pom.xml new file mode 100644 index 0000000000..c3b6a084ac --- /dev/null +++ b/patterns/template-method/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + com.baeldung.templatemethodpattern + templatemethodpattern + 1.0 + jar + + UTF-8 + 1.8 + 1.8 + + + + junit + junit + 4.12 + test + + + \ No newline at end of file diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/application/Application.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/application/Application.java new file mode 100644 index 0000000000..581c774f52 --- /dev/null +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/application/Application.java @@ -0,0 +1,18 @@ +package com.baeldung.templatemethodpattern.application; + +import com.baeldung.templatemethodpattern.model.Computer; +import com.baeldung.templatemethodpattern.model.HighEndComputer; +import com.baeldung.templatemethodpattern.model.StandardComputer; + +public class Application { + + public static void main(String[] args) { + Computer standardComputer = new StandardComputer(); + standardComputer.buildComputer(); + standardComputer.getComputerParts().forEach((k, v) -> System.out.println("Part : " + k + " Value : " + v)); + + Computer highEndComputer = new HighEndComputer(); + highEndComputer.buildComputer(); + highEndComputer.getComputerParts().forEach((k, v) -> System.out.println("Part : " + k + " Value : " + v)); + } +} diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java new file mode 100644 index 0000000000..c5d1a2cde8 --- /dev/null +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java @@ -0,0 +1,34 @@ +package com.baeldung.templatemethodpattern.model; + +import java.util.HashMap; +import java.util.Map; + +public abstract class Computer { + + protected Map computerParts = new HashMap<>(); + + public final void buildComputer() { + addMotherboard(); + addProcessor(); + addMemory(); + addHardDrive(); + addGraphicCard(); + addSoundCard(); + } + + public abstract void addProcessor(); + + public abstract void addMotherboard(); + + public abstract void addMemory(); + + public abstract void addHardDrive(); + + public abstract void addGraphicCard(); + + public abstract void addSoundCard(); + + public Map getComputerParts() { + return computerParts; + } +} diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java new file mode 100644 index 0000000000..11baeca6f7 --- /dev/null +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java @@ -0,0 +1,34 @@ +package com.baeldung.templatemethodpattern.model; + +public class HighEndComputer extends Computer { + + @Override + public void addProcessor() { + computerParts.put("Processor", "High End Processor"); + } + + @Override + public void addMotherboard() { + computerParts.put("Motherboard", "High End Motherboard"); + } + + @Override + public void addMemory() { + computerParts.put("Memory", "16GB"); + } + + @Override + public void addHardDrive() { + computerParts.put("Hard Drive", "2TB Hard Drive"); + } + + @Override + public void addGraphicCard() { + computerParts.put("Graphic Card", "High End Graphic Card"); + } + + @Override + public void addSoundCard() { + computerParts.put("Sound Card", "High End Sound Card"); + } +} diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java new file mode 100644 index 0000000000..22ff370203 --- /dev/null +++ b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java @@ -0,0 +1,34 @@ +package com.baeldung.templatemethodpattern.model; + +public class StandardComputer extends Computer { + + @Override + public void addProcessor() { + computerParts.put("Processor", "Standard Processor"); + } + + @Override + public void addMotherboard() { + computerParts.put("Motherboard", "Standard Motherboard"); + } + + @Override + public void addMemory() { + computerParts.put("Memory", "8GB"); + } + + @Override + public void addHardDrive() { + computerParts.put("Hard Drive", "1TB Hard Drive"); + } + + @Override + public void addGraphicCard() { + computerParts.put("Graphic Card", "Standard Graphic Card"); + } + + @Override + public void addSoundCard() { + computerParts.put("Sound Card", "Standard Sound Card"); + } +} diff --git a/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java b/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java new file mode 100644 index 0000000000..afe66883ac --- /dev/null +++ b/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java @@ -0,0 +1,120 @@ +package com.baeldung.templatemethodpatterntest; + +import com.baeldung.templatemethodpattern.model.HighEndComputer; +import com.baeldung.templatemethodpattern.model.StandardComputer; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class TemplateMethodPatternTest { + + private static StandardComputer standardComputer; + private static HighEndComputer highEndComputer; + + @BeforeClass + public static void setUpStandardComputerInstance() { + standardComputer = new StandardComputer(); + } + + @BeforeClass + public static void setUpHighEndComputerInstance() { + highEndComputer = new HighEndComputer(); + } + + @Test + public void givenStandardProcessor_whenAddingProcessor_thenEqualAssertion() { + standardComputer.addProcessor(); + Assert.assertEquals("Standard Processor", standardComputer + .getComputerParts().get("Processor")); + } + + @Test + public void givenStandardMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { + standardComputer.addMotherboard(); + Assert.assertEquals("Standard Motherboard", standardComputer + .getComputerParts().get("Motherboard")); + } + + @Test + public void givenStandardMemory_whenAddingMemory_thenEqualAssertion() { + standardComputer.addMemory(); + Assert.assertEquals("8GB", standardComputer + .getComputerParts().get("Memory")); + } + + @Test + public void givenStandardHardDrive_whenAddingHardDrive_thenEqualAssertion() { + standardComputer.addHardDrive(); + Assert.assertEquals("1TB Hard Drive", standardComputer + .getComputerParts().get("Hard Drive")); + } + + @Test + public void givenStandardGraphicaCard_whenAddingGraphicCard_thenEqualAssertion() { + standardComputer.addGraphicCard(); + Assert.assertEquals("Standard Graphic Card", standardComputer + .getComputerParts().get("Graphic Card")); + } + + @Test + public void givenStandardSoundCard_whenAddingSoundCard_thenEqualAssertion() { + standardComputer.addSoundCard(); + Assert.assertEquals("Standard Sound Card", standardComputer + .getComputerParts().get("Sound Card")); + } + + @Test + public void givenAllStandardParts_whenBuildingComputer_thenSixParts() { + standardComputer.buildComputer(); + Assert.assertEquals(6, standardComputer + .getComputerParts().size()); + } + + @Test + public void givenHightEndProcessor_whenAddingProcessor_thenEqualAssertion() { + highEndComputer.addProcessor(); + Assert.assertEquals("High End Processor", highEndComputer + .getComputerParts().get("Processor")); + } + + @Test + public void givenHighEnddMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { + highEndComputer.addMotherboard(); + Assert.assertEquals("High End Motherboard", highEndComputer + .getComputerParts().get("Motherboard")); + } + + @Test + public void givenHighEndMemory_whenAddingMemory_thenEqualAssertion() { + highEndComputer.addMemory(); + Assert.assertEquals("16GB", highEndComputer + .getComputerParts().get("Memory")); + } + + @Test + public void givenHighEndHardDrive_whenAddingHardDrive_thenEqualAssertion() { + highEndComputer.addHardDrive(); + Assert.assertEquals("2TB Hard Drive", highEndComputer + .getComputerParts().get("Hard Drive")); + } + + @Test + public void givenHighEndGraphicCard_whenAddingGraphicCard_thenEqualAssertion() { + highEndComputer.addGraphicCard(); + Assert.assertEquals("High End Graphic Card", highEndComputer + .getComputerParts().get("Graphic Card")); + } + + @Test + public void givenHighEndSoundCard_whenAddingSoundCard_thenEqualAssertion() { + highEndComputer.addSoundCard(); + Assert.assertEquals("High End Sound Card", highEndComputer + .getComputerParts().get("Sound Card")); + } + + @Test + public void givenAllHighEndParts_whenBuildingComputer_thenSixParts() { + highEndComputer.buildComputer(); + Assert.assertEquals(6, highEndComputer.getComputerParts().size()); + } +} diff --git a/java-cassandra/README.md b/persistence-modules/java-cassandra/README.md similarity index 100% rename from java-cassandra/README.md rename to persistence-modules/java-cassandra/README.md diff --git a/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml similarity index 98% rename from java-cassandra/pom.xml rename to persistence-modules/java-cassandra/pom.xml index 12df920e7d..faaabb9e2e 100644 --- a/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java similarity index 100% rename from java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java rename to persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java similarity index 100% rename from java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java rename to persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraConnector.java diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java similarity index 100% rename from java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java rename to persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java similarity index 100% rename from java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java rename to persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java similarity index 100% rename from java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java rename to persistence-modules/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepository.java diff --git a/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java b/persistence-modules/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java similarity index 100% rename from java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java rename to persistence-modules/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/BookRepositoryIntegrationTest.java diff --git a/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java b/persistence-modules/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java similarity index 100% rename from java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java rename to persistence-modules/java-cassandra/src/test/java/com/baeldung/cassandra/java/client/repository/KeyspaceRepositoryIntegrationTest.java diff --git a/java-mongodb/.gitignore b/persistence-modules/java-mongodb/.gitignore similarity index 100% rename from java-mongodb/.gitignore rename to persistence-modules/java-mongodb/.gitignore diff --git a/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md similarity index 100% rename from java-mongodb/README.md rename to persistence-modules/java-mongodb/README.md diff --git a/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml similarity index 97% rename from java-mongodb/pom.xml rename to persistence-modules/java-mongodb/pom.xml index 304d961b0a..aab48921a6 100644 --- a/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/java-mongodb/src/main/java/com/baeldung/MongoExample.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/MongoExample.java similarity index 100% rename from java-mongodb/src/main/java/com/baeldung/MongoExample.java rename to persistence-modules/java-mongodb/src/main/java/com/baeldung/MongoExample.java diff --git a/java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java similarity index 100% rename from java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java rename to persistence-modules/java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java diff --git a/liquibase/README.md b/persistence-modules/liquibase/README.md similarity index 100% rename from liquibase/README.md rename to persistence-modules/liquibase/README.md diff --git a/liquibase/pom.xml b/persistence-modules/liquibase/pom.xml similarity index 96% rename from liquibase/pom.xml rename to persistence-modules/liquibase/pom.xml index d26acc8c98..020c2516a2 100644 --- a/liquibase/pom.xml +++ b/persistence-modules/liquibase/pom.xml @@ -6,6 +6,7 @@ parent-modules com.baeldung 1.0.0-SNAPSHOT + ../ 4.0.0 diff --git a/liquibase/src/main/resources/liquibase/db-changelog.xml b/persistence-modules/liquibase/src/main/resources/liquibase/db-changelog.xml similarity index 100% rename from liquibase/src/main/resources/liquibase/db-changelog.xml rename to persistence-modules/liquibase/src/main/resources/liquibase/db-changelog.xml diff --git a/liquibase/src/main/resources/liquibase/liquibase.properties b/persistence-modules/liquibase/src/main/resources/liquibase/liquibase.properties similarity index 100% rename from liquibase/src/main/resources/liquibase/liquibase.properties rename to persistence-modules/liquibase/src/main/resources/liquibase/liquibase.properties diff --git a/querydsl/README.md b/persistence-modules/querydsl/README.md similarity index 100% rename from querydsl/README.md rename to persistence-modules/querydsl/README.md diff --git a/querydsl/pom.xml b/persistence-modules/querydsl/pom.xml similarity index 99% rename from querydsl/pom.xml rename to persistence-modules/querydsl/pom.xml index 6c968f01e4..27f383e0c6 100644 --- a/querydsl/pom.xml +++ b/persistence-modules/querydsl/pom.xml @@ -15,6 +15,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/querydsl/src/main/java/org/baeldung/dao/PersonDao.java b/persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDao.java similarity index 100% rename from querydsl/src/main/java/org/baeldung/dao/PersonDao.java rename to persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDao.java diff --git a/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java b/persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java similarity index 100% rename from querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java rename to persistence-modules/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java diff --git a/querydsl/src/main/java/org/baeldung/entity/Person.java b/persistence-modules/querydsl/src/main/java/org/baeldung/entity/Person.java similarity index 100% rename from querydsl/src/main/java/org/baeldung/entity/Person.java rename to persistence-modules/querydsl/src/main/java/org/baeldung/entity/Person.java diff --git a/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java b/persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java similarity index 100% rename from querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java rename to persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java diff --git a/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java b/persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java similarity index 100% rename from querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java rename to persistence-modules/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java diff --git a/querydsl/src/main/resources/META-INF/persistence.xml b/persistence-modules/querydsl/src/main/resources/META-INF/persistence.xml similarity index 100% rename from querydsl/src/main/resources/META-INF/persistence.xml rename to persistence-modules/querydsl/src/main/resources/META-INF/persistence.xml diff --git a/querydsl/src/main/resources/logback.xml b/persistence-modules/querydsl/src/main/resources/logback.xml similarity index 100% rename from querydsl/src/main/resources/logback.xml rename to persistence-modules/querydsl/src/main/resources/logback.xml diff --git a/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java b/persistence-modules/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java similarity index 100% rename from querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java rename to persistence-modules/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java diff --git a/querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLIntegrationTest.java b/persistence-modules/querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLIntegrationTest.java similarity index 100% rename from querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLIntegrationTest.java rename to persistence-modules/querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLIntegrationTest.java diff --git a/querydsl/src/test/resources/db.properties b/persistence-modules/querydsl/src/test/resources/db.properties similarity index 100% rename from querydsl/src/test/resources/db.properties rename to persistence-modules/querydsl/src/test/resources/db.properties diff --git a/querydsl/src/test/resources/test-context.xml b/persistence-modules/querydsl/src/test/resources/test-context.xml similarity index 100% rename from querydsl/src/test/resources/test-context.xml rename to persistence-modules/querydsl/src/test/resources/test-context.xml diff --git a/querydsl/src/test/resources/test-db.xml b/persistence-modules/querydsl/src/test/resources/test-db.xml similarity index 100% rename from querydsl/src/test/resources/test-db.xml rename to persistence-modules/querydsl/src/test/resources/test-db.xml diff --git a/redis/README.md b/persistence-modules/redis/README.md similarity index 100% rename from redis/README.md rename to persistence-modules/redis/README.md diff --git a/redis/pom.xml b/persistence-modules/redis/pom.xml similarity index 96% rename from redis/pom.xml rename to persistence-modules/redis/pom.xml index db454188a7..ef081a2c69 100644 --- a/redis/pom.xml +++ b/persistence-modules/redis/pom.xml @@ -15,6 +15,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/redis/src/main/java/com/baeldung/CustomMessage.java b/persistence-modules/redis/src/main/java/com/baeldung/CustomMessage.java similarity index 100% rename from redis/src/main/java/com/baeldung/CustomMessage.java rename to persistence-modules/redis/src/main/java/com/baeldung/CustomMessage.java diff --git a/redis/src/main/java/com/baeldung/Ledger.java b/persistence-modules/redis/src/main/java/com/baeldung/Ledger.java similarity index 100% rename from redis/src/main/java/com/baeldung/Ledger.java rename to persistence-modules/redis/src/main/java/com/baeldung/Ledger.java diff --git a/redis/src/main/java/com/baeldung/LedgerLiveObject.java b/persistence-modules/redis/src/main/java/com/baeldung/LedgerLiveObject.java similarity index 100% rename from redis/src/main/java/com/baeldung/LedgerLiveObject.java rename to persistence-modules/redis/src/main/java/com/baeldung/LedgerLiveObject.java diff --git a/redis/src/main/java/com/baeldung/LedgerServiceImpl.java b/persistence-modules/redis/src/main/java/com/baeldung/LedgerServiceImpl.java similarity index 100% rename from redis/src/main/java/com/baeldung/LedgerServiceImpl.java rename to persistence-modules/redis/src/main/java/com/baeldung/LedgerServiceImpl.java diff --git a/redis/src/main/java/com/baeldung/LedgerServiceInterface.java b/persistence-modules/redis/src/main/java/com/baeldung/LedgerServiceInterface.java similarity index 100% rename from redis/src/main/java/com/baeldung/LedgerServiceInterface.java rename to persistence-modules/redis/src/main/java/com/baeldung/LedgerServiceInterface.java diff --git a/redis/src/main/resources/singleNodeConfig.json b/persistence-modules/redis/src/main/resources/singleNodeConfig.json similarity index 100% rename from redis/src/main/resources/singleNodeConfig.json rename to persistence-modules/redis/src/main/resources/singleNodeConfig.json diff --git a/redis/src/main/resources/singleNodeConfig.yaml b/persistence-modules/redis/src/main/resources/singleNodeConfig.yaml similarity index 100% rename from redis/src/main/resources/singleNodeConfig.yaml rename to persistence-modules/redis/src/main/resources/singleNodeConfig.yaml diff --git a/redis/src/test/java/com/baeldung/JedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java similarity index 100% rename from redis/src/test/java/com/baeldung/JedisIntegrationTest.java rename to persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java diff --git a/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java similarity index 100% rename from redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java rename to persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java diff --git a/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java similarity index 100% rename from redis/src/test/java/com/baeldung/RedissonIntegrationTest.java rename to persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java diff --git a/solr/README.md b/persistence-modules/solr/README.md similarity index 100% rename from solr/README.md rename to persistence-modules/solr/README.md diff --git a/solr/pom.xml b/persistence-modules/solr/pom.xml similarity index 93% rename from solr/pom.xml rename to persistence-modules/solr/pom.xml index 1b26a21edc..2fd0bdd721 100644 --- a/solr/pom.xml +++ b/persistence-modules/solr/pom.xml @@ -12,6 +12,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/solr/src/main/java/com/baeldung/solr/fulltext/search/model/Item.java b/persistence-modules/solr/src/main/java/com/baeldung/solr/fulltext/search/model/Item.java similarity index 100% rename from solr/src/main/java/com/baeldung/solr/fulltext/search/model/Item.java rename to persistence-modules/solr/src/main/java/com/baeldung/solr/fulltext/search/model/Item.java diff --git a/solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchService.java b/persistence-modules/solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchService.java similarity index 100% rename from solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchService.java rename to persistence-modules/solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchService.java diff --git a/solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceImpl.java b/persistence-modules/solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceImpl.java similarity index 100% rename from solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceImpl.java rename to persistence-modules/solr/src/main/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceImpl.java diff --git a/solr/src/test/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceLiveTest.java b/persistence-modules/solr/src/test/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceLiveTest.java similarity index 100% rename from solr/src/test/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceLiveTest.java rename to persistence-modules/solr/src/test/java/com/baeldung/solr/fulltext/search/service/ItemSearchServiceLiveTest.java diff --git a/spring-data-cassandra/README.md b/persistence-modules/spring-data-cassandra/README.md similarity index 100% rename from spring-data-cassandra/README.md rename to persistence-modules/spring-data-cassandra/README.md diff --git a/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml similarity index 99% rename from spring-data-cassandra/pom.xml rename to persistence-modules/spring-data-cassandra/pom.xml index fbc2071134..607d7b90ba 100644 --- a/spring-data-cassandra/pom.xml +++ b/persistence-modules/spring-data-cassandra/pom.xml @@ -13,6 +13,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java b/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java similarity index 100% rename from spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java rename to persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java diff --git a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java b/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java similarity index 100% rename from spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java rename to persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java diff --git a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java b/persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java similarity index 100% rename from spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java rename to persistence-modules/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java diff --git a/spring-data-cassandra/src/main/resources/cassandra.properties b/persistence-modules/spring-data-cassandra/src/main/resources/cassandra.properties similarity index 100% rename from spring-data-cassandra/src/main/resources/cassandra.properties rename to persistence-modules/spring-data-cassandra/src/main/resources/cassandra.properties diff --git a/spring-data-cassandra/src/main/resources/logback.xml b/persistence-modules/spring-data-cassandra/src/main/resources/logback.xml similarity index 100% rename from spring-data-cassandra/src/main/resources/logback.xml rename to persistence-modules/spring-data-cassandra/src/main/resources/logback.xml diff --git a/spring-data-cassandra/src/main/resources/test.png b/persistence-modules/spring-data-cassandra/src/main/resources/test.png similarity index 100% rename from spring-data-cassandra/src/main/resources/test.png rename to persistence-modules/spring-data-cassandra/src/main/resources/test.png diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java similarity index 100% rename from spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java rename to persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java similarity index 100% rename from spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java rename to persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java similarity index 100% rename from spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java rename to persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java diff --git a/spring-data-dynamodb/.gitignore b/persistence-modules/spring-data-dynamodb/.gitignore similarity index 100% rename from spring-data-dynamodb/.gitignore rename to persistence-modules/spring-data-dynamodb/.gitignore diff --git a/spring-data-dynamodb/README.MD b/persistence-modules/spring-data-dynamodb/README.MD similarity index 100% rename from spring-data-dynamodb/README.MD rename to persistence-modules/spring-data-dynamodb/README.MD diff --git a/spring-data-dynamodb/pom.xml b/persistence-modules/spring-data-dynamodb/pom.xml similarity index 96% rename from spring-data-dynamodb/pom.xml rename to persistence-modules/spring-data-dynamodb/pom.xml index 11bbbdf40f..bf90779c29 100644 --- a/spring-data-dynamodb/pom.xml +++ b/persistence-modules/spring-data-dynamodb/pom.xml @@ -12,7 +12,7 @@ parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../../parent-boot-5 diff --git a/spring-data-dynamodb/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/Application.java similarity index 100% rename from spring-data-dynamodb/src/main/java/com/baeldung/Application.java rename to persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/Application.java diff --git a/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java similarity index 100% rename from spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java rename to persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java diff --git a/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/model/ProductInfo.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/model/ProductInfo.java similarity index 100% rename from spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/model/ProductInfo.java rename to persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/model/ProductInfo.java diff --git a/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java similarity index 100% rename from spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java rename to persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java diff --git a/spring-data-dynamodb/src/main/resources/application.properties b/persistence-modules/spring-data-dynamodb/src/main/resources/application.properties similarity index 100% rename from spring-data-dynamodb/src/main/resources/application.properties rename to persistence-modules/spring-data-dynamodb/src/main/resources/application.properties diff --git a/spring-data-dynamodb/src/main/resources/demo.properties b/persistence-modules/spring-data-dynamodb/src/main/resources/demo.properties similarity index 100% rename from spring-data-dynamodb/src/main/resources/demo.properties rename to persistence-modules/spring-data-dynamodb/src/main/resources/demo.properties diff --git a/spring-data-dynamodb/src/main/resources/logback.xml b/persistence-modules/spring-data-dynamodb/src/main/resources/logback.xml similarity index 100% rename from spring-data-dynamodb/src/main/resources/logback.xml rename to persistence-modules/spring-data-dynamodb/src/main/resources/logback.xml diff --git a/spring-data-dynamodb/src/main/resources/templates/index.html b/persistence-modules/spring-data-dynamodb/src/main/resources/templates/index.html similarity index 100% rename from spring-data-dynamodb/src/main/resources/templates/index.html rename to persistence-modules/spring-data-dynamodb/src/main/resources/templates/index.html diff --git a/spring-data-dynamodb/src/test/java/com/baeldung/spring/data/dynamodb/repository/ProductInfoRepositoryIntegrationTest.java b/persistence-modules/spring-data-dynamodb/src/test/java/com/baeldung/spring/data/dynamodb/repository/ProductInfoRepositoryIntegrationTest.java similarity index 100% rename from spring-data-dynamodb/src/test/java/com/baeldung/spring/data/dynamodb/repository/ProductInfoRepositoryIntegrationTest.java rename to persistence-modules/spring-data-dynamodb/src/test/java/com/baeldung/spring/data/dynamodb/repository/ProductInfoRepositoryIntegrationTest.java diff --git a/spring-data-dynamodb/src/test/resources/application.properties b/persistence-modules/spring-data-dynamodb/src/test/resources/application.properties similarity index 100% rename from spring-data-dynamodb/src/test/resources/application.properties rename to persistence-modules/spring-data-dynamodb/src/test/resources/application.properties diff --git a/spring-data-dynamodb/src/test/resources/exception-hibernate.properties b/persistence-modules/spring-data-dynamodb/src/test/resources/exception-hibernate.properties similarity index 100% rename from spring-data-dynamodb/src/test/resources/exception-hibernate.properties rename to persistence-modules/spring-data-dynamodb/src/test/resources/exception-hibernate.properties diff --git a/spring-data-dynamodb/src/test/resources/exception.properties b/persistence-modules/spring-data-dynamodb/src/test/resources/exception.properties similarity index 100% rename from spring-data-dynamodb/src/test/resources/exception.properties rename to persistence-modules/spring-data-dynamodb/src/test/resources/exception.properties diff --git a/spring-data-gemfire/README.md b/persistence-modules/spring-data-gemfire/README.md similarity index 100% rename from spring-data-gemfire/README.md rename to persistence-modules/spring-data-gemfire/README.md diff --git a/spring-data-gemfire/pom.xml b/persistence-modules/spring-data-gemfire/pom.xml similarity index 97% rename from spring-data-gemfire/pom.xml rename to persistence-modules/spring-data-gemfire/pom.xml index ae7612d719..9108865b4c 100644 --- a/spring-data-gemfire/pom.xml +++ b/persistence-modules/spring-data-gemfire/pom.xml @@ -12,6 +12,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionExecution.java b/persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionExecution.java similarity index 100% rename from spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionExecution.java rename to persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionExecution.java diff --git a/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionImpl.java b/persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionImpl.java similarity index 100% rename from spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionImpl.java rename to persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/FunctionImpl.java diff --git a/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/GemfireConfiguration.java b/persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/GemfireConfiguration.java similarity index 100% rename from spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/GemfireConfiguration.java rename to persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/function/GemfireConfiguration.java diff --git a/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/model/Employee.java b/persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/model/Employee.java similarity index 100% rename from spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/model/Employee.java rename to persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/model/Employee.java diff --git a/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepository.java b/persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepository.java similarity index 100% rename from spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepository.java rename to persistence-modules/spring-data-gemfire/src/main/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepository.java diff --git a/spring-data-gemfire/src/main/resources/application-context.xml b/persistence-modules/spring-data-gemfire/src/main/resources/application-context.xml similarity index 100% rename from spring-data-gemfire/src/main/resources/application-context.xml rename to persistence-modules/spring-data-gemfire/src/main/resources/application-context.xml diff --git a/spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryIntegrationTest.java b/persistence-modules/spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryIntegrationTest.java similarity index 100% rename from spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryIntegrationTest.java rename to persistence-modules/spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryIntegrationTest.java diff --git a/spring-data-neo4j/README.md b/persistence-modules/spring-data-neo4j/README.md similarity index 100% rename from spring-data-neo4j/README.md rename to persistence-modules/spring-data-neo4j/README.md diff --git a/spring-data-neo4j/pom.xml b/persistence-modules/spring-data-neo4j/pom.xml similarity index 99% rename from spring-data-neo4j/pom.xml rename to persistence-modules/spring-data-neo4j/pom.xml index e01e7d7294..0055850ec3 100644 --- a/spring-data-neo4j/pom.xml +++ b/persistence-modules/spring-data-neo4j/pom.xml @@ -10,6 +10,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java similarity index 100% rename from spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java diff --git a/spring-data-neo4j/src/main/resources/logback.xml b/persistence-modules/spring-data-neo4j/src/main/resources/logback.xml similarity index 100% rename from spring-data-neo4j/src/main/resources/logback.xml rename to persistence-modules/spring-data-neo4j/src/main/resources/logback.xml diff --git a/spring-data-neo4j/src/main/resources/test.png b/persistence-modules/spring-data-neo4j/src/main/resources/test.png similarity index 100% rename from spring-data-neo4j/src/main/resources/test.png rename to persistence-modules/spring-data-neo4j/src/main/resources/test.png diff --git a/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerLiveTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerLiveTest.java similarity index 100% rename from spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerLiveTest.java rename to persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4JServerLiveTest.java diff --git a/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java similarity index 100% rename from spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java rename to persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java diff --git a/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java similarity index 100% rename from spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java rename to persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java diff --git a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java similarity index 100% rename from spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java rename to persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java diff --git a/spring-data-neo4j/src/test/resources/logback.xml b/persistence-modules/spring-data-neo4j/src/test/resources/logback.xml similarity index 100% rename from spring-data-neo4j/src/test/resources/logback.xml rename to persistence-modules/spring-data-neo4j/src/test/resources/logback.xml diff --git a/spring-data-redis/README.md b/persistence-modules/spring-data-redis/README.md similarity index 100% rename from spring-data-redis/README.md rename to persistence-modules/spring-data-redis/README.md diff --git a/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml similarity index 98% rename from spring-data-redis/pom.xml rename to persistence-modules/spring-data-redis/pom.xml index d2835595da..b184d7e369 100644 --- a/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java similarity index 100% rename from spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java rename to persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java diff --git a/spring-data-redis/src/main/resources/logback.xml b/persistence-modules/spring-data-redis/src/main/resources/logback.xml similarity index 100% rename from spring-data-redis/src/main/resources/logback.xml rename to persistence-modules/spring-data-redis/src/main/resources/logback.xml diff --git a/spring-data-redis/src/main/resources/test.png b/persistence-modules/spring-data-redis/src/main/resources/test.png similarity index 100% rename from spring-data-redis/src/main/resources/test.png rename to persistence-modules/spring-data-redis/src/main/resources/test.png diff --git a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java similarity index 100% rename from spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java rename to persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java diff --git a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java similarity index 100% rename from spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java rename to persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java diff --git a/spring-data-solr/README.md b/persistence-modules/spring-data-solr/README.md similarity index 100% rename from spring-data-solr/README.md rename to persistence-modules/spring-data-solr/README.md diff --git a/spring-data-solr/pom.xml b/persistence-modules/spring-data-solr/pom.xml similarity index 97% rename from spring-data-solr/pom.xml rename to persistence-modules/spring-data-solr/pom.xml index 48ddaa7085..0759c1dbc0 100644 --- a/spring-data-solr/pom.xml +++ b/persistence-modules/spring-data-solr/pom.xml @@ -12,6 +12,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/config/SolrConfig.java b/persistence-modules/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/config/SolrConfig.java similarity index 100% rename from spring-data-solr/src/main/java/com/baeldung/spring/data/solr/config/SolrConfig.java rename to persistence-modules/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/config/SolrConfig.java diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java b/persistence-modules/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java similarity index 100% rename from spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java rename to persistence-modules/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java b/persistence-modules/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java similarity index 100% rename from spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java rename to persistence-modules/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java diff --git a/spring-data-solr/src/main/resources/solr-named-queries.properties b/persistence-modules/spring-data-solr/src/main/resources/solr-named-queries.properties similarity index 100% rename from spring-data-solr/src/main/resources/solr-named-queries.properties rename to persistence-modules/spring-data-solr/src/main/resources/solr-named-queries.properties diff --git a/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java similarity index 100% rename from spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java rename to persistence-modules/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java diff --git a/spring-hibernate3/.gitignore b/persistence-modules/spring-hibernate-3/.gitignore similarity index 100% rename from spring-hibernate3/.gitignore rename to persistence-modules/spring-hibernate-3/.gitignore diff --git a/spring-hibernate3/README.md b/persistence-modules/spring-hibernate-3/README.md similarity index 100% rename from spring-hibernate3/README.md rename to persistence-modules/spring-hibernate-3/README.md diff --git a/spring-hibernate3/pom.xml b/persistence-modules/spring-hibernate-3/pom.xml similarity index 95% rename from spring-hibernate3/pom.xml rename to persistence-modules/spring-hibernate-3/pom.xml index d7607cac0a..8eee819572 100644 --- a/spring-hibernate3/pom.xml +++ b/persistence-modules/spring-hibernate-3/pom.xml @@ -2,15 +2,16 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - spring-hibernate3 + spring-hibernate-3 0.1-SNAPSHOT - spring-hibernate3 + spring-hibernate-3 com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ @@ -87,7 +88,7 @@ - spring-hibernate3 + spring-hibernate-3 src/main/resources @@ -141,7 +142,7 @@ 3.6.10.Final 5.1.40 - 7.0.73 + 8.5.8 1.4.193 @@ -162,4 +163,4 @@ - \ No newline at end of file + diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/AbstractHibernateDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/AbstractHibernateDao.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/dao/AbstractHibernateDao.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/AbstractHibernateDao.java diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/EventDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/EventDao.java new file mode 100644 index 0000000000..74da643f35 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/EventDao.java @@ -0,0 +1,18 @@ +package org.baeldung.persistence.dao; + + +import org.baeldung.persistence.model.Event; +import org.springframework.stereotype.Repository; + +@Repository +public class EventDao extends AbstractHibernateDao implements IEventDao { + + public EventDao() { + super(); + + setClazz(Event.class); + } + + // API + +} diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/FooDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/FooDao.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/dao/FooDao.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/FooDao.java diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IEventDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IEventDao.java new file mode 100644 index 0000000000..f7be705905 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IEventDao.java @@ -0,0 +1,9 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.Event; + + + +public interface IEventDao extends IOperations { + // +} diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/IFooDao.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IFooDao.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/dao/IFooDao.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IFooDao.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/IOperations.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IOperations.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/dao/IOperations.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/dao/IOperations.java diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Event.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Event.java new file mode 100644 index 0000000000..1d659ed75c --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Event.java @@ -0,0 +1,45 @@ +package org.baeldung.persistence.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "EVENTS") +public class Event implements Serializable { + + @Id + @GeneratedValue + private Long id; + + private String description; + + public Event() { + } + + + public Event(String description) { + this.description = description; + } + + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + } \ No newline at end of file diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/model/Foo.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Foo.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/model/Foo.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/model/Foo.java diff --git a/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/EventService.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/EventService.java new file mode 100644 index 0000000000..6171751cc5 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/EventService.java @@ -0,0 +1,27 @@ +package org.baeldung.persistence.service; + + +import org.baeldung.persistence.dao.IEventDao; +import org.baeldung.persistence.model.Event; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class EventService { + + @Autowired + private IEventDao dao; + + public EventService() { + super(); + } + + // API + + public void create(final Event entity) { + dao.create(entity); + } + +} diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/service/FooService.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/FooService.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/persistence/service/FooService.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/persistence/service/FooService.java diff --git a/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfig.java similarity index 98% rename from spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfig.java index fea76dfc70..03b9bfac33 100644 --- a/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfig.java @@ -4,7 +4,7 @@ import java.util.Properties; import javax.sql.DataSource; -import org.apache.tomcat.dbcp.dbcp.BasicDataSource; +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -75,4 +75,4 @@ public class PersistenceConfig { return hibernateProperties; } -} \ No newline at end of file +} diff --git a/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceXmlConfig.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceXmlConfig.java similarity index 100% rename from spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceXmlConfig.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceXmlConfig.java diff --git a/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemo.cfg.xml b/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemo.cfg.xml new file mode 100644 index 0000000000..8a710cc559 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemo.cfg.xml @@ -0,0 +1,9 @@ + + + + + + + diff --git a/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemoPersistenceConfig.xml b/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemoPersistenceConfig.xml new file mode 100644 index 0000000000..09314c67b1 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemoPersistenceConfig.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + classpath:exceptionDemo.cfg.xml + + + + ${hibernate.dialect} + true + create + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-hibernate3/src/main/resources/logback.xml b/persistence-modules/spring-hibernate-3/src/main/resources/logback.xml similarity index 100% rename from spring-hibernate3/src/main/resources/logback.xml rename to persistence-modules/spring-hibernate-3/src/main/resources/logback.xml diff --git a/spring-hibernate3/src/main/resources/persistence-h2.properties b/persistence-modules/spring-hibernate-3/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-hibernate3/src/main/resources/persistence-h2.properties rename to persistence-modules/spring-hibernate-3/src/main/resources/persistence-h2.properties diff --git a/spring-hibernate3/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-hibernate-3/src/main/resources/persistence-mysql.properties similarity index 100% rename from spring-hibernate3/src/main/resources/persistence-mysql.properties rename to persistence-modules/spring-hibernate-3/src/main/resources/persistence-mysql.properties diff --git a/spring-hibernate3/src/main/resources/persistenceConfig.xml b/persistence-modules/spring-hibernate-3/src/main/resources/persistenceConfig.xml similarity index 94% rename from spring-hibernate3/src/main/resources/persistenceConfig.xml rename to persistence-modules/spring-hibernate-3/src/main/resources/persistenceConfig.xml index 347e85ee51..e7ef9ad765 100644 --- a/spring-hibernate3/src/main/resources/persistenceConfig.xml +++ b/persistence-modules/spring-hibernate-3/src/main/resources/persistenceConfig.xml @@ -18,7 +18,7 @@ - + @@ -31,4 +31,4 @@ - \ No newline at end of file + diff --git a/spring-hibernate3/src/main/webapp/WEB-INF/view/sample.jsp b/persistence-modules/spring-hibernate-3/src/main/webapp/WEB-INF/view/sample.jsp similarity index 100% rename from spring-hibernate3/src/main/webapp/WEB-INF/view/sample.jsp rename to persistence-modules/spring-hibernate-3/src/main/webapp/WEB-INF/view/sample.jsp diff --git a/spring-hibernate3/src/main/webapp/WEB-INF/web.xml b/persistence-modules/spring-hibernate-3/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-hibernate3/src/main/webapp/WEB-INF/web.xml rename to persistence-modules/spring-hibernate-3/src/main/webapp/WEB-INF/web.xml diff --git a/spring-hibernate3/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java similarity index 100% rename from spring-hibernate3/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java rename to persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java new file mode 100644 index 0000000000..2b29dcb7a9 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest.java @@ -0,0 +1,42 @@ +package org.baeldung.persistence.service; + +import org.baeldung.persistence.model.Event; +import org.baeldung.spring.PersistenceXmlConfig; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.orm.hibernate3.HibernateSystemException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceXmlConfig.class }, loader = AnnotationConfigContextLoader.class) +public class NoHibernateSessBoundUsingAnnoSessionBeanMainIntegrationTest { + + @Autowired + EventService service; + + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + service.create(new Event("from Annotation Session Bean Factory")); + } + + @Test + @Ignore + public final void whenNoTransBoundToSession_thenException() { + expectedEx.expect(HibernateSystemException.class); + expectedEx.expectMessage("No Hibernate Session bound to thread, " + + "and configuration does not allow creation of " + + "non-transactional one here"); + service.create(new Event("from Annotation Session Bean Factory")); + } + +} diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java new file mode 100644 index 0000000000..1bc6c07b18 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest.java @@ -0,0 +1,39 @@ +package org.baeldung.persistence.service; + +import org.baeldung.persistence.model.Event; +import org.hibernate.HibernateException; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.orm.hibernate3.HibernateSystemException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:exceptionDemoPersistenceConfig.xml" }) +public class NoHibernateSessBoundUsingLocalSessionBeanMainIntegrationTest { + + @Autowired + EventService service; + + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + service.create(new Event("from local session bean factory")); + } + + @Test + @Ignore + public final void whenNoTransBoundToSession_thenException() { + expectedEx.expect(HibernateException.class); + expectedEx.expectMessage("No Hibernate Session bound to thread, " + + "and configuration does not allow creation " + + "of non-transactional one here"); + service.create(new Event("from local session bean factory")); + } +} diff --git a/spring-hibernate3/src/test/resources/.gitignore b/persistence-modules/spring-hibernate-3/src/test/resources/.gitignore similarity index 100% rename from spring-hibernate3/src/test/resources/.gitignore rename to persistence-modules/spring-hibernate-3/src/test/resources/.gitignore diff --git a/spring-hibernate5/.gitignore b/persistence-modules/spring-hibernate-5/.gitignore similarity index 100% rename from spring-hibernate5/.gitignore rename to persistence-modules/spring-hibernate-5/.gitignore diff --git a/spring-hibernate5/README.md b/persistence-modules/spring-hibernate-5/README.md similarity index 100% rename from spring-hibernate5/README.md rename to persistence-modules/spring-hibernate-5/README.md diff --git a/spring-hibernate5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml similarity index 97% rename from spring-hibernate5/pom.xml rename to persistence-modules/spring-hibernate-5/pom.xml index dac43c4dd3..f1f3d10347 100644 --- a/spring-hibernate5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -2,15 +2,16 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - spring-hibernate5 + spring-hibernate-5 0.1-SNAPSHOT - spring-hibernate5 + spring-hibernate-5 com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ @@ -136,7 +137,7 @@ - spring-hibernate5 + spring-hibernate-5 src/main/resources diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/dao/IFooDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/IFooDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/dao/IFooDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/IFooDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/dao/common/IOperations.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/common/IOperations.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/dao/common/IOperations.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/common/IOperations.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/dao/impl/FooHibernateDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/impl/FooHibernateDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/dao/impl/FooHibernateDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/dao/impl/FooHibernateDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/model/Foo.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/model/Foo.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/persistence/model/Foo.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/model/Foo.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/spring/PersistenceConfig.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java diff --git a/spring-hibernate5/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java similarity index 100% rename from spring-hibernate5/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceXmlConfig.java diff --git a/spring-hibernate5/src/main/resources/hibernate5Config.xml b/persistence-modules/spring-hibernate-5/src/main/resources/hibernate5Config.xml similarity index 100% rename from spring-hibernate5/src/main/resources/hibernate5Config.xml rename to persistence-modules/spring-hibernate-5/src/main/resources/hibernate5Config.xml diff --git a/spring-hibernate5/src/main/resources/immutable.cfg.xml b/persistence-modules/spring-hibernate-5/src/main/resources/immutable.cfg.xml similarity index 100% rename from spring-hibernate5/src/main/resources/immutable.cfg.xml rename to persistence-modules/spring-hibernate-5/src/main/resources/immutable.cfg.xml diff --git a/spring-hibernate5/src/main/resources/logback.xml b/persistence-modules/spring-hibernate-5/src/main/resources/logback.xml similarity index 100% rename from spring-hibernate5/src/main/resources/logback.xml rename to persistence-modules/spring-hibernate-5/src/main/resources/logback.xml diff --git a/spring-hibernate5/src/main/resources/manytomany.cfg.xml b/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml similarity index 100% rename from spring-hibernate5/src/main/resources/manytomany.cfg.xml rename to persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml diff --git a/spring-hibernate5/src/main/resources/persistence-h2.properties b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-hibernate5/src/main/resources/persistence-h2.properties rename to persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties diff --git a/spring-hibernate5/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-mysql.properties similarity index 100% rename from spring-hibernate5/src/main/resources/persistence-mysql.properties rename to persistence-modules/spring-hibernate-5/src/main/resources/persistence-mysql.properties diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java similarity index 100% rename from spring-hibernate5/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java similarity index 100% rename from spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java similarity index 100% rename from spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java diff --git a/spring-hibernate5/src/test/java/com/baeldung/persistence/dao/common/HibernateDaoIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/dao/common/HibernateDaoIntegrationTest.java similarity index 100% rename from spring-hibernate5/src/test/java/com/baeldung/persistence/dao/common/HibernateDaoIntegrationTest.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/dao/common/HibernateDaoIntegrationTest.java diff --git a/spring-hibernate5/src/test/resources/.gitignore b/persistence-modules/spring-hibernate-5/src/test/resources/.gitignore similarity index 100% rename from spring-hibernate5/src/test/resources/.gitignore rename to persistence-modules/spring-hibernate-5/src/test/resources/.gitignore diff --git a/pom.xml b/pom.xml index 3d28707b5f..9aa45b1d5d 100644 --- a/pom.xml +++ b/pom.xml @@ -49,8 +49,8 @@ core-java-8 core-java-concurrency couchbase - cas-server - cas-secured-app + cas/cas-server + cas/cas-secured-app deltaspike dozer @@ -85,7 +85,7 @@ immutables jackson - + vavr javax-servlets javaxval @@ -124,11 +124,11 @@ pdf protobuffer - querydsl + persistence-modules/querydsl reactor-core - redis + persistence-modules/redis rest-assured rest-testing resteasy @@ -136,7 +136,7 @@ spring-swagger-codegen selenium-junit-testng - solr + persistence-modules/solr spark-java spring-5-mvc @@ -149,28 +149,30 @@ spring-batch spring-bom spring-boot + spring-boot-bootstrap spring-cloud-data-flow spring-cloud spring-core spring-cucumber spring-aop - spring-data-cassandra + persistence-modules/spring-data-cassandra spring-data-couchbase-2 - spring-data-dynamodb + persistence-modules/spring-data-dynamodb spring-data-elasticsearch spring-data-mongodb - spring-data-neo4j - spring-data-redis + persistence-modules/spring-data-neo4j + persistence-modules/spring-data-redis spring-data-rest - spring-data-solr + persistence-modules/spring-data-solr spring-dispatcher-servlet spring-exceptions spring-freemarker - spring-hibernate3 + persistence-modules/spring-hibernate-3 spring-hibernate4 - spring-hibernate5 + persistence-modules/spring-hibernate-5 spring-integration spring-jersey + spring-jmeter-jenkins spring-jms spring-jooq spring-jpa @@ -192,6 +194,8 @@ spring-quartz spring-rest-angular spring-rest-docs + spring-rest-full + spring-rest-query-language spring-rest spring-rest-simple spring-security-cache-control @@ -213,7 +217,6 @@ spring-security-mvc-socket spring-security-rest-basic-auth spring-security-rest-custom - spring-security-rest-full spring-security-rest spring-security-sso spring-security-x509 @@ -242,17 +245,18 @@ rabbitmq vertx - spring-data-gemfire + persistence-modules/spring-data-gemfire mybatis spring-drools drools - liquibase + persistence-modules/liquibase spring-boot-property-exp mockserver undertow vertx-and-rxjava saas deeplearning4j + spring-boot-admin diff --git a/rest-testing/pom.xml b/rest-testing/pom.xml index b99dfac571..74ea5760c4 100644 --- a/rest-testing/pom.xml +++ b/rest-testing/pom.xml @@ -88,6 +88,19 @@ ${jbehave.version} test + + + com.intuit.karate + karate-apache + ${karate.version} + + + + com.intuit.karate + karate-junit4 + ${karate.version} + test + @@ -150,6 +163,7 @@ 2.9.0 1.2.5 2.4.1 + 0.6.1 4.4.5 4.5.2 diff --git a/rest-testing/src/main/resources/Feature/cucumber.feature b/rest-testing/src/main/resources/karate/cucumber.feature similarity index 100% rename from rest-testing/src/main/resources/Feature/cucumber.feature rename to rest-testing/src/main/resources/karate/cucumber.feature diff --git a/rest-testing/src/test/java/com/baeldung/rest/karate/KarateUnitTest.java b/rest-testing/src/test/java/com/baeldung/rest/karate/KarateUnitTest.java new file mode 100644 index 0000000000..f942721504 --- /dev/null +++ b/rest-testing/src/test/java/com/baeldung/rest/karate/KarateUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.rest.karate; + +import com.github.tomakehurst.wiremock.WireMockServer; +import com.intuit.karate.junit4.Karate; +import cucumber.api.CucumberOptions; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.runner.RunWith; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; + +@RunWith(Karate.class) +@CucumberOptions(features = "classpath:karate") +public class KarateUnitTest { + + private static final WireMockServer wireMockServer = new WireMockServer(); + + @BeforeClass + public static void setUp() throws Exception { + wireMockServer.start(); + + configureFor("localhost", 8080); + stubFor(get(urlEqualTo("/user/get")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("{ \"id\": \"1234\", name: \"John Smith\" }"))); + stubFor(post(urlEqualTo("/user/create")) + .withHeader("content-type", equalTo("application/json")) + .withRequestBody(containing("id")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("{ \"id\": \"1234\", name: \"John Smith\" }"))); + + } + + @AfterClass + public static void tearDown() throws Exception { + wireMockServer.stop(); + } + +} diff --git a/rest-testing/src/test/resources/karate/user.feature b/rest-testing/src/test/resources/karate/user.feature new file mode 100644 index 0000000000..d9f0f12a9c --- /dev/null +++ b/rest-testing/src/test/resources/karate/user.feature @@ -0,0 +1,42 @@ +Feature: Testing a REST API with Karate + +Scenario: Testing valid GET endpoint + Given url 'http://localhost:8080/user/get' + When method GET + Then status 200 + +Scenario: Testing an invalid GET endpoint - 404 + Given url 'http://localhost:8080/user/wrong' + When method GET + Then status 404 + +Scenario: Testing the exact response of a GET endpoint + Given url 'http://localhost:8080/user/get' + When method GET + Then status 200 + And match $ == {id:"1234",name:"John Smith"} + +Scenario: Testing the exact response field value of a GET endpoint + Given url 'http://localhost:8080/user/get' + When method GET + Then status 200 + And match $.id == "1234" + +Scenario: Testing that GET response contains specific field + Given url 'http://localhost:8080/user/get' + When method GET + Then status 200 + And match $ contains {id:"1234"} + +Scenario: Test GET response using markers + Given url 'http://localhost:8080/user/get' + When method GET + Then status 200 + And match $ == {id:"#notnull",name:"John Smith"} + +Scenario: Testing a POST endpoint with request body + Given url 'http://localhost:8080/user/create' + And request { id: '1234' , name: 'John Smith'} + When method POST + Then status 200 + And match $ contains {id:"#notnull"} diff --git a/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java b/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java index 7bab288bab..a218c6b7cf 100644 --- a/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java +++ b/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java @@ -43,7 +43,8 @@ public class WebClientController { WebClient.RequestHeadersSpec requestSpec2 = uri2.body(BodyInserters.fromObject("data")); // inserters - BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters.fromPublisher(Subscriber::onComplete, String.class); + BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters + .fromPublisher(Subscriber::onComplete, String.class); LinkedMultiValueMap map = new LinkedMultiValueMap<>(); map.add("key1", "value1"); diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index c5289b20a6..f6f992b7c0 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -19,9 +19,11 @@ + com.example.activitiwithspring.ActivitiWithSpringApplication UTF-8 UTF-8 1.8 + 6.0.0 @@ -30,9 +32,14 @@ activiti-spring-boot-starter-basic 6.0.0 + + org.activiti + activiti-spring-boot-starter-security + ${activiti.version} + org.springframework.boot - spring-boot-starter-web + spring-boot-starter-thymeleaf diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security.rar b/spring-activiti/src/main/java/com/baeldung/activiti/security.rar new file mode 100644 index 0000000000..38c4946168 Binary files /dev/null and b/spring-activiti/src/main/java/com/baeldung/activiti/security.rar differ diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/MvcConfig.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/MvcConfig.java new file mode 100644 index 0000000000..f9394742cd --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/MvcConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.activiti.security.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/login") + .setViewName("login"); + registry.addViewController("/homepage") + .setViewName("homepage"); + } + +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/ProcessController.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/ProcessController.java new file mode 100644 index 0000000000..671b246328 --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/ProcessController.java @@ -0,0 +1,54 @@ +package com.baeldung.activiti.security.config; + +import java.util.List; + +import org.activiti.engine.IdentityService; +import org.activiti.engine.RuntimeService; +import org.activiti.engine.TaskService; +import org.activiti.engine.runtime.ProcessInstance; +import org.activiti.engine.task.Task; +import org.activiti.spring.SpringProcessEngineConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ProcessController { + + @Autowired + private RuntimeService runtimeService; + + @Autowired + private TaskService taskService; + + @Autowired + private IdentityService identityService; + + @Autowired + SpringProcessEngineConfiguration config; + + @GetMapping("/protected-process") + public String startProcess() { + + String userId = SecurityContextHolder.getContext() + .getAuthentication() + .getName(); + + identityService.setAuthenticatedUserId(userId); + + ProcessInstance pi = runtimeService.startProcessInstanceByKey("protected-process"); + + List usertasks = taskService.createTaskQuery() + .processInstanceId(pi.getId()) + .list(); + + taskService.complete(usertasks.iterator() + .next() + .getId()); + + return "Process started. Number of currently running process instances = " + runtimeService.createProcessInstanceQuery() + .count(); + } + +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityGroupManager.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityGroupManager.java new file mode 100644 index 0000000000..00fc674e22 --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityGroupManager.java @@ -0,0 +1,86 @@ +package com.baeldung.activiti.security.config; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.activiti.engine.identity.Group; +import org.activiti.engine.identity.GroupQuery; +import org.activiti.engine.impl.GroupQueryImpl; +import org.activiti.engine.impl.Page; +import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.activiti.engine.impl.persistence.entity.GroupEntityImpl; +import org.activiti.engine.impl.persistence.entity.GroupEntityManagerImpl; +import org.activiti.engine.impl.persistence.entity.data.GroupDataManager; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.provisioning.JdbcUserDetailsManager; + +public class SpringSecurityGroupManager extends GroupEntityManagerImpl { + + private JdbcUserDetailsManager userManager; + + public SpringSecurityGroupManager(ProcessEngineConfigurationImpl processEngineConfiguration, GroupDataManager groupDataManager) { + super(processEngineConfiguration, groupDataManager); + } + + @Override + public List findGroupByQueryCriteria(GroupQueryImpl query, Page page) { + + if (query.getUserId() != null) { + return findGroupsByUser(query.getUserId()); + } + return null; + } + + @Override + public long findGroupCountByQueryCriteria(GroupQueryImpl query) { + return findGroupByQueryCriteria(query, null).size(); + } + + @Override + public List findGroupsByUser(String userId) { + UserDetails userDetails = userManager.loadUserByUsername(userId); + System.out.println("group manager"); + if (userDetails != null) { + List groups = userDetails.getAuthorities() + .stream() + .map(a -> a.getAuthority()) + .map(a -> { + Group g = new GroupEntityImpl(); + g.setId(a); + return g; + }) + .collect(Collectors.toList()); + return groups; + } + return null; + } + + public void setUserManager(JdbcUserDetailsManager userManager) { + this.userManager = userManager; + } + + public Group createNewGroup(String groupId) { + throw new UnsupportedOperationException("This operation is not supported!"); + + } + + @Override + public void delete(String groupId) { + throw new UnsupportedOperationException("This operation is not supported!"); + + } + + public GroupQuery createNewGroupQuery() { + throw new UnsupportedOperationException("This operation is not supported!"); + } + + public List findGroupsByNativeQuery(Map parameterMap, int firstResult, int maxResults) { + throw new UnsupportedOperationException("This operation is not supported!"); + } + + public long findGroupCountByNativeQuery(Map parameterMap) { + throw new UnsupportedOperationException("This operation is not supported!"); + } + +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityUserManager.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityUserManager.java new file mode 100644 index 0000000000..ce9863eb6c --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityUserManager.java @@ -0,0 +1,144 @@ +package com.baeldung.activiti.security.config; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.activiti.engine.identity.Group; +import org.activiti.engine.identity.User; +import org.activiti.engine.identity.UserQuery; +import org.activiti.engine.impl.Page; +import org.activiti.engine.impl.UserQueryImpl; +import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.activiti.engine.impl.persistence.entity.GroupEntityImpl; +import org.activiti.engine.impl.persistence.entity.UserEntity; +import org.activiti.engine.impl.persistence.entity.UserEntityImpl; +import org.activiti.engine.impl.persistence.entity.UserEntityManagerImpl; +import org.activiti.engine.impl.persistence.entity.data.UserDataManager; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.provisioning.JdbcUserDetailsManager; + +public class SpringSecurityUserManager extends UserEntityManagerImpl { + + private JdbcUserDetailsManager userManager; + + public SpringSecurityUserManager(ProcessEngineConfigurationImpl processEngineConfiguration, UserDataManager userDataManager, JdbcUserDetailsManager userManager) { + super(processEngineConfiguration, userDataManager); + this.userManager = userManager; + } + + @Override + public UserEntity findById(String userId) { + UserDetails userDetails = userManager.loadUserByUsername(userId); + if (userDetails != null) { + UserEntityImpl user = new UserEntityImpl(); + user.setId(userId); + return user; + } + return null; + + } + + @Override + public List findUserByQueryCriteria(UserQueryImpl query, Page page) { + List users = null; + if (query.getGroupId() != null) { + users = userManager.findUsersInGroup(query.getGroupId()) + .stream() + .map(username -> { + User user = new UserEntityImpl(); + user.setId(username); + return user; + }) + .collect(Collectors.toList()); + if (page != null) { + return users.subList(page.getFirstResult(), page.getFirstResult() + page.getMaxResults()); + + } + return users; + } + + if (query.getId() != null) { + UserDetails userDetails = userManager.loadUserByUsername(query.getId()); + if (userDetails != null) { + UserEntityImpl user = new UserEntityImpl(); + user.setId(query.getId()); + return Collections.singletonList(user); + } + } + return null; + } + + @Override + public Boolean checkPassword(String userId, String password) { + return true; + } + + public void setUserManager(JdbcUserDetailsManager userManager) { + this.userManager = userManager; + } + + public User createNewUser(String userId) { + throw new UnsupportedOperationException("This operation is not supported!"); + } + + public void updateUser(User updatedUser) { + throw new UnsupportedOperationException("This operation is not supported!"); + + } + + public void delete(UserEntity userEntity) { + throw new UnsupportedOperationException("This operation is not supported!"); + + } + + @Override + public void deletePicture(User user) { + UserEntity userEntity = (UserEntity) user; + if (userEntity.getPictureByteArrayRef() != null) { + userEntity.getPictureByteArrayRef() + .delete(); + } + } + + public void delete(String userId) { + throw new UnsupportedOperationException("This operation is not supported!"); + + } + + public long findUserCountByQueryCriteria(UserQueryImpl query) { + return findUserByQueryCriteria(query, null).size(); + } + + public List findGroupsByUser(String userId) { + UserDetails userDetails = userManager.loadUserByUsername(userId); + if (userDetails != null) { + List groups = userDetails.getAuthorities() + .stream() + .map(a -> a.getAuthority()) + .map(a -> { + Group g = new GroupEntityImpl(); + g.setId(a); + return g; + }) + .collect(Collectors.toList()); + return groups; + } + return null; + } + + public UserQuery createNewUserQuery() { + throw new UnsupportedOperationException("This operation is not supported!"); + } + + public List findUsersByNativeQuery(Map parameterMap, int firstResult, int maxResults) { + throw new UnsupportedOperationException("This operation is not supported!"); + } + + public long findUserCountByNativeQuery(Map parameterMap) { + throw new UnsupportedOperationException("This operation is not supported!"); + + } + +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SecurityConfig.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SecurityConfig.java new file mode 100644 index 0000000000..f471600553 --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SecurityConfig.java @@ -0,0 +1,47 @@ +package com.baeldung.activiti.security.withactiviti; + +import org.activiti.engine.IdentityService; +import org.activiti.spring.security.IdentityServiceUserDetailsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/protected-process*") + .authenticated() + .anyRequest() + .permitAll() + .and() + .formLogin() + .loginPage("/login") + .defaultSuccessUrl("/homepage") + .failureUrl("/login?error=true") + .and() + .csrf() + .disable() + .logout() + .logoutSuccessUrl("/login"); + } + + @Autowired + private IdentityService identityService; + + @Bean + public IdentityServiceUserDetailsService userDetailsService() { + return new IdentityServiceUserDetailsService(identityService); + } + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService()); + } + +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SpringSecurityActivitiApplication.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SpringSecurityActivitiApplication.java new file mode 100644 index 0000000000..2270a4d684 --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SpringSecurityActivitiApplication.java @@ -0,0 +1,34 @@ +package com.baeldung.activiti.security.withactiviti; + +import org.activiti.engine.IdentityService; +import org.activiti.engine.identity.Group; +import org.activiti.engine.identity.User; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication(scanBasePackages = { "com.baeldung.activiti.security.config", "com.baeldung.activiti.security.withactiviti" }) +public class SpringSecurityActivitiApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringSecurityActivitiApplication.class, args); + } + + @Bean + InitializingBean usersAndGroupsInitializer(IdentityService identityService) { + return new InitializingBean() { + public void afterPropertiesSet() throws Exception { + User user = identityService.newUser("activiti_user"); + user.setPassword("pass"); + identityService.saveUser(user); + + Group group = identityService.newGroup("user"); + group.setName("ROLE_USER"); + group.setType("USER"); + identityService.saveGroup(group); + identityService.createMembership(user.getId(), group.getId()); + } + }; + } +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/ActivitiSpringSecurityApplication.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/ActivitiSpringSecurityApplication.java new file mode 100644 index 0000000000..5878a5d678 --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/ActivitiSpringSecurityApplication.java @@ -0,0 +1,39 @@ +package com.baeldung.activiti.security.withspring; + +import org.activiti.engine.impl.persistence.entity.data.impl.MybatisGroupDataManager; +import org.activiti.engine.impl.persistence.entity.data.impl.MybatisUserDataManager; +import org.activiti.spring.SpringProcessEngineConfiguration; +import org.activiti.spring.boot.SecurityAutoConfiguration; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.security.provisioning.JdbcUserDetailsManager; + +import com.baeldung.activiti.security.config.SpringSecurityGroupManager; +import com.baeldung.activiti.security.config.SpringSecurityUserManager; + +@SpringBootApplication(exclude = SecurityAutoConfiguration.class, scanBasePackages = { "com.baeldung.activiti.security.config", "com.baeldung.activiti.security.withspring" }) +public class ActivitiSpringSecurityApplication { + + public static void main(String[] args) { + SpringApplication.run(ActivitiSpringSecurityApplication.class, args); + } + + @Autowired + private SpringProcessEngineConfiguration processEngineConfiguration; + + @Autowired + private JdbcUserDetailsManager userManager; + + @Bean + InitializingBean processEngineInitializer() { + return new InitializingBean() { + public void afterPropertiesSet() throws Exception { + processEngineConfiguration.setUserEntityManager(new SpringSecurityUserManager(processEngineConfiguration, new MybatisUserDataManager(processEngineConfiguration), userManager)); + processEngineConfiguration.setGroupEntityManager(new SpringSecurityGroupManager(processEngineConfiguration, new MybatisGroupDataManager(processEngineConfiguration))); + } + }; + } +} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java new file mode 100644 index 0000000000..df1991c3e4 --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java @@ -0,0 +1,50 @@ +package com.baeldung.activiti.security.withspring; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.provisioning.JdbcUserDetailsManager; + +@Configuration +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private DataSource dataSource; + + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/protected-process*") + .authenticated() + .anyRequest() + .permitAll() + .and() + .formLogin() + .loginPage("/login") + .defaultSuccessUrl("/homepage") + .failureUrl("/login?error=true") + .and() + .csrf() + .disable() + .logout() + .logoutSuccessUrl("/login"); + } + + @Bean + public JdbcUserDetailsManager userDetailsManager() { + JdbcUserDetailsManager manager = new JdbcUserDetailsManager(); + manager.setDataSource(dataSource); + return manager; + } + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsManager()); + } + +} diff --git a/spring-activiti/src/main/resources/data.sql b/spring-activiti/src/main/resources/data.sql new file mode 100644 index 0000000000..cb9b72617a --- /dev/null +++ b/spring-activiti/src/main/resources/data.sql @@ -0,0 +1,3 @@ +insert into users(username, password, enabled) values ('spring_user', 'pass', true); + +insert into authorities(username, authority) values ('spring_user','ROLE_USER'); \ No newline at end of file diff --git a/spring-activiti/src/main/resources/processes/protected-process.bpmn20.xml b/spring-activiti/src/main/resources/processes/protected-process.bpmn20.xml new file mode 100644 index 0000000000..b7e04515cd --- /dev/null +++ b/spring-activiti/src/main/resources/processes/protected-process.bpmn20.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + ROLE_USER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-activiti/src/main/resources/schema.sql b/spring-activiti/src/main/resources/schema.sql new file mode 100644 index 0000000000..bf882895fd --- /dev/null +++ b/spring-activiti/src/main/resources/schema.sql @@ -0,0 +1,3 @@ +create table users(username varchar(255), password varchar(255), enabled boolean); + +create table authorities(username varchar(255),authority varchar(255)); \ No newline at end of file diff --git a/spring-activiti/src/main/resources/templates/login.html b/spring-activiti/src/main/resources/templates/login.html new file mode 100644 index 0000000000..53077fd5f3 --- /dev/null +++ b/spring-activiti/src/main/resources/templates/login.html @@ -0,0 +1,21 @@ + + + +

Login

+
+
" + user.getUsername() + "" + user.getEmail() + "
+ + + + + + + + + + + +
User:
Password:
+ + + \ No newline at end of file diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java new file mode 100644 index 0000000000..c2eeb96555 --- /dev/null +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java @@ -0,0 +1,31 @@ +package com.example.activitiwithspring; + +import org.activiti.engine.IdentityService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.activiti.security.withspring.ActivitiSpringSecurityApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ActivitiSpringSecurityApplication.class) +@WebAppConfiguration +public class ActivitiSpringSecurityIntegrationTest { + @Autowired + private IdentityService identityService; + + @Test + public void whenUserExists_thenOk() { + identityService.setUserPicture("spring_user", null); + } + + @Test(expected = UsernameNotFoundException.class) + public void whenUserNonExistent_thenSpringException() { + identityService.setUserPicture("user3", null); + } + +} diff --git a/spring-aop/src/main/java/org/baeldung/performancemonitor/AopConfiguration.java b/spring-aop/src/main/java/org/baeldung/performancemonitor/AopConfiguration.java index a5f36fb716..00026baf07 100644 --- a/spring-aop/src/main/java/org/baeldung/performancemonitor/AopConfiguration.java +++ b/spring-aop/src/main/java/org/baeldung/performancemonitor/AopConfiguration.java @@ -16,10 +16,10 @@ import java.time.Month; @EnableAspectJAutoProxy public class AopConfiguration { - @Pointcut("execution(public String com.baeldung.performancemonitor.PersonService.getFullName(..))") + @Pointcut("execution(public String org.baeldung.performancemonitor.PersonService.getFullName(..))") public void monitor() { } - @Pointcut("execution(public int com.baeldung.performancemonitor.PersonService.getAge(..))") + @Pointcut("execution(public int org.baeldung.performancemonitor.PersonService.getAge(..))") public void myMonitor() { } @Bean @@ -30,7 +30,7 @@ public class AopConfiguration { @Bean public Advisor performanceMonitorAdvisor() { AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); - pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.monitor()"); + pointcut.setExpression("org.baeldung.performancemonitor.AopConfiguration.monitor()"); return new DefaultPointcutAdvisor(pointcut, performanceMonitorInterceptor()); } @@ -52,7 +52,7 @@ public class AopConfiguration { @Bean public Advisor myPerformanceMonitorAdvisor() { AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); - pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.myMonitor()"); + pointcut.setExpression("org.baeldung.performancemonitor.AopConfiguration.myMonitor()"); return new DefaultPointcutAdvisor(pointcut, myPerformanceMonitorInterceptor()); } diff --git a/spring-boot-admin/README.md b/spring-boot-admin/README.md new file mode 100644 index 0000000000..622533a6ad --- /dev/null +++ b/spring-boot-admin/README.md @@ -0,0 +1,17 @@ +## 1. Spring Boot Admin Server + +* mvn clean install +* mvn spring-boot:run +* starts on port 8080 +* login with admin/admin +* to activate mail notifications uncomment the starter mail dependency +and the mail configuration from application.properties +* add some real credentials if you want the app to send emails +* to activate Hipchat notifications proceed same as for email + +## 2. Spring Boot App Client + +* mvn clean install +* mvn spring-boot:run +* starts on port 8081 +* basic auth client/client \ No newline at end of file diff --git a/spring-boot-admin/pom.xml b/spring-boot-admin/pom.xml new file mode 100644 index 0000000000..9c1eeeabff --- /dev/null +++ b/spring-boot-admin/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + spring-boot-admin + 0.0.1-SNAPSHOT + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + UTF-8 + 1.5.8.RELEASE + + + + spring-boot-admin-server + spring-boot-admin-client + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + + + \ No newline at end of file diff --git a/cas-secured-app/.gitignore b/spring-boot-admin/spring-boot-admin-client/.gitignore similarity index 100% rename from cas-secured-app/.gitignore rename to spring-boot-admin/spring-boot-admin-client/.gitignore diff --git a/spring-boot-admin/spring-boot-admin-client/pom.xml b/spring-boot-admin/spring-boot-admin-client/pom.xml new file mode 100644 index 0000000000..d119450e0b --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/pom.xml @@ -0,0 +1,70 @@ + + + 4.0.0 + + spring-boot-admin-client + 0.0.1-SNAPSHOT + jar + + spring-boot-admin-client + Spring Boot Admin Client + + + spring-boot-admin + com.baeldung + 0.0.1-SNAPSHOT + ../../spring-boot-admin + + + + UTF-8 + UTF-8 + 1.8 + 1.5.4 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-security + + + de.codecentric + spring-boot-admin-starter-client + ${spring-boot-admin-starter-client.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + build-info + + + + + + + + + diff --git a/spring-boot-admin/spring-boot-admin-client/src/main/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplication.java b/spring-boot-admin/spring-boot-admin-client/src/main/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplication.java new file mode 100644 index 0000000000..596da131a6 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/main/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.springbootadminclient; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootAdminClientApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootAdminClientApplication.class, args); + } +} diff --git a/spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties b/spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties new file mode 100644 index 0000000000..58c178ecd9 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties @@ -0,0 +1,16 @@ +#basic auth creddentials +security.user.name=client +security.user.password=client + +#configs to connect to a secured server +spring.boot.admin.url=http://localhost:8080 +spring.boot.admin.username=admin +spring.boot.admin.password=admin + +#configs to give secured server info +spring.boot.admin.client.metadata.user.name=${security.user.name} +spring.boot.admin.client.metadata.user.password=${security.user.password} + +#app config +spring.application.name=spring-boot-admin-client +server.port=8081 \ No newline at end of file diff --git a/spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml b/spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..ff96acae79 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + + %date [%thread] %-5level %logger{25} - %msg%n + + + + + + + \ No newline at end of file diff --git a/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationTests.java b/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationTests.java new file mode 100644 index 0000000000..d70fb1c7cf --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationTests.java @@ -0,0 +1,55 @@ +package com.baeldung.springbootadminclient; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.junit.Assert.assertEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = RANDOM_PORT) +public class SpringBootAdminClientApplicationTests { + + @Autowired Environment environment; + + @Autowired WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + mockMvc = MockMvcBuilders + .webAppContextSetup(wac) + .build(); + } + + @Test + public void whenEnvironmentAvailable_ThenAdminServerPropertiesExist() { + assertEquals(environment.getProperty("spring.boot.admin.url"), "http://localhost:8080"); + assertEquals(environment.getProperty("spring.boot.admin.username"), "admin"); + assertEquals(environment.getProperty("spring.boot.admin.password"), "admin"); + } + + @Test + public void whenHttpBasicAttempted_ThenSuccess() throws Exception { + mockMvc.perform(get("/env").with(httpBasic("client", "client"))); + } + + @Test + public void whenInvalidHttpBasicAttempted_ThenUnauthorized() throws Exception { + mockMvc + .perform(get("/env").with(httpBasic("client", "invalid"))) + .andExpect(status().isUnauthorized()); + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/.gitignore b/spring-boot-admin/spring-boot-admin-server/.gitignore new file mode 100644 index 0000000000..2af7cefb0a --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-admin/spring-boot-admin-server/pom.xml b/spring-boot-admin/spring-boot-admin-server/pom.xml new file mode 100644 index 0000000000..f28b7a3dc9 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/pom.xml @@ -0,0 +1,94 @@ + + + 4.0.0 + + spring-boot-admin-server + 0.0.1-SNAPSHOT + jar + + spring-boot-admin-server + Spring Boot Admin Server + + + spring-boot-admin + com.baeldung + 0.0.1-SNAPSHOT + ../../spring-boot-admin + + + + UTF-8 + UTF-8 + 1.8 + 1.5.4 + 1.5.4 + + + + + org.springframework.boot + spring-boot-starter + + + + + de.codecentric + spring-boot-admin-server + ${spring-boot-admin-server.version} + + + de.codecentric + spring-boot-admin-server-ui + ${spring-boot-admin-server.version} + + + + + de.codecentric + spring-boot-admin-server-ui-login + ${spring-boot-admin-server.version} + + + org.springframework.boot + spring-boot-starter-security + + + com.hazelcast + hazelcast + + + + de.codecentric + spring-boot-admin-starter-client + ${spring-boot-admin-starter-client.version} + + + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/SpringBootAdminServerApplication.java b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/SpringBootAdminServerApplication.java new file mode 100644 index 0000000000..d1fb4e769b --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/SpringBootAdminServerApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.springbootadminserver; + +import de.codecentric.boot.admin.config.EnableAdminServer; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@EnableAdminServer +@SpringBootApplication +public class SpringBootAdminServerApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootAdminServerApplication.class, args); + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/HazelcastConfig.java b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/HazelcastConfig.java new file mode 100644 index 0000000000..b19b7820af --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/HazelcastConfig.java @@ -0,0 +1,24 @@ +package com.baeldung.springbootadminserver.configs; + +import com.hazelcast.config.Config; +import com.hazelcast.config.EvictionPolicy; +import com.hazelcast.config.ListConfig; +import com.hazelcast.config.MapConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class HazelcastConfig { + + @Bean + public Config hazelcast() { + return new Config() + .setProperty("hazelcast.jmx", "true") + .addMapConfig(new MapConfig("spring-boot-admin-application-store") + .setBackupCount(1) + .setEvictionPolicy(EvictionPolicy.NONE)) + .addListConfig(new ListConfig("spring-boot-admin-event-store") + .setBackupCount(1) + .setMaxSize(1000)); + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/NotifierConfiguration.java b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/NotifierConfiguration.java new file mode 100644 index 0000000000..10a31464ab --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/NotifierConfiguration.java @@ -0,0 +1,42 @@ +package com.baeldung.springbootadminserver.configs; + +import de.codecentric.boot.admin.notify.LoggingNotifier; +import de.codecentric.boot.admin.notify.RemindingNotifier; +import de.codecentric.boot.admin.notify.filter.FilteringNotifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; + +import java.util.concurrent.TimeUnit; + +@Configuration +@EnableScheduling +public class NotifierConfiguration { + + // @Autowired private Notifier notifier; + + @Bean + public LoggingNotifier notifier() { + return new LoggingNotifier(); + } + + @Bean + public FilteringNotifier filteringNotifier() { + return new FilteringNotifier(notifier()); + } + + @Bean + @Primary + public RemindingNotifier remindingNotifier() { + RemindingNotifier remindingNotifier = new RemindingNotifier(filteringNotifier()); + remindingNotifier.setReminderPeriod(TimeUnit.MINUTES.toMillis(5)); + return remindingNotifier; + } + + @Scheduled(fixedRate = 60_000L) + public void remind() { + remindingNotifier().sendReminders(); + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/WebSecurityConfig.java b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/WebSecurityConfig.java new file mode 100644 index 0000000000..4a7c8330b7 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/main/java/com/baeldung/springbootadminserver/configs/WebSecurityConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.springbootadminserver.configs; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/login") + .permitAll(); + http + .logout() + .logoutUrl("/logout"); + http + .csrf() + .disable(); + http + .authorizeRequests() + .antMatchers("/login.html", "/**/*.css", "/img/**", "/third-party/**") + .permitAll(); + http + .authorizeRequests() + .antMatchers("/**") + .authenticated(); + http.httpBasic(); + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties b/spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties new file mode 100644 index 0000000000..362f6428e8 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties @@ -0,0 +1,28 @@ +spring.application.name=spring-boot-admin-server + +security.user.name=admin +security.user.password=admin + +#configs to connect to self register the admin server as a client +spring.boot.admin.url=http://localhost:8080 +spring.boot.admin.username=${security.user.name} +spring.boot.admin.password=${security.user.password} + +#configs to give secured server info +spring.boot.admin.client.metadata.user.name=${security.user.name} +spring.boot.admin.client.metadata.user.password=${security.user.password} + +#mail notifications +#spring.mail.host=smtp.gmail.com +#spring.mail.username=test@gmail.com +#spring.mail.password=password +#spring.mail.port=587 +#spring.mail.properties.mail.smtp.auth=true +#spring.mail.properties.mail.smtp.starttls.enable=true + +#spring.boot.admin.notify.mail.to=test@gmail.com + +#hipchat notifications +#spring.boot.admin.notify.hipchat.auth-token= +#spring.boot.admin.notify.hipchat.room-id= +#spring.boot.admin.notify.hipchat.url=https://youcompany.hipchat.com/v2/ \ No newline at end of file diff --git a/spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml b/spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..ff96acae79 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + + %date [%thread] %-5level %logger{25} - %msg%n + + + + + + + \ No newline at end of file diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigTest.java new file mode 100644 index 0000000000..8ca50a6f75 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigTest.java @@ -0,0 +1,24 @@ +package com.baeldung.springbootadminserver; + +import com.baeldung.springbootadminserver.configs.HazelcastConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertNotEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { HazelcastConfig.class }, webEnvironment = NONE) +public class HazelcastConfigTest { + + @Autowired private ApplicationContext applicationContext; + + @Test + public void whenApplicationContextStarts_HazelcastConfigBeanExists() { + assertNotEquals(applicationContext.getBean("hazelcast"), null); + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationTest.java new file mode 100644 index 0000000000..85f6b374a4 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.springbootadminserver; + +import com.baeldung.springbootadminserver.configs.NotifierConfiguration; +import de.codecentric.boot.admin.notify.Notifier; +import de.codecentric.boot.admin.notify.RemindingNotifier; +import de.codecentric.boot.admin.notify.filter.FilteringNotifier; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertNotEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { NotifierConfiguration.class }, webEnvironment = NONE) +public class NotifierConfigurationTest { + + @Autowired private ApplicationContext applicationContext; + + @Test + public void whenApplicationContextStart_ThenNotifierBeanExists() { + Notifier notifier = (Notifier) applicationContext.getBean("notifier"); + assertNotEquals(notifier, null); + } + + @Test + public void whenApplicationContextStart_ThenFilteringNotifierBeanExists() { + FilteringNotifier filteringNotifier = (FilteringNotifier) applicationContext.getBean("filteringNotifier"); + assertNotEquals(filteringNotifier, null); + } + + @Test + public void whenApplicationContextStart_ThenRemindingNotifierBeanExists() { + RemindingNotifier remindingNotifier = (RemindingNotifier) applicationContext.getBean("remindingNotifier"); + assertNotEquals(remindingNotifier, null); + } + +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigTest.java new file mode 100644 index 0000000000..40611f00f6 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigTest.java @@ -0,0 +1,71 @@ +package com.baeldung.springbootadminserver; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class WebSecurityConfigTest { + + @Autowired WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + mockMvc = MockMvcBuilders + .webAppContextSetup(wac) + .build(); + } + + @Test + public void whenApplicationStarts_ThenGetLoginPageWithSuccess() throws Exception { + mockMvc + .perform(get("/login.html")) + .andExpect(status().is2xxSuccessful()); + } + + @Test + public void whenFormLoginAttempted_ThenSuccess() throws Exception { + mockMvc.perform(formLogin("/login") + .user("admin") + .password("admin")); + } + + @Test + public void whenFormLoginWithSuccess_ThenApiEndpointsAreAccessible() throws Exception { + mockMvc.perform(formLogin("/login") + .user("admin") + .password("admin")); + + mockMvc + .perform(get("/api/applications/")) + .andExpect(status().is2xxSuccessful()); + + } + + @Test + public void whenHttpBasicAttempted_ThenSuccess() throws Exception { + mockMvc.perform(get("/env").with(httpBasic("admin", "admin"))); + } + + @Test + public void whenInvalidHttpBasicAttempted_ThenUnauthorized() throws Exception { + mockMvc + .perform(get("/env").with(httpBasic("admin", "invalid"))) + .andExpect(status().isUnauthorized()); + } + +} diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 9da37a3261..5ad8330a89 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - org.springframework.boot - spring-boot-starter-parent - 1.5.3.RELEASE - + 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.keycloak + keycloak-spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + org.hsqldb + hsqldb + runtime + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + + org.keycloak.bom + keycloak-adapter-bom + 3.3.0.Final + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/Customer.java b/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/Customer.java new file mode 100644 index 0000000000..3293446b1d --- /dev/null +++ b/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/Customer.java @@ -0,0 +1,49 @@ +package com.baeldung.keycloak; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Customer { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + private String name; + private String serviceRendered; + private String address; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getServiceRendered() { + return serviceRendered; + } + + public void setServiceRendered(String serviceRendered) { + this.serviceRendered = serviceRendered; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + +} diff --git a/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomerDAO.java b/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomerDAO.java new file mode 100644 index 0000000000..20d992d335 --- /dev/null +++ b/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomerDAO.java @@ -0,0 +1,7 @@ +package com.baeldung.keycloak; + +import org.springframework.data.repository.CrudRepository; + +public interface CustomerDAO extends CrudRepository { + +} diff --git a/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java b/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java new file mode 100644 index 0000000000..4ecb62b6d4 --- /dev/null +++ b/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java @@ -0,0 +1,52 @@ +package com.baeldung.keycloak; + +import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver; +import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents; +import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider; +import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper; +import org.springframework.security.core.session.SessionRegistryImpl; +import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy; +import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; + +@Configuration +@EnableWebSecurity +@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class) +class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { + // Submits the KeycloakAuthenticationProvider to the AuthenticationManager + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider(); + keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper()); + auth.authenticationProvider(keycloakAuthenticationProvider); + } + + @Bean + public KeycloakSpringBootConfigResolver KeycloakConfigResolver() { + return new KeycloakSpringBootConfigResolver(); + } + + // Specifies the session authentication strategy + @Bean + @Override + protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { + return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + super.configure(http); + http.authorizeRequests() + .antMatchers("/customers*") + .hasRole("user") + .anyRequest() + .permitAll(); + } +} diff --git a/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBoot.java b/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBoot.java new file mode 100644 index 0000000000..d67dd05fc7 --- /dev/null +++ b/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBoot.java @@ -0,0 +1,14 @@ +package com.baeldung.keycloak; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication + +public class SpringBoot { + + public static void main(String[] args) { + SpringApplication.run(SpringBoot.class, args); + } + +} diff --git a/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/WebController.java b/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/WebController.java new file mode 100644 index 0000000000..3bafe1f195 --- /dev/null +++ b/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/WebController.java @@ -0,0 +1,52 @@ +package com.baeldung.keycloak; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +import java.security.Principal; + +import org.springframework.beans.factory.annotation.Autowired; + +@Controller +public class WebController { + + @Autowired + private CustomerDAO customerDAO; + + @GetMapping(path = "/") + public String index() { + return "external"; + } + + @GetMapping(path = "/customers") + public String customers(Principal principal, Model model) { + addCustomers(); + Iterable customers = customerDAO.findAll(); + model.addAttribute("customers", customers); + model.addAttribute("username", principal.getName()); + return "customers"; + } + + // add customers for demonstration + public void addCustomers() { + + Customer customer1 = new Customer(); + customer1.setAddress("1111 foo blvd"); + customer1.setName("Foo Industries"); + customer1.setServiceRendered("Important services"); + customerDAO.save(customer1); + + Customer customer2 = new Customer(); + customer2.setAddress("2222 bar street"); + customer2.setName("Bar LLP"); + customer2.setServiceRendered("Important services"); + customerDAO.save(customer2); + + Customer customer3 = new Customer(); + customer3.setAddress("33 main street"); + customer3.setName("Big LLC"); + customer3.setServiceRendered("Important services"); + customerDAO.save(customer3); + } +} diff --git a/spring-boot-keycloak/src/main/resources/application.properties b/spring-boot-keycloak/src/main/resources/application.properties new file mode 100644 index 0000000000..f667d3b27e --- /dev/null +++ b/spring-boot-keycloak/src/main/resources/application.properties @@ -0,0 +1,6 @@ +#Keycloak Configuration +keycloak.auth-server-url=http://localhost:8180/auth +keycloak.realm=SpringBootKeycloak +keycloak.resource=login-app +keycloak.public-client=true +keycloak.principal-attribute=preferred_username \ No newline at end of file diff --git a/spring-boot-keycloak/src/main/resources/templates/customers.html b/spring-boot-keycloak/src/main/resources/templates/customers.html new file mode 100644 index 0000000000..5a060d31da --- /dev/null +++ b/spring-boot-keycloak/src/main/resources/templates/customers.html @@ -0,0 +1,33 @@ + + + + + +
+

+ Hello, --name--. +

+ + + + + + + + + + + + + + + + + +
IDNameAddressService Rendered
Text ...Text ...Text ...Text...
+ +
+ + + diff --git a/spring-boot-keycloak/src/main/resources/templates/external.html b/spring-boot-keycloak/src/main/resources/templates/external.html new file mode 100644 index 0000000000..2f9cc76961 --- /dev/null +++ b/spring-boot-keycloak/src/main/resources/templates/external.html @@ -0,0 +1,31 @@ + + + + + +
+
+

Customer Portal

+
+
+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam + erat lectus, vehicula feugiat ultricies at, tempus sed ante. Cras + arcu erat, lobortis vitae quam et, mollis pharetra odio. Nullam sit + amet congue ipsum. Nunc dapibus odio ut ligula venenatis porta non + id dui. Duis nec tempor tellus. Suspendisse id blandit ligula, sit + amet varius mauris. Nulla eu eros pharetra, tristique dui quis, + vehicula libero. Aenean a neque sit amet tellus porttitor rutrum nec + at leo.

+ +

Existing Customers

+
+ Enter the intranet: customers +
+
+ +
+ + + + diff --git a/spring-boot-keycloak/src/main/resources/templates/layout.html b/spring-boot-keycloak/src/main/resources/templates/layout.html new file mode 100644 index 0000000000..bab0c2982b --- /dev/null +++ b/spring-boot-keycloak/src/main/resources/templates/layout.html @@ -0,0 +1,18 @@ + + + +Customer Portal + + + + + \ No newline at end of file diff --git a/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java b/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java new file mode 100644 index 0000000000..41662e5c17 --- /dev/null +++ b/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java @@ -0,0 +1,50 @@ +package com.baeldung.keycloak; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.keycloak.KeycloakPrincipal; +import org.keycloak.KeycloakSecurityContext; +import org.keycloak.adapters.springboot.client.KeycloakSecurityContextClientRequestInterceptor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.when; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = SpringBoot.class) +public class KeycloakConfigurationTest { + + @Spy + private KeycloakSecurityContextClientRequestInterceptor factory; + + private MockHttpServletRequest servletRequest; + + @Mock + public KeycloakSecurityContext keycloakSecurityContext; + + @Mock + private KeycloakPrincipal keycloakPrincipal; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + servletRequest = new MockHttpServletRequest(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(servletRequest)); + servletRequest.setUserPrincipal(keycloakPrincipal); + when(keycloakPrincipal.getKeycloakSecurityContext()).thenReturn(keycloakSecurityContext); + } + + @Test + public void testGetKeycloakSecurityContext() throws Exception { + assertNotNull(keycloakPrincipal.getKeycloakSecurityContext()); + } + +} diff --git a/spring-boot/.factorypath b/spring-boot/.factorypath new file mode 100644 index 0000000000..aa15485f5c --- /dev/null +++ b/spring-boot/.factorypath @@ -0,0 +1,149 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-boot/.gitignore b/spring-boot/.gitignore index e26d6af438..88e3308e9d 100644 --- a/spring-boot/.gitignore +++ b/spring-boot/.gitignore @@ -2,3 +2,4 @@ .settings/ .classpath .project + diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 9d44de64a3..5e5f01013d 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -24,7 +24,10 @@ org.springframework.boot spring-boot-starter-web - + + org.keycloak + keycloak-spring-boot-starter + org.springframework.boot spring-boot-starter-data-jpa @@ -73,7 +76,6 @@ tomcat-embed-core ${tomcat.version} - org.apache.tomcat.embed tomcat-embed-jasper @@ -170,6 +172,17 @@ artemis-server + + + + org.keycloak.bom + keycloak-adapter-bom + 3.3.0.CR2 + pom + import + + + spring-boot @@ -280,4 +293,4 @@ 2.4.1.Final - + \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/config/WebConfig.java b/spring-boot/src/main/java/org/baeldung/config/WebConfig.java index 4ef407823e..6609791c69 100644 --- a/spring-boot/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-boot/src/main/java/org/baeldung/config/WebConfig.java @@ -1,7 +1,11 @@ package org.baeldung.config; +import org.baeldung.converter.GenericBigDecimalConverter; +import org.baeldung.converter.StringToEnumConverterFactory; +import org.baeldung.converter.StringToEmployeeConverter; import org.baeldung.web.resolver.HeaderVersionArgumentResolver; import org.springframework.context.annotation.Configuration; +import org.springframework.format.FormatterRegistry; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -14,4 +18,11 @@ public class WebConfig extends WebMvcConfigurerAdapter { public void addArgumentResolvers(final List argumentResolvers) { argumentResolvers.add(new HeaderVersionArgumentResolver()); } + + @Override + public void addFormatters(FormatterRegistry registry) { + registry.addConverter(new StringToEmployeeConverter()); + registry.addConverterFactory(new StringToEnumConverterFactory()); + registry.addConverter(new GenericBigDecimalConverter()); + } } diff --git a/spring-boot/src/main/java/org/baeldung/converter/GenericBigDecimalConverter.java b/spring-boot/src/main/java/org/baeldung/converter/GenericBigDecimalConverter.java new file mode 100644 index 0000000000..1dbb7df6de --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/converter/GenericBigDecimalConverter.java @@ -0,0 +1,38 @@ +package org.baeldung.converter; + +import com.google.common.collect.ImmutableSet; +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.core.convert.converter.GenericConverter; + +import java.math.BigDecimal; +import java.math.MathContext; +import java.util.Set; + +public class GenericBigDecimalConverter implements GenericConverter { + @Override + public Set getConvertibleTypes () { + + ConvertiblePair[] pairs = new ConvertiblePair[] { + new ConvertiblePair(Number.class, BigDecimal.class), + new ConvertiblePair(String.class, BigDecimal.class)}; + + return ImmutableSet.copyOf(pairs); + } + + @Override + public Object convert (Object source, TypeDescriptor sourceType, + TypeDescriptor targetType) { + if (sourceType.getType() == BigDecimal.class) { + return source; + } + + if(sourceType.getType() == String.class) { + String number = (String) source; + return new BigDecimal(number); + } else { + Number number = (Number) source; + BigDecimal converted = new BigDecimal(number.doubleValue()); + return converted.setScale(2, BigDecimal.ROUND_HALF_EVEN); + } + } +} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/converter/StringToEmployeeConverter.java b/spring-boot/src/main/java/org/baeldung/converter/StringToEmployeeConverter.java new file mode 100644 index 0000000000..5f680972b7 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/converter/StringToEmployeeConverter.java @@ -0,0 +1,14 @@ +package org.baeldung.converter; + + +import com.baeldung.toggle.Employee; +import org.springframework.core.convert.converter.Converter; + +public class StringToEmployeeConverter implements Converter { + + @Override + public Employee convert(String from) { + String[] data = from.split(","); + return new Employee(Long.parseLong(data[0]), Double.parseDouble(data[1])); + } +} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/converter/controller/StringToEmployeeConverterController.java b/spring-boot/src/main/java/org/baeldung/converter/controller/StringToEmployeeConverterController.java new file mode 100644 index 0000000000..edd56dc136 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/converter/controller/StringToEmployeeConverterController.java @@ -0,0 +1,16 @@ +package org.baeldung.converter.controller; + +import com.baeldung.toggle.Employee; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/string-to-employee") +public class StringToEmployeeConverterController { + + @GetMapping + public ResponseEntity getStringToEmployee(@RequestParam("employee") Employee employee) { + return ResponseEntity.ok(employee); + } +} diff --git a/spring-boot/src/main/resources/templates/customers.html b/spring-boot/src/main/resources/templates/customers.html new file mode 100644 index 0000000000..5a060d31da --- /dev/null +++ b/spring-boot/src/main/resources/templates/customers.html @@ -0,0 +1,33 @@ + + + + + +
+

+ Hello, --name--. +

+ + + + + + + + + + + + + + + + + +
IDNameAddressService Rendered
Text ...Text ...Text ...Text...
+ +
+ + + diff --git a/spring-boot/src/main/resources/templates/external.html b/spring-boot/src/main/resources/templates/external.html new file mode 100644 index 0000000000..2f9cc76961 --- /dev/null +++ b/spring-boot/src/main/resources/templates/external.html @@ -0,0 +1,31 @@ + + + + + +
+
+

Customer Portal

+
+
+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam + erat lectus, vehicula feugiat ultricies at, tempus sed ante. Cras + arcu erat, lobortis vitae quam et, mollis pharetra odio. Nullam sit + amet congue ipsum. Nunc dapibus odio ut ligula venenatis porta non + id dui. Duis nec tempor tellus. Suspendisse id blandit ligula, sit + amet varius mauris. Nulla eu eros pharetra, tristique dui quis, + vehicula libero. Aenean a neque sit amet tellus porttitor rutrum nec + at leo.

+ +

Existing Customers

+
+ Enter the intranet: customers +
+
+ +
+ + + + diff --git a/spring-boot/src/main/resources/templates/layout.html b/spring-boot/src/main/resources/templates/layout.html new file mode 100644 index 0000000000..bab0c2982b --- /dev/null +++ b/spring-boot/src/main/resources/templates/layout.html @@ -0,0 +1,18 @@ + + + +Customer Portal + + + + + \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/converter/CustomConverterTest.java b/spring-boot/src/test/java/org/baeldung/converter/CustomConverterTest.java new file mode 100644 index 0000000000..6a585b9905 --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/converter/CustomConverterTest.java @@ -0,0 +1,53 @@ +package org.baeldung.converter; + +import com.baeldung.toggle.Employee; +import org.baeldung.Application; +import org.baeldung.domain.Modes; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.convert.ConversionService; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import java.math.BigDecimal; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = Application.class) +@WebAppConfiguration +public class CustomConverterTest { + + @Autowired + ConversionService conversionService; + + @Test + public void whenConvertStringToIntegerUsingDefaultConverter_thenSuccess() { + assertThat(conversionService.convert("25", Integer.class)).isEqualTo(25); + } + + @Test + public void whenConvertStringToEmployee_thenSuccess() { + Employee employee = conversionService.convert("1,50000.00", Employee.class); + Employee actualEmployee = new Employee(1, 50000.00); + assertThat(conversionService.convert("1,50000.00", Employee.class)) + .isEqualToComparingFieldByField(actualEmployee); + } + + @Test + public void whenConvertStringToEnum_thenSuccess() { + assertThat(conversionService.convert("ALPHA", Modes.class)).isEqualTo(Modes.ALPHA); + } + + @Test + public void whenConvertingToBigDecimalUsingGenericConverter_thenSuccess() { + assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class)) + .isEqualTo(BigDecimal.valueOf(11.00).setScale(2, BigDecimal.ROUND_HALF_EVEN)); + assertThat(conversionService.convert(Double.valueOf(25.23), BigDecimal.class)) + .isEqualByComparingTo(BigDecimal.valueOf(Double.valueOf(25.23))); + assertThat(conversionService.convert("2.32", BigDecimal.class)) + .isEqualTo(BigDecimal.valueOf(2.32)); + } +} \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerTest.java b/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerTest.java new file mode 100644 index 0000000000..a5ed7998b4 --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerTest.java @@ -0,0 +1,34 @@ +package org.baeldung.converter.controller; + +import org.baeldung.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import static org.hamcrest.CoreMatchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class) +@AutoConfigureMockMvc +public class StringToEmployeeConverterControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void getStringToEmployeeTest() throws Exception { + mockMvc.perform(get("/string-to-employee?employee=1,2000")) + .andDo(print()) + .andExpect(jsonPath("$.id", is(1))) + .andExpect(jsonPath("$.salary", is(2000.0))) + .andExpect(status().isOk()); + } +} diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 44e72535f8..93bf6ea74b 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -16,6 +16,7 @@ spring-cloud-rest spring-cloud-zookeeper spring-cloud-gateway + spring-cloud-connectors-heroku pom diff --git a/spring-cloud/spring-cloud-connectors-heroku/pom.xml b/spring-cloud/spring-cloud-connectors-heroku/pom.xml new file mode 100644 index 0000000000..ba3f0ef28f --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/pom.xml @@ -0,0 +1,100 @@ + + + 4.0.0 + + + spring-boot-starter-parent + org.springframework.boot + 1.4.4.RELEASE + + + + com.baeldung.spring.cloud + spring-cloud-connectors-heroku + 1.0.0-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-cloud-connectors + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-actuator + + + + org.postgresql + postgresql + 9.4-1201-jdbc4 + + + + com.h2database + h2 + runtime + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud-dependencies.version} + pom + import + + + + + + Brixton.SR7 + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + true + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.0 + + 1.8 + 1.8 + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/ConnectorsHerokuApplication.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/ConnectorsHerokuApplication.java new file mode 100644 index 0000000000..63246e89cc --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/ConnectorsHerokuApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.connectors.heroku; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ConnectorsHerokuApplication { + + public static void main(String[] args) { + SpringApplication.run(ConnectorsHerokuApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/Product.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/Product.java new file mode 100644 index 0000000000..40e8809fc5 --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/Product.java @@ -0,0 +1,30 @@ +package com.baeldung.spring.cloud.connectors.heroku.product; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Product { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long productId; + private String sku; + + public Long getProductId() { + return productId; + } + + public void setProductId(Long productId) { + this.productId = productId; + } + + public String getSku() { + return sku; + } + + public void setSku(String sku) { + this.sku = sku; + } +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductController.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductController.java new file mode 100644 index 0000000000..51cf4412bf --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductController.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.cloud.connectors.heroku.product; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/products") +public class ProductController { + + private final ProductService productService; + + @Autowired + public ProductController(ProductService productService) { + this.productService = productService; + } + + @GetMapping("/{productId}") + public Product findProduct(@PathVariable Long productId) { + return productService.findProductById(productId); + } + + @PostMapping + public Product createProduct(@RequestBody Product product) { + return productService.createProduct(product); + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductRepository.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductRepository.java new file mode 100644 index 0000000000..508e1d048b --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.spring.cloud.connectors.heroku.product; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ProductRepository extends JpaRepository{ +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductService.java b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductService.java new file mode 100644 index 0000000000..f25b4ecf7b --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/java/com/baeldung/spring/cloud/connectors/heroku/product/ProductService.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.cloud.connectors.heroku.product; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(readOnly = true) +public class ProductService { + private final ProductRepository productRepository; + + @Autowired + public ProductService(ProductRepository productRepository) { + this.productRepository = productRepository; + } + + public Product findProductById(Long productId) { + return productRepository.findOne(productId); + } + + @Transactional(propagation = Propagation.REQUIRED) + public Product createProduct(Product product) { + Product newProduct = new Product(); + newProduct.setSku(product.getSku()); + return productRepository.save(newProduct); + } +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/resources/application.properties b/spring-cloud/spring-cloud-connectors-heroku/src/main/resources/application.properties new file mode 100644 index 0000000000..d2f1c89dc5 --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.datasource.driverClassName=org.postgresql.Driver +spring.datasource.maxActive=10 +spring.datasource.maxIdle=5 +spring.datasource.minIdle=2 +spring.datasource.initialSize=5 +spring.datasource.removeAbandoned=true + +spring.jpa.hibernate.ddl-auto=update \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/di/spring/IService.java b/spring-core/src/main/java/com/baeldung/di/spring/IService.java new file mode 100644 index 0000000000..478eea0657 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/IService.java @@ -0,0 +1,5 @@ +package com.baeldung.di.spring; + +public interface IService { + public String serve(); +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/IndexApp.java b/spring-core/src/main/java/com/baeldung/di/spring/IndexApp.java new file mode 100644 index 0000000000..a45970d6b2 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/IndexApp.java @@ -0,0 +1,19 @@ +package com.baeldung.di.spring; + +public class IndexApp { + + private IService service; + + public String getServiceValue() { + return service.serve(); + } + + public IService getService() { + return service; + } + + public void setService(IService service) { + this.service = service; + } + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/IndexService.java b/spring-core/src/main/java/com/baeldung/di/spring/IndexService.java new file mode 100644 index 0000000000..ad241f5200 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/IndexService.java @@ -0,0 +1,10 @@ +package com.baeldung.di.spring; + +public class IndexService implements IService { + + @Override + public String serve() { + return "Hello World"; + } + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/InstanceServiceFactory.java b/spring-core/src/main/java/com/baeldung/di/spring/InstanceServiceFactory.java new file mode 100644 index 0000000000..f083504e8f --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/InstanceServiceFactory.java @@ -0,0 +1,14 @@ +package com.baeldung.di.spring; + +public class InstanceServiceFactory { + public IService getService(int number) { + switch (number) { + case 1: + return new MessageService("Foo"); + case 0: + return new IndexService(); + default: + throw new IllegalArgumentException("Unknown parameter " + number); + } + } +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/MessageApp.java b/spring-core/src/main/java/com/baeldung/di/spring/MessageApp.java new file mode 100644 index 0000000000..1bf6c20b28 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/MessageApp.java @@ -0,0 +1,14 @@ +package com.baeldung.di.spring; + +public class MessageApp { + + private IService iService; + + public MessageApp(IService iService) { + this.iService = iService; + } + + public String getServiceValue() { + return iService.serve(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/MessageService.java b/spring-core/src/main/java/com/baeldung/di/spring/MessageService.java new file mode 100644 index 0000000000..9b6efaab2a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/MessageService.java @@ -0,0 +1,16 @@ +package com.baeldung.di.spring; + +public class MessageService implements IService { + + private String message; + + public MessageService(String message) { + this.message = message; + } + + @Override + public String serve() { + return message; + } + +} diff --git a/spring-core/src/main/java/com/baeldung/di/spring/StaticServiceFactory.java b/spring-core/src/main/java/com/baeldung/di/spring/StaticServiceFactory.java new file mode 100644 index 0000000000..bd70898faf --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/di/spring/StaticServiceFactory.java @@ -0,0 +1,14 @@ +package com.baeldung.di.spring; + +public class StaticServiceFactory { + public static IService getService(int number) { + switch (number) { + case 1: + return new MessageService("Foo"); + case 0: + return new IndexService(); + default: + throw new IllegalArgumentException("Unknown parameter " + number); + } + } +} diff --git a/spring-core/src/main/resources/com.baeldung.di.spring.properties b/spring-core/src/main/resources/com.baeldung.di.spring.properties new file mode 100644 index 0000000000..8b8b5b85c2 --- /dev/null +++ b/spring-core/src/main/resources/com.baeldung.di.spring.properties @@ -0,0 +1 @@ +message.value=Hello World \ No newline at end of file diff --git a/spring-core/src/main/resources/com.baeldung.di.spring.xml b/spring-core/src/main/resources/com.baeldung.di.spring.xml new file mode 100644 index 0000000000..9c44d911d1 --- /dev/null +++ b/spring-core/src/main/resources/com.baeldung.di.spring.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java new file mode 100644 index 0000000000..1d133faf63 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java @@ -0,0 +1,45 @@ +package com.baeldung.di.spring; + +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class BeanInjectionTest { + + private ApplicationContext applicationContext; + + @Before + public void setUp() throws Exception { + applicationContext = new ClassPathXmlApplicationContext("com.baeldung.di.spring.xml"); + } + + @Test + public void protoBean_getBean_returnsMultipleInstance() { + final MessageApp messageApp1 = applicationContext.getBean("messageWorldApp", MessageApp.class); + final MessageApp messageApp2 = applicationContext.getBean("messageWorldApp", MessageApp.class); + assertNotEquals(messageApp1, messageApp2); + } + + @Test + public void protoFactoryMethod_getBean_returnsMultipleInstance() { + final IndexApp indexApp1 = applicationContext.getBean("indexAppWithFactoryMethod", IndexApp.class); + final IndexApp indexApp2 = applicationContext.getBean("indexAppWithFactoryMethod", IndexApp.class); + assertNotEquals(indexApp1, indexApp2); + } + + @Test + public void protoStaticFactory_getBean_returnsMultipleInstance() { + final IndexApp indexApp1 = applicationContext.getBean("indexAppWithStaticFactory", IndexApp.class); + final IndexApp indexApp2 = applicationContext.getBean("indexAppWithStaticFactory", IndexApp.class); + assertNotEquals(indexApp1, indexApp2); + } + + @Test + public void singletonBean_getBean_returnsSingleInstance() { + final IndexApp indexApp1 = applicationContext.getBean("indexApp", IndexApp.class); + final IndexApp indexApp2 = applicationContext.getBean("indexApp", IndexApp.class); + assertEquals(indexApp1, indexApp2); + } +} diff --git a/spring-groovy/pom.xml b/spring-groovy/pom.xml index 59c7ba4a7c..9086369fa4 100644 --- a/spring-groovy/pom.xml +++ b/spring-groovy/pom.xml @@ -37,5 +37,38 @@ spring-integration-groovy 4.3.7.RELEASE + + org.codehaus.groovy + groovy-all + 2.4.12 + + + + + maven-compiler-plugin + 3.7.0 + + groovy-eclipse-compiler + true + 1.8 + 1.8 + ${project.build.sourceEncoding} + + + + org.codehaus.groovy + groovy-eclipse-compiler + 2.9.2-01 + + + org.codehaus.groovy + groovy-eclipse-batch + 2.4.3-01 + + + + + + diff --git a/spring-groovy/src/main/java/com/baeldug/groovyconfig/BandsBean.java b/spring-groovy/src/main/java/com/baeldug/groovyconfig/BandsBean.java new file mode 100644 index 0000000000..1deba5d2f6 --- /dev/null +++ b/spring-groovy/src/main/java/com/baeldug/groovyconfig/BandsBean.java @@ -0,0 +1,17 @@ +package com.baeldug.groovyconfig; + +import java.util.ArrayList; +import java.util.List; + +public class BandsBean { + + private List bandsList = new ArrayList<>(); + + public List getBandsList() { + return bandsList; + } + + public void setBandsList(List bandsList) { + this.bandsList = bandsList; + } +} diff --git a/spring-groovy/src/main/java/com/baeldug/groovyconfig/GroovyBeanConfig.groovy b/spring-groovy/src/main/java/com/baeldug/groovyconfig/GroovyBeanConfig.groovy new file mode 100644 index 0000000000..32a6fedff0 --- /dev/null +++ b/spring-groovy/src/main/java/com/baeldug/groovyconfig/GroovyBeanConfig.groovy @@ -0,0 +1,18 @@ +package com.baeldug.groovyconfig; + +beans { + javaPesronBean(JavaPersonBean) { + firstName = 'John' + lastName = 'Doe' + age ='32' + eyesColor = 'blue' + hairColor='black' + } + + bandsBean(BandsBean) { bean-> + bean.scope = "singleton" + bandsList=['Nirvana', 'Pearl Jam', 'Foo Fighters'] + } + + registerAlias("bandsBean","bands") +} diff --git a/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaBeanConfig.java b/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaBeanConfig.java new file mode 100644 index 0000000000..7c4238ae28 --- /dev/null +++ b/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaBeanConfig.java @@ -0,0 +1,21 @@ +package com.baeldug.groovyconfig; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class JavaBeanConfig { + + @Bean + public JavaPersonBean javaPerson() { + JavaPersonBean jPerson = new JavaPersonBean(); + jPerson.setFirstName("John"); + jPerson.setLastName("Doe"); + jPerson.setAge("31"); + jPerson.setEyesColor("green"); + jPerson.setHairColor("blond"); + + return jPerson; + } + +} diff --git a/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaPersonBean.java b/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaPersonBean.java new file mode 100644 index 0000000000..db988d4abf --- /dev/null +++ b/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaPersonBean.java @@ -0,0 +1,57 @@ +package com.baeldug.groovyconfig; + +public class JavaPersonBean { + + public String jj; + + private String firstName; + + private String lastName; + + private String age; + + private String eyesColor; + + private String hairColor; + + 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; + } + + public String getAge() { + return age; + } + + public void setAge(String age) { + this.age = age; + } + + public String getEyesColor() { + return eyesColor; + } + + public void setEyesColor(String eyesColor) { + this.eyesColor = eyesColor; + } + + public String getHairColor() { + return hairColor; + } + + public void setHairColor(String hairColor) { + this.hairColor = hairColor; + } + +} diff --git a/spring-groovy/src/main/resources/xml-bean-config.xml b/spring-groovy/src/main/resources/xml-bean-config.xml new file mode 100644 index 0000000000..3b880bbd70 --- /dev/null +++ b/spring-groovy/src/main/resources/xml-bean-config.xml @@ -0,0 +1,12 @@ + + + + + + + + + + \ No newline at end of file diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationTest.java b/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationTest.java new file mode 100644 index 0000000000..91ca6dbfe9 --- /dev/null +++ b/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationTest.java @@ -0,0 +1,50 @@ +package com.baeldug.groovyconfig; + +import static org.junit.Assert.assertEquals; + +import java.io.File; + +import org.junit.Test; +import org.springframework.context.support.GenericGroovyApplicationContext; + +public class GroovyConfigurationTest { + + private static final String FILE_NAME = "GroovyBeanConfig.groovy"; + private static final String FILE_PATH = "src/main/java/com/baeldug/groovyconfig/"; + + @Test + public void whenGroovyConfig_thenCorrectPerson() throws Exception { + + GenericGroovyApplicationContext ctx = new GenericGroovyApplicationContext(); + ctx.load("file:" + getPathPart() + FILE_NAME); + ctx.refresh(); + + JavaPersonBean j = ctx.getBean(JavaPersonBean.class); + + assertEquals("32", j.getAge()); + assertEquals("blue", j.getEyesColor()); + assertEquals("black", j.getHairColor()); + } + + @Test + public void whenGroovyConfig_thenCorrectListLength() throws Exception { + + GenericGroovyApplicationContext ctx = new GenericGroovyApplicationContext(); + ctx.load("file:" + getPathPart() + FILE_NAME); + ctx.refresh(); + + BandsBean bb = ctx.getBean(BandsBean.class); + + assertEquals(3, bb.getBandsList() + .size()); + } + + private String getPathPart() { + String pathPart = new File(".").getAbsolutePath(); + pathPart = pathPart.replace(".", ""); + pathPart = pathPart.replace("\\", "/"); + pathPart = pathPart + FILE_PATH; + + return pathPart; + } +} diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationTest.java b/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationTest.java new file mode 100644 index 0000000000..2d9b1000ff --- /dev/null +++ b/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationTest.java @@ -0,0 +1,24 @@ +package com.baeldug.groovyconfig; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class JavaConfigurationTest { + + @Test + public void whenJavaConfig_thenCorrectPerson() { + + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + ctx.register(JavaBeanConfig.class); + ctx.refresh(); + + JavaPersonBean j = ctx.getBean(JavaPersonBean.class); + + assertEquals("31", j.getAge()); + assertEquals("green", j.getEyesColor()); + assertEquals("blond", j.getHairColor()); + + } +} diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationTest.java b/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationTest.java new file mode 100644 index 0000000000..3ee724207c --- /dev/null +++ b/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationTest.java @@ -0,0 +1,23 @@ +package com.baeldug.groovyconfig; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class XmlConfigurationTest { + + @Test + public void whenXmlConfig_thenCorrectPerson() { + final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("xml-bean-config.xml"); + + JavaPersonBean j = (JavaPersonBean) applicationContext.getBean("JavaPersonBean"); + + assertEquals("30", j.getAge()); + assertEquals("brown", j.getEyesColor()); + assertEquals("brown", j.getHairColor()); + + } + +} diff --git a/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java b/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java new file mode 100644 index 0000000000..a128d8848c --- /dev/null +++ b/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java @@ -0,0 +1,81 @@ +package org.baeldung.spring; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.orm.hibernate3.HibernateTransactionManager; +import org.springframework.orm.hibernate3.LocalSessionFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-h2.properties" }) +@ComponentScan({ "org.baeldung.persistence.dao", "org.baeldung.persistence.service" }) +public class PersistenceConfigHibernate3 { + + @Autowired + private Environment env; + + public PersistenceConfigHibernate3() { + super(); + } + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + Resource config = new ClassPathResource("exceptionDemo.cfg.xml"); + sessionFactory.setDataSource(dataSource()); + sessionFactory.setConfigLocation(config); + 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 + @Autowired + public HibernateTransactionManager transactionManager(final SessionFactory sessionFactory) { + final HibernateTransactionManager txManager = new HibernateTransactionManager(); + txManager.setSessionFactory(sessionFactory); + + return txManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + +} diff --git a/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java b/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java new file mode 100644 index 0000000000..d53c4445a8 --- /dev/null +++ b/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java @@ -0,0 +1,43 @@ +package org.baeldung.persistence.service; + +import java.util.List; + +import org.baeldung.persistence.model.Event; +import org.baeldung.spring.PersistenceConfigHibernate3; +import org.hamcrest.core.IsInstanceOf; +import org.hibernate.HibernateException; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +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; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfigHibernate3.class }, loader = AnnotationConfigContextLoader.class) +public class HibernateExceptionScen1MainIntegrationTest { + + @Autowired + EventService service; + + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + service.create(new Event("from LocalSessionFactoryBean")); + } + + @Test + @Ignore + public final void whenNoTransBoundToSession_thenException() { + expectedEx.expectCause(IsInstanceOf.instanceOf(HibernateException.class)); + expectedEx.expectMessage("No Hibernate Session bound to thread, " + + "and configuration does not allow creation " + + "of non-transactional one here"); + service.create(new Event("from LocalSessionFactoryBean")); + } +} diff --git a/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java b/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java new file mode 100644 index 0000000000..84cafe0536 --- /dev/null +++ b/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java @@ -0,0 +1,45 @@ +package org.baeldung.persistence.service; + +import java.util.List; + +import org.baeldung.persistence.model.Event; +import org.baeldung.spring.PersistenceConfig; +import org.hamcrest.core.IsInstanceOf; +import org.hibernate.HibernateException; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +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; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class HibernateExceptionScen2MainIntegrationTest { + + @Autowired + EventService service; + + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + service.create(new Event("from AnnotationSessionFactoryBean")); + } + + @Test + @Ignore + public final void whenNoTransBoundToSession_thenException() { + expectedEx.expectCause(IsInstanceOf.instanceOf(HibernateException.class)); + expectedEx.expectMessage("No Hibernate Session bound to thread, " + + "and configuration does not allow creation " + + "of non-transactional one here"); + service.create(new Event("from AnnotationSessionFactoryBean")); + } + +} diff --git a/spring-jmeter-jenkins/.gitignore b/spring-jmeter-jenkins/.gitignore new file mode 100644 index 0000000000..2af7cefb0a --- /dev/null +++ b/spring-jmeter-jenkins/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/spring-jmeter-jenkins/.mvn/wrapper/maven-wrapper.jar b/spring-jmeter-jenkins/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000..5fd4d5023f Binary files /dev/null and b/spring-jmeter-jenkins/.mvn/wrapper/maven-wrapper.jar differ diff --git a/spring-jmeter-jenkins/.mvn/wrapper/maven-wrapper.properties b/spring-jmeter-jenkins/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..c954cec91c --- /dev/null +++ b/spring-jmeter-jenkins/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip diff --git a/spring-jmeter-jenkins/README.md b/spring-jmeter-jenkins/README.md new file mode 100644 index 0000000000..49c18122a2 --- /dev/null +++ b/spring-jmeter-jenkins/README.md @@ -0,0 +1,55 @@ +BASIC CRUD API with Spring Boot +================================ + +This is the code of a simple API for some CRUD operations realised for a seminar at [FGI](www.fgi-ud.org) using Spring Boot. + +### Demo +* API: The online version **is**/**will be** hosted here: https://fgi-tcheck.herokuapp.com +* Mobile version is also opensource and located here: https://github.com/valdesekamdem/tcheck-mobile + +### Features +#### Currently Implemented +* CRUD + * Student + +#### To DO +* Validations of input with: [Spring Data Rest Validators](http://docs.spring.io/spring-data/rest/docs/2.1.0.RELEASE/reference/html/validation-chapter.html) + + +### Requirements + +- Maven +- JDK 8 +- MongoDB + +### Running + +To build and start the server simply type + +```bash +$ mvn clean install +$ mvn spring-boot:run -Dserver.port=8989 +``` + +### Available CRUD + +You can see what crud operation are available using curl: + +```bash +$ curl localhost:8080 +``` +You can view existing student objects with this command: + +```bash +$ curl localhost:8080/students +``` +Or create a new one via a POST: + +```bash +$ curl -X POST -H "Content-Type:application/json" -d '{ "firstName" : "Dassi", "lastName" : "Orleando", "phoneNumber": "+237 545454545", "email": "mymail@yahoo.fr" }' localhost:8080/students +``` + + +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/spring-jmeter-jenkins/mvnw b/spring-jmeter-jenkins/mvnw new file mode 100755 index 0000000000..a1ba1bf554 --- /dev/null +++ b/spring-jmeter-jenkins/mvnw @@ -0,0 +1,233 @@ +#!/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 + # + # Look for the Apple JDKs first to preserve the existing behaviour, and then look + # for the new JDKs provided by Oracle. + # + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then + # + # Oracle JDKs + # + export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then + # + # Apple JDKs + # + export JAVA_HOME=`/usr/libexec/java_home` + 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 Migwn, 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 + +# 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"` +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + local basedir=$(pwd) + local wdir=$(pwd) + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + wdir=$(cd "$wdir/.."; pwd) + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +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} "$@" diff --git a/spring-jmeter-jenkins/mvnw.cmd b/spring-jmeter-jenkins/mvnw.cmd new file mode 100644 index 0000000000..2b934e89dd --- /dev/null +++ b/spring-jmeter-jenkins/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 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 + +set MAVEN_CMD_LINE_ARGS=%* + +@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="".\.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_CMD_LINE_ARGS% +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% \ No newline at end of file diff --git a/spring-jmeter-jenkins/pom.xml b/spring-jmeter-jenkins/pom.xml new file mode 100644 index 0000000000..38b5f98e45 --- /dev/null +++ b/spring-jmeter-jenkins/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + spring-jmeter-jenkins + 0.0.1-SNAPSHOT + jar + + spring-jmeter-jenkins + Run and Show JMeter test with Jenkins + + + parent-boot-5 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-5 + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + org.springframework.boot + spring-boot-starter-data-rest + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-jmeter-jenkins/src/main/java/com/baeldung/SpringJMeterJenkinsApplication.java b/spring-jmeter-jenkins/src/main/java/com/baeldung/SpringJMeterJenkinsApplication.java new file mode 100644 index 0000000000..3bc1f64f41 --- /dev/null +++ b/spring-jmeter-jenkins/src/main/java/com/baeldung/SpringJMeterJenkinsApplication.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; + +@SpringBootApplication +@EnableMongoRepositories +public class SpringJMeterJenkinsApplication { + public static void main(String[] args) { + SpringApplication.run(SpringJMeterJenkinsApplication.class, args); + } +} diff --git a/spring-jmeter-jenkins/src/main/java/com/baeldung/domain/Student.java b/spring-jmeter-jenkins/src/main/java/com/baeldung/domain/Student.java new file mode 100644 index 0000000000..0f6150fc48 --- /dev/null +++ b/spring-jmeter-jenkins/src/main/java/com/baeldung/domain/Student.java @@ -0,0 +1,66 @@ +package com.baeldung.domain; + +import javax.validation.constraints.NotNull; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +import java.io.Serializable; + +@Document(collection = "STUDENT") +public class Student implements Serializable { + + @Id + private String id; + @NotNull + private String firstName; + private String lastName; + @NotNull + private String phoneNumber; + private String email; + + public String getId() { + return id; + } + + 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; + } + + public String getPhoneNumber() { + return phoneNumber; + } + + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "Student{" + + "firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + ", phoneNumber='" + phoneNumber + '\'' + + ", email='" + email + '\'' + + '}'; + } +} diff --git a/spring-jmeter-jenkins/src/main/java/com/baeldung/repository/StudentRepository.java b/spring-jmeter-jenkins/src/main/java/com/baeldung/repository/StudentRepository.java new file mode 100644 index 0000000000..d0ca7d8510 --- /dev/null +++ b/spring-jmeter-jenkins/src/main/java/com/baeldung/repository/StudentRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.repository; + +import org.springframework.data.mongodb.repository.MongoRepository; +import com.baeldung.domain.Student; + +public interface StudentRepository extends MongoRepository { +} diff --git a/spring-jmeter-jenkins/src/main/resources/JMeter-Jenkins.jmx b/spring-jmeter-jenkins/src/main/resources/JMeter-Jenkins.jmx new file mode 100644 index 0000000000..49ce2dec1d --- /dev/null +++ b/spring-jmeter-jenkins/src/main/resources/JMeter-Jenkins.jmx @@ -0,0 +1,96 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 5 + 1 + 1507776008000 + 1507776008000 + false + + + + + + + + + localhost + 8989 + + + /students + GET + true + false + true + false + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + true + false + false + false + true + 0 + true + true + true + true + true + + + + + + + 10 + + + + + + + true + + + + diff --git a/spring-jmeter-jenkins/src/main/resources/application.properties b/spring-jmeter-jenkins/src/main/resources/application.properties new file mode 100644 index 0000000000..c7d86e14b0 --- /dev/null +++ b/spring-jmeter-jenkins/src/main/resources/application.properties @@ -0,0 +1,14 @@ +# the db host +spring.data.mongodb.host=localhost +# the connection port (defaults to 27107) +spring.data.mongodb.port=27017 +# The database's name +spring.data.mongodb.database=JMeter-Jenkins + +# Or this +# spring.data.mongodb.uri=mongodb://localhost/JMeter-Jenkins + +# spring.data.mongodb.username= +# spring.data.mongodb.password= + +spring.data.mongodb.repositories.enabled=true \ No newline at end of file diff --git a/spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationTests.java b/spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationTests.java new file mode 100644 index 0000000000..b39a5605b1 --- /dev/null +++ b/spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationTests.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringJMeterJenkinsApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-jms/README.md b/spring-jms/README.md index 9093937f44..b942cc72a0 100644 --- a/spring-jms/README.md +++ b/spring-jms/README.md @@ -1,2 +1,2 @@ -###Relevant Articles: +### Relevant Articles: - [An Introduction To Spring JMS](http://www.baeldung.com/spring-jms) diff --git a/spring-jms/src/main/webapp/META-INF/MANIFEST.MF b/spring-jms/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..5e9495128c --- /dev/null +++ b/spring-jms/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/spring-jpa/README.md b/spring-jpa/README.md index 70f4404f98..d93271164c 100644 --- a/spring-jpa/README.md +++ b/spring-jpa/README.md @@ -14,6 +14,7 @@ - [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) - [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate) - [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database) +- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/spring-security-rest-full/.gitignore b/spring-rest-full/.gitignore similarity index 100% rename from spring-security-rest-full/.gitignore rename to spring-rest-full/.gitignore diff --git a/spring-security-rest-full/README.md b/spring-rest-full/README.md similarity index 65% rename from spring-security-rest-full/README.md rename to spring-rest-full/README.md index 2737bd5465..a1fea806ef 100644 --- a/spring-security-rest-full/README.md +++ b/spring-rest-full/README.md @@ -1,6 +1,6 @@ ========= -## REST Example Project with Spring Security +## REST Example Project with Spring ### Courses The "REST With Spring" Classes: http://bit.ly/restwithspring @@ -15,15 +15,9 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Integration Testing with the Maven Cargo plugin](http://www.baeldung.com/2011/10/16/how-to-set-up-integration-testing-with-the-maven-cargo-plugin/) - [Introduction to Spring Data JPA](http://www.baeldung.com/2011/12/22/the-persistence-layer-with-spring-data-jpa/) - [Project Configuration with Spring](http://www.baeldung.com/2012/03/12/project-configuration-with-spring/) -- [REST Query Language with Spring and JPA Criteria](http://www.baeldung.com/rest-search-language-spring-jpa-criteria) -- [REST Query Language with Spring Data JPA Specifications](http://www.baeldung.com/rest-api-search-language-spring-data-specifications) -- [REST Query Language with Spring Data JPA and QueryDSL](http://www.baeldung.com/rest-api-search-language-spring-data-querydsl) -- [REST Query Language – Advanced Search Operations](http://www.baeldung.com/rest-api-query-search-language-more-operations) - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) -- [REST Query Language with RSQL](http://www.baeldung.com/rest-api-search-language-rsql-fiql) - [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) - [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) -- [REST Query Language – Implementing OR Operation](http://www.baeldung.com/rest-api-query-search-or-operation) @@ -46,5 +40,5 @@ mysql -u root -p ### Use the REST Service ``` -curl http://localhost:8080/spring-security-rest-full/foos +curl http://localhost:8080/spring-rest-full/foos ``` diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml new file mode 100644 index 0000000000..c596e79b31 --- /dev/null +++ b/spring-rest-full/pom.xml @@ -0,0 +1,378 @@ + + 4.0.0 + com.baeldung + spring-rest-full + 0.1-SNAPSHOT + + spring-rest-full + war + + + parent-boot-4 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-4 + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.aspectj + aspectjweaver + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + + + org.springframework + spring-core + + + commons-logging + commons-logging + + + + + org.springframework + spring-context + + + org.springframework + spring-jdbc + + + org.springframework + spring-beans + + + org.springframework + spring-aop + + + org.springframework + spring-tx + + + org.springframework + spring-expression + + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + + org.springframework.data + spring-data-commons + + + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + + + org.apache.httpcomponents + httpclient + + + commons-logging + commons-logging + + + + + org.apache.httpcomponents + httpcore + + + + + + org.springframework + spring-orm + + + org.springframework.data + spring-data-jpa + + + org.hibernate + hibernate-entitymanager + + + xml-apis + xml-apis + + + org.javassist + javassist + + + mysql + mysql-connector-java + runtime + + + + com.h2database + h2 + + + + + + javax.servlet + javax.servlet-api + provided + + + + javax.servlet + jstl + runtime + + + + + + com.fasterxml.jackson.core + jackson-databind + + + + com.thoughtworks.xstream + xstream + ${xstream.version} + + + + + + com.google.guava + guava + ${guava.version} + + + + + + org.springframework + spring-test + test + + + + + + + + + + org.hamcrest + hamcrest-library + test + + + + org.mockito + mockito-core + test + + + + + + spring-rest-full + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + + + + + + com.mysema.maven + apt-maven-plugin + ${apt-maven-plugin.version} + + + + process + + + target/generated-sources/java + com.querydsl.apt.jpa.JPAAnnotationProcessor + + + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + **/*LiveTest.java + + + + + + + json + + + + + org.codehaus.cargo + cargo-maven2-plugin + + false + + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + + + + + + + 1.4.9 + + + 19.0 + 3.5 + + + 1.6.1 + 1.1.3 + + + \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/IOperations.java b/spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/IOperations.java rename to spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/IFooDao.java b/spring-rest-full/src/main/java/org/baeldung/persistence/dao/IFooDao.java similarity index 69% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/IFooDao.java rename to spring-rest-full/src/main/java/org/baeldung/persistence/dao/IFooDao.java index 824d6ea546..230abd0d5f 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/IFooDao.java +++ b/spring-rest-full/src/main/java/org/baeldung/persistence/dao/IFooDao.java @@ -2,13 +2,10 @@ package org.baeldung.persistence.dao; import org.baeldung.persistence.model.Foo; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; - -public interface IFooDao extends JpaRepository, JpaSpecificationExecutor { +public interface IFooDao extends JpaRepository { @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)") Foo retrieveByName(@Param("name") String name); - } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-rest-full/src/main/java/org/baeldung/persistence/model/Foo.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Foo.java rename to spring-rest-full/src/main/java/org/baeldung/persistence/model/Foo.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User.java b/spring-rest-full/src/main/java/org/baeldung/persistence/model/User.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User.java rename to spring-rest-full/src/main/java/org/baeldung/persistence/model/User.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/service/IFooService.java b/spring-rest-full/src/main/java/org/baeldung/persistence/service/IFooService.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/service/IFooService.java rename to spring-rest-full/src/main/java/org/baeldung/persistence/service/IFooService.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java b/spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java rename to spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java b/spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java rename to spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/Application.java b/spring-rest-full/src/main/java/org/baeldung/spring/Application.java similarity index 98% rename from spring-security-rest-full/src/main/java/org/baeldung/spring/Application.java rename to spring-rest-full/src/main/java/org/baeldung/spring/Application.java index a43b21c2b7..9a3f473b8b 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/Application.java +++ b/spring-rest-full/src/main/java/org/baeldung/spring/Application.java @@ -16,7 +16,7 @@ import org.springframework.web.filter.ShallowEtagHeaderFilter; /** * Main Application Class - uses Spring Boot. Just run this as a normal Java - * class to run up a Jetty Server (on http://localhost:8082/spring-security-rest-full) + * class to run up a Jetty Server (on http://localhost:8082/spring-rest-full) * */ @EnableScheduling diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java rename to spring-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java b/spring-rest-full/src/main/java/org/baeldung/spring/WebConfig.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java rename to spring-rest-full/src/main/java/org/baeldung/spring/WebConfig.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java rename to spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java rename to spring-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java b/spring-rest-full/src/main/java/org/baeldung/web/controller/RootController.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java rename to spring-rest-full/src/main/java/org/baeldung/web/controller/RootController.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java b/spring-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java rename to spring-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-full/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java rename to spring-rest-full/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/event/PaginatedResultsRetrievedEvent.java b/spring-rest-full/src/main/java/org/baeldung/web/hateoas/event/PaginatedResultsRetrievedEvent.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/event/PaginatedResultsRetrievedEvent.java rename to spring-rest-full/src/main/java/org/baeldung/web/hateoas/event/PaginatedResultsRetrievedEvent.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/event/ResourceCreatedEvent.java b/spring-rest-full/src/main/java/org/baeldung/web/hateoas/event/ResourceCreatedEvent.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/event/ResourceCreatedEvent.java rename to spring-rest-full/src/main/java/org/baeldung/web/hateoas/event/ResourceCreatedEvent.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java b/spring-rest-full/src/main/java/org/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java rename to spring-rest-full/src/main/java/org/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java b/spring-rest-full/src/main/java/org/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java rename to spring-rest-full/src/main/java/org/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/ResourceCreatedDiscoverabilityListener.java b/spring-rest-full/src/main/java/org/baeldung/web/hateoas/listener/ResourceCreatedDiscoverabilityListener.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/ResourceCreatedDiscoverabilityListener.java rename to spring-rest-full/src/main/java/org/baeldung/web/hateoas/listener/ResourceCreatedDiscoverabilityListener.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java b/spring-rest-full/src/main/java/org/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java rename to spring-rest-full/src/main/java/org/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java rename to spring-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java rename to spring-rest-full/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java rename to spring-rest-full/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java rename to spring-rest-full/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/IMetricService.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/IMetricService.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/metric/IMetricService.java rename to spring-rest-full/src/main/java/org/baeldung/web/metric/IMetricService.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java rename to spring-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricService.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/MetricService.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricService.java rename to spring-rest-full/src/main/java/org/baeldung/web/metric/MetricService.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/util/LinkUtil.java b/spring-rest-full/src/main/java/org/baeldung/web/util/LinkUtil.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/util/LinkUtil.java rename to spring-rest-full/src/main/java/org/baeldung/web/util/LinkUtil.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java b/spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java rename to spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java diff --git a/spring-rest-full/src/main/resources/application.properties b/spring-rest-full/src/main/resources/application.properties new file mode 100644 index 0000000000..6c7461f12c --- /dev/null +++ b/spring-rest-full/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8082 +server.context-path=/spring-rest-full +endpoints.metrics.enabled=true \ No newline at end of file diff --git a/spring-security-rest-full/src/main/resources/logback.xml b/spring-rest-full/src/main/resources/logback.xml similarity index 100% rename from spring-security-rest-full/src/main/resources/logback.xml rename to spring-rest-full/src/main/resources/logback.xml diff --git a/spring-security-rest-full/src/main/resources/persistence-h2.properties b/spring-rest-full/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-security-rest-full/src/main/resources/persistence-h2.properties rename to spring-rest-full/src/main/resources/persistence-h2.properties diff --git a/spring-security-rest-full/src/main/resources/persistence-mysql.properties b/spring-rest-full/src/main/resources/persistence-mysql.properties similarity index 100% rename from spring-security-rest-full/src/main/resources/persistence-mysql.properties rename to spring-rest-full/src/main/resources/persistence-mysql.properties diff --git a/spring-security-rest-full/src/main/resources/springDataPersistenceConfig.xml b/spring-rest-full/src/main/resources/springDataPersistenceConfig.xml similarity index 100% rename from spring-security-rest-full/src/main/resources/springDataPersistenceConfig.xml rename to spring-rest-full/src/main/resources/springDataPersistenceConfig.xml diff --git a/spring-security-rest-full/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest-full/src/main/webapp/WEB-INF/api-servlet.xml similarity index 100% rename from spring-security-rest-full/src/main/webapp/WEB-INF/api-servlet.xml rename to spring-rest-full/src/main/webapp/WEB-INF/api-servlet.xml diff --git a/spring-security-rest-full/src/main/webapp/WEB-INF/view/graph.jsp b/spring-rest-full/src/main/webapp/WEB-INF/view/graph.jsp similarity index 100% rename from spring-security-rest-full/src/main/webapp/WEB-INF/view/graph.jsp rename to spring-rest-full/src/main/webapp/WEB-INF/view/graph.jsp diff --git a/spring-security-rest-full/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-rest-full/src/main/webapp/WEB-INF/view/homepage.jsp similarity index 100% rename from spring-security-rest-full/src/main/webapp/WEB-INF/view/homepage.jsp rename to spring-rest-full/src/main/webapp/WEB-INF/view/homepage.jsp diff --git a/spring-security-rest-full/src/main/webapp/WEB-INF/web.xml b/spring-rest-full/src/main/webapp/WEB-INF/web.xml similarity index 81% rename from spring-security-rest-full/src/main/webapp/WEB-INF/web.xml rename to spring-rest-full/src/main/webapp/WEB-INF/web.xml index 49e4d1afa1..85bc72469e 100644 --- a/spring-security-rest-full/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest-full/src/main/webapp/WEB-INF/web.xml @@ -5,7 +5,7 @@ http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0" > - Spring Security REST Application + Spring REST Application @@ -43,16 +43,6 @@ / - - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - - - springSecurityFilterChain - /* - - metricFilter diff --git a/spring-security-rest-full/src/test/java/org/baeldung/Consts.java b/spring-rest-full/src/test/java/org/baeldung/Consts.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/Consts.java rename to spring-rest-full/src/test/java/org/baeldung/Consts.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/TestSuite.java b/spring-rest-full/src/test/java/org/baeldung/TestSuite.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/TestSuite.java rename to spring-rest-full/src/test/java/org/baeldung/TestSuite.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractBasicLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/common/web/AbstractBasicLiveTest.java similarity index 73% rename from spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractBasicLiveTest.java rename to spring-rest-full/src/test/java/org/baeldung/common/web/AbstractBasicLiveTest.java index 2cc0aa7b28..4e0007d036 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractBasicLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/common/web/AbstractBasicLiveTest.java @@ -10,6 +10,8 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import io.restassured.RestAssured; +import io.restassured.response.Response; import java.io.Serializable; import java.util.List; @@ -18,7 +20,6 @@ import org.junit.Ignore; import org.junit.Test; import com.google.common.net.HttpHeaders; -import io.restassured.response.Response; public abstract class AbstractBasicLiveTest extends AbstractLiveTest { @@ -34,7 +35,9 @@ public abstract class AbstractBasicLiveTest extends Abst final String uriOfResource = createAsUri(); // When - final Response findOneResponse = givenAuth().header("Accept", "application/json").get(uriOfResource); + final Response findOneResponse = RestAssured.given() + .header("Accept", "application/json") + .get(uriOfResource); // Then assertNotNull(findOneResponse.getHeader(HttpHeaders.ETAG)); @@ -44,11 +47,16 @@ public abstract class AbstractBasicLiveTest extends Abst public void givenResourceWasRetrieved_whenRetrievingAgainWithEtag_thenNotModifiedReturned() { // Given final String uriOfResource = createAsUri(); - final Response findOneResponse = givenAuth().header("Accept", "application/json").get(uriOfResource); + final Response findOneResponse = RestAssured.given() + .header("Accept", "application/json") + .get(uriOfResource); final String etagValue = findOneResponse.getHeader(HttpHeaders.ETAG); // When - final Response secondFindOneResponse = givenAuth().header("Accept", "application/json").headers("If-None-Match", etagValue).get(uriOfResource); + final Response secondFindOneResponse = RestAssured.given() + .header("Accept", "application/json") + .headers("If-None-Match", etagValue) + .get(uriOfResource); // Then assertTrue(secondFindOneResponse.getStatusCode() == 304); @@ -59,14 +67,19 @@ public abstract class AbstractBasicLiveTest extends Abst public void givenResourceWasRetrievedThenModified_whenRetrievingAgainWithEtag_thenResourceIsReturned() { // Given final String uriOfResource = createAsUri(); - final Response findOneResponse = givenAuth().header("Accept", "application/json").get(uriOfResource); + final Response findOneResponse = RestAssured.given() + .header("Accept", "application/json") + .get(uriOfResource); final String etagValue = findOneResponse.getHeader(HttpHeaders.ETAG); // existingResource.setName(randomAlphabetic(6)); // getApi().update(existingResource.setName("randomString")); // When - final Response secondFindOneResponse = givenAuth().header("Accept", "application/json").headers("If-None-Match", etagValue).get(uriOfResource); + final Response secondFindOneResponse = RestAssured.given() + .header("Accept", "application/json") + .headers("If-None-Match", etagValue) + .get(uriOfResource); // Then assertTrue(secondFindOneResponse.getStatusCode() == 200); @@ -79,7 +92,10 @@ public abstract class AbstractBasicLiveTest extends Abst final String uriOfResource = createAsUri(); // When - final Response findOneResponse = givenAuth().header("Accept", "application/json").headers("If-Match", randomAlphabetic(8)).get(uriOfResource); + final Response findOneResponse = RestAssured.given() + .header("Accept", "application/json") + .headers("If-Match", randomAlphabetic(8)) + .get(uriOfResource); // Then assertTrue(findOneResponse.getStatusCode() == 412); @@ -93,7 +109,7 @@ public abstract class AbstractBasicLiveTest extends Abst @Test public void whenResourcesAreRetrievedPaged_then200IsReceived() { - final Response response = givenAuth().get(getURL() + "?page=0&size=10"); + final Response response = RestAssured.get(getURL() + "?page=0&size=10"); assertThat(response.getStatusCode(), is(200)); } @@ -101,7 +117,7 @@ public abstract class AbstractBasicLiveTest extends Abst @Test public void whenPageOfResourcesAreRetrievedOutOfBounds_then404IsReceived() { final String url = getURL() + "?page=" + randomNumeric(5) + "&size=10"; - final Response response = givenAuth().get(url); + final Response response = RestAssured.get(url); assertThat(response.getStatusCode(), is(404)); } @@ -110,14 +126,14 @@ public abstract class AbstractBasicLiveTest extends Abst public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() { create(); - final Response response = givenAuth().get(getURL() + "?page=0&size=10"); + final Response response = RestAssured.get(getURL() + "?page=0&size=10"); assertFalse(response.body().as(List.class).isEmpty()); } @Test public void whenFirstPageOfResourcesAreRetrieved_thenSecondPageIsNext() { - final Response response = givenAuth().get(getURL() + "?page=0&size=2"); + final Response response = RestAssured.get(getURL() + "?page=0&size=2"); final String uriToNextPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "next"); assertEquals(getURL() + "?page=1&size=2", uriToNextPage); @@ -125,7 +141,7 @@ public abstract class AbstractBasicLiveTest extends Abst @Test public void whenFirstPageOfResourcesAreRetrieved_thenNoPreviousPage() { - final Response response = givenAuth().get(getURL() + "?page=0&size=2"); + final Response response = RestAssured.get(getURL() + "?page=0&size=2"); final String uriToPrevPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "prev"); assertNull(uriToPrevPage); @@ -136,7 +152,7 @@ public abstract class AbstractBasicLiveTest extends Abst create(); create(); - final Response response = givenAuth().get(getURL() + "?page=1&size=2"); + final Response response = RestAssured.get(getURL() + "?page=1&size=2"); final String uriToPrevPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "prev"); assertEquals(getURL() + "?page=0&size=2", uriToPrevPage); @@ -144,10 +160,10 @@ public abstract class AbstractBasicLiveTest extends Abst @Test public void whenLastPageOfResourcesIsRetrieved_thenNoNextPageIsDiscoverable() { - final Response first = givenAuth().get(getURL() + "?page=0&size=2"); + final Response first = RestAssured.get(getURL() + "?page=0&size=2"); final String uriToLastPage = extractURIByRel(first.getHeader(HttpHeaders.LINK), "last"); - final Response response = givenAuth().get(uriToLastPage); + final Response response = RestAssured.get(uriToLastPage); final String uriToNextPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "next"); assertNull(uriToNextPage); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java similarity index 76% rename from spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java rename to spring-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java index e7456f1667..c2dd3d84c7 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java @@ -5,6 +5,8 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; +import io.restassured.RestAssured; +import io.restassured.response.Response; import java.io.Serializable; @@ -15,7 +17,6 @@ import org.junit.Test; import org.springframework.http.MediaType; import com.google.common.net.HttpHeaders; -import io.restassured.response.Response; public abstract class AbstractDiscoverabilityLiveTest extends AbstractLiveTest { @@ -33,7 +34,7 @@ public abstract class AbstractDiscoverabilityLiveTest ex final String uriOfExistingResource = createAsUri(); // When - final Response res = givenAuth().post(uriOfExistingResource); + final Response res = RestAssured.post(uriOfExistingResource); // Then final String allowHeader = res.getHeader(HttpHeaders.ALLOW); @@ -44,11 +45,16 @@ public abstract class AbstractDiscoverabilityLiveTest ex public void whenResourceIsCreated_thenUriOfTheNewlyCreatedResourceIsDiscoverable() { // When final Foo newResource = new Foo(randomAlphabetic(6)); - final Response createResp = givenAuth().contentType(MediaType.APPLICATION_JSON_VALUE).body(newResource).post(getURL()); + final Response createResp = RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(newResource) + .post(getURL()); final String uriOfNewResource = createResp.getHeader(HttpHeaders.LOCATION); // Then - final Response response = givenAuth().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).get(uriOfNewResource); + final Response response = RestAssured.given() + .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) + .get(uriOfNewResource); final Foo resourceFromServer = response.body().as(Foo.class); assertThat(newResource, equalTo(resourceFromServer)); @@ -60,13 +66,13 @@ public abstract class AbstractDiscoverabilityLiveTest ex final String uriOfExistingResource = createAsUri(); // When - final Response getResponse = givenAuth().get(uriOfExistingResource); + final Response getResponse = RestAssured.get(uriOfExistingResource); // Then final String uriToAllResources = HTTPLinkHeaderUtil.extractURIByRel(getResponse.getHeader("Link"), "collection"); - final Response getAllResponse = givenAuth().get(uriToAllResources); - assertThat(getAllResponse.getStatusCode(), is(403)); + final Response getAllResponse = RestAssured.get(uriToAllResources); + assertThat(getAllResponse.getStatusCode(), is(200)); } // template method diff --git a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java similarity index 79% rename from spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java rename to spring-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java index 72dbcedc64..5aa0f5a768 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java @@ -1,6 +1,8 @@ package org.baeldung.common.web; import static org.baeldung.Consts.APPLICATION_PORT; +import io.restassured.RestAssured; +import io.restassured.response.Response; import java.io.Serializable; @@ -9,9 +11,6 @@ import org.springframework.beans.factory.annotation.Autowired; import com.google.common.base.Preconditions; import com.google.common.net.HttpHeaders; -import io.restassured.RestAssured; -import io.restassured.response.Response; -import io.restassured.specification.RequestSpecification; public abstract class AbstractLiveTest { @@ -48,20 +47,18 @@ public abstract class AbstractLiveTest { final Response createAsResponse(final T resource) { Preconditions.checkNotNull(resource); - final RequestSpecification givenAuthenticated = givenAuth(); final String resourceAsString = marshaller.encode(resource); - return givenAuthenticated.contentType(marshaller.getMime()).body(resourceAsString).post(getURL()); + return RestAssured.given() + .contentType(marshaller.getMime()) + .body(resourceAsString) + .post(getURL()); } // protected String getURL() { - return "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/auth/foos"; - } - - protected final RequestSpecification givenAuth() { - return RestAssured.given().auth().preemptive().basic("user1", "user1Pass"); + return "http://localhost:" + APPLICATION_PORT + "/spring-rest-full/auth/foos"; } } diff --git a/spring-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java b/spring-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java new file mode 100644 index 0000000000..fb0fd00bb5 --- /dev/null +++ b/spring-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java @@ -0,0 +1,16 @@ +package org.baeldung.persistence; + +import org.baeldung.persistence.service.FooServicePersistenceIntegrationTest; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ + // @formatter:off + + FooServicePersistenceIntegrationTest.class + +}) // +public class PersistenceTestSuite { + +} diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java b/spring-rest-full/src/test/java/org/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java rename to spring-rest-full/src/test/java/org/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/spring-rest-full/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java rename to spring-rest-full/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java b/spring-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java rename to spring-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/test/IMarshaller.java b/spring-rest-full/src/test/java/org/baeldung/test/IMarshaller.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/test/IMarshaller.java rename to spring-rest-full/src/test/java/org/baeldung/test/IMarshaller.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java b/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java rename to spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/test/TestMarshallerFactory.java b/spring-rest-full/src/test/java/org/baeldung/test/TestMarshallerFactory.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/test/TestMarshallerFactory.java rename to spring-rest-full/src/test/java/org/baeldung/test/TestMarshallerFactory.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/test/XStreamMarshaller.java b/spring-rest-full/src/test/java/org/baeldung/test/XStreamMarshaller.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/test/XStreamMarshaller.java rename to spring-rest-full/src/test/java/org/baeldung/test/XStreamMarshaller.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java b/spring-rest-full/src/test/java/org/baeldung/util/IDUtil.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java rename to spring-rest-full/src/test/java/org/baeldung/util/IDUtil.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java rename to spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java rename to spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java similarity index 88% rename from spring-security-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java rename to spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java index f43ca34bba..62a8983356 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java @@ -1,29 +1,26 @@ package org.baeldung.web; -import static org.baeldung.Consts.APPLICATION_PORT; -import static org.hamcrest.Matchers.is; - import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; +import static org.baeldung.Consts.APPLICATION_PORT; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import io.restassured.RestAssured; +import io.restassured.response.Response; import java.util.List; import org.baeldung.common.web.AbstractBasicLiveTest; import org.baeldung.persistence.model.Foo; +import org.baeldung.spring.ConfigTest; +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.baeldung.spring.ConfigTest; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import org.junit.runner.RunWith; -import org.junit.Test; -import io.restassured.response.Response; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") @@ -45,32 +42,35 @@ public class FooPageableLiveTest extends AbstractBasicLiveTest { return createAsUri(new Foo(randomAlphabetic(6))); } + @Override @Test public void whenResourcesAreRetrievedPaged_then200IsReceived() { - final Response response = givenAuth().get(getPageableURL() + "?page=0&size=10"); + final Response response = RestAssured.get(getPageableURL() + "?page=0&size=10"); assertThat(response.getStatusCode(), is(200)); } + @Override @Test public void whenPageOfResourcesAreRetrievedOutOfBounds_then404IsReceived() { final String url = getPageableURL() + "?page=" + randomNumeric(5) + "&size=10"; - final Response response = givenAuth().get(url); + final Response response = RestAssured.get(url); assertThat(response.getStatusCode(), is(404)); } + @Override @Test public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() { create(); - final Response response = givenAuth().get(getPageableURL() + "?page=0&size=10"); + final Response response = RestAssured.get(getPageableURL() + "?page=0&size=10"); assertFalse(response.body().as(List.class).isEmpty()); } protected String getPageableURL() { - return "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/auth/foos/pageable"; + return "http://localhost:" + APPLICATION_PORT + "/spring-rest-full/auth/foos/pageable"; } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/LiveTestSuite.java b/spring-rest-full/src/test/java/org/baeldung/web/LiveTestSuite.java similarity index 60% rename from spring-security-rest-full/src/test/java/org/baeldung/web/LiveTestSuite.java rename to spring-rest-full/src/test/java/org/baeldung/web/LiveTestSuite.java index 5d3d7fc518..6d5b94a686 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/LiveTestSuite.java +++ b/spring-rest-full/src/test/java/org/baeldung/web/LiveTestSuite.java @@ -1,17 +1,14 @@ package org.baeldung.web; -import org.baeldung.persistence.query.JPASpecificationLiveTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ // @formatter:off - JPASpecificationLiveTest.class - ,FooDiscoverabilityLiveTest.class + FooDiscoverabilityLiveTest.class ,FooLiveTest.class ,FooPageableLiveTest.class - ,MyUserLiveTest.class }) // public class LiveTestSuite { diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java b/spring-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java rename to spring-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java diff --git a/spring-security-rest-full/src/test/resources/.gitignore b/spring-rest-full/src/test/resources/.gitignore similarity index 100% rename from spring-security-rest-full/src/test/resources/.gitignore rename to spring-rest-full/src/test/resources/.gitignore diff --git a/spring-rest-query-language/.gitignore b/spring-rest-query-language/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-rest-query-language/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-rest-query-language/README.md b/spring-rest-query-language/README.md new file mode 100644 index 0000000000..7677f96379 --- /dev/null +++ b/spring-rest-query-language/README.md @@ -0,0 +1,35 @@ +========= + +## REST Example Project Query Language + +### Courses +The "REST With Spring" Classes: http://bit.ly/restwithspring + +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com + +### Relevant Articles: + +- [REST Query Language with Spring and JPA Criteria](http://www.baeldung.com/rest-search-language-spring-jpa-criteria) +- [REST Query Language with Spring Data JPA Specifications](http://www.baeldung.com/rest-api-search-language-spring-data-specifications) +- [REST Query Language with Spring Data JPA and QueryDSL](http://www.baeldung.com/rest-api-search-language-spring-data-querydsl) +- [REST Query Language – Advanced Search Operations](http://www.baeldung.com/rest-api-query-search-language-more-operations) +- [REST Query Language with RSQL](http://www.baeldung.com/rest-api-search-language-rsql-fiql) +- [REST Query Language – Implementing OR Operation](http://www.baeldung.com/rest-api-query-search-or-operation) + + + + +### Build the Project +``` +mvn clean install +``` + + +### Set up MySQL +``` +mysql -u root -p +> CREATE USER 'tutorialuser'@'localhost' IDENTIFIED BY 'tutorialmy5ql'; +> GRANT ALL PRIVILEGES ON *.* TO 'tutorialuser'@'localhost'; +> FLUSH PRIVILEGES; +``` + diff --git a/spring-security-rest-full/pom.xml b/spring-rest-query-language/pom.xml similarity index 98% rename from spring-security-rest-full/pom.xml rename to spring-rest-query-language/pom.xml index 12a611431e..bf3eb8cb78 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -2,10 +2,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - spring-security-rest-full + spring-rest-query-language 0.1-SNAPSHOT - spring-security-rest-full + spring-rest-query-language war @@ -230,7 +230,7 @@ - spring-security-rest-full + spring-rest-query-language src/main/resources diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/GenericSpecificationsBuilder.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/GenericSpecificationsBuilder.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/GenericSpecificationsBuilder.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/GenericSpecificationsBuilder.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/IUserDAO.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/IUserDAO.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/IUserDAO.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/IUserDAO.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/UserDAO.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserDAO.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/UserDAO.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserDAO.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserRepository.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/UserRepository.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserRepository.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/UserSpecification.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserSpecification.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/UserSpecification.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserSpecification.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/UserSpecificationsBuilder.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserSpecificationsBuilder.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/UserSpecificationsBuilder.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserSpecificationsBuilder.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/RsqlSearchOperation.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/RsqlSearchOperation.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/RsqlSearchOperation.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/RsqlSearchOperation.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/MyUser.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/model/MyUser.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/model/MyUser.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/model/MyUser.java diff --git a/spring-rest-query-language/src/main/java/org/baeldung/persistence/model/User.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/model/User.java new file mode 100644 index 0000000000..670d4a2e74 --- /dev/null +++ b/spring-rest-query-language/src/main/java/org/baeldung/persistence/model/User.java @@ -0,0 +1,94 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String firstName; + + private String lastName; + + private String email; + + private int age; + + public User() { + super(); + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(final String username) { + email = username; + } + + public int getAge() { + return age; + } + + public void setAge(final int age) { + this.age = age; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((email == null) ? 0 : email.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final User user = (User) obj; + return email.equals(user.email); + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); + return builder.toString(); + } + +} \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User_.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/model/User_.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User_.java rename to spring-rest-query-language/src/main/java/org/baeldung/persistence/model/User_.java diff --git a/spring-rest-query-language/src/main/java/org/baeldung/spring/Application.java b/spring-rest-query-language/src/main/java/org/baeldung/spring/Application.java new file mode 100644 index 0000000000..7aa9ea5bc3 --- /dev/null +++ b/spring-rest-query-language/src/main/java/org/baeldung/spring/Application.java @@ -0,0 +1,40 @@ +package org.baeldung.spring; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.context.request.RequestContextListener; + +/** + * Main Application Class - uses Spring Boot. Just run this as a normal Java + * class to run up a Jetty Server (on http://localhost:8082/spring-rest-query-language) + * + */ +@EnableScheduling +@EnableAutoConfiguration +@ComponentScan("org.baeldung") +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + @Override + public void onStartup(ServletContext sc) throws ServletException { + // Manages the lifecycle of the root application context + sc.addListener(new RequestContextListener()); + } + + public static void main(final String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/spring-rest-query-language/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-rest-query-language/src/main/java/org/baeldung/spring/PersistenceConfig.java new file mode 100644 index 0000000000..f3a87b189e --- /dev/null +++ b/spring-rest-query-language/src/main/java/org/baeldung/spring/PersistenceConfig.java @@ -0,0 +1,85 @@ +package org.baeldung.spring; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +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.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) +@ComponentScan({ "org.baeldung.persistence" }) +// @ImportResource("classpath*:springDataPersistenceConfig.xml") +@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") +public class PersistenceConfig { + + @Autowired + private Environment env; + + public PersistenceConfig() { + super(); + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + // vendorAdapter.set + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); + + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + +} \ No newline at end of file diff --git a/spring-rest-query-language/src/main/java/org/baeldung/spring/WebConfig.java b/spring-rest-query-language/src/main/java/org/baeldung/spring/WebConfig.java new file mode 100644 index 0000000000..41711ee1ad --- /dev/null +++ b/spring-rest-query-language/src/main/java/org/baeldung/spring/WebConfig.java @@ -0,0 +1,36 @@ +package org.baeldung.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +@ComponentScan("org.baeldung.web") +@EnableWebMvc +public class WebConfig extends WebMvcConfigurerAdapter { + + public WebConfig() { + super(); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setPrefix("/WEB-INF/view/"); + viewResolver.setSuffix(".jsp"); + return viewResolver; + } + + // API + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/homepage.html"); + } + +} \ No newline at end of file diff --git a/spring-rest-query-language/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-rest-query-language/src/main/java/org/baeldung/web/controller/HomeController.java new file mode 100644 index 0000000000..9c4d14cae3 --- /dev/null +++ b/spring-rest-query-language/src/main/java/org/baeldung/web/controller/HomeController.java @@ -0,0 +1,14 @@ +package org.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping(value = "/") +public class HomeController { + + public String index() { + return "homepage"; + } + +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java b/spring-rest-query-language/src/main/java/org/baeldung/web/controller/UserController.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java rename to spring-rest-query-language/src/main/java/org/baeldung/web/controller/UserController.java diff --git a/spring-rest-query-language/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java b/spring-rest-query-language/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java new file mode 100644 index 0000000000..b593116c4a --- /dev/null +++ b/spring-rest-query-language/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java @@ -0,0 +1,84 @@ +package org.baeldung.web.error; + +import javax.persistence.EntityNotFoundException; + +import org.baeldung.web.exception.MyResourceNotFoundException; +import org.hibernate.exception.ConstraintViolationException; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +@ControllerAdvice +public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { + + public RestResponseEntityExceptionHandler() { + super(); + } + + // API + + // 400 + + @ExceptionHandler({ ConstraintViolationException.class }) + public ResponseEntity handleBadRequest(final ConstraintViolationException ex, final WebRequest request) { + final String bodyOfResponse = "This should be application specific"; + return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request); + } + + @ExceptionHandler({ DataIntegrityViolationException.class }) + public ResponseEntity handleBadRequest(final DataIntegrityViolationException ex, final WebRequest request) { + final String bodyOfResponse = "This should be application specific"; + return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request); + } + + @Override + protected ResponseEntity handleHttpMessageNotReadable(final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { + final String bodyOfResponse = "This should be application specific"; + // ex.getCause() instanceof JsonMappingException, JsonParseException // for additional information later on + return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request); + } + + @Override + protected ResponseEntity handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { + final String bodyOfResponse = "This should be application specific"; + return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request); + } + + + // 404 + + @ExceptionHandler(value = { EntityNotFoundException.class, MyResourceNotFoundException.class }) + protected ResponseEntity handleNotFound(final RuntimeException ex, final WebRequest request) { + final String bodyOfResponse = "This should be application specific"; + return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request); + } + + // 409 + + @ExceptionHandler({ InvalidDataAccessApiUsageException.class, DataAccessException.class }) + protected ResponseEntity handleConflict(final RuntimeException ex, final WebRequest request) { + final String bodyOfResponse = "This should be application specific"; + return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, request); + } + + // 412 + + // 500 + + @ExceptionHandler({ NullPointerException.class, IllegalArgumentException.class, IllegalStateException.class }) + /*500*/public ResponseEntity handleInternal(final RuntimeException ex, final WebRequest request) { + logger.error("500 Status Code", ex); + final String bodyOfResponse = "This should be application specific"; + return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request); + } + +} diff --git a/spring-rest-query-language/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-query-language/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java new file mode 100644 index 0000000000..14b61f9832 --- /dev/null +++ b/spring-rest-query-language/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java @@ -0,0 +1,21 @@ +package org.baeldung.web.exception; + +public final class MyResourceNotFoundException extends RuntimeException { + + public MyResourceNotFoundException() { + super(); + } + + public MyResourceNotFoundException(final String message, final Throwable cause) { + super(message, cause); + } + + public MyResourceNotFoundException(final String message) { + super(message); + } + + public MyResourceNotFoundException(final Throwable cause) { + super(cause); + } + +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/util/CriteriaParser.java b/spring-rest-query-language/src/main/java/org/baeldung/web/util/CriteriaParser.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/util/CriteriaParser.java rename to spring-rest-query-language/src/main/java/org/baeldung/web/util/CriteriaParser.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/util/SearchCriteria.java b/spring-rest-query-language/src/main/java/org/baeldung/web/util/SearchCriteria.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/util/SearchCriteria.java rename to spring-rest-query-language/src/main/java/org/baeldung/web/util/SearchCriteria.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/util/SearchOperation.java b/spring-rest-query-language/src/main/java/org/baeldung/web/util/SearchOperation.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/util/SearchOperation.java rename to spring-rest-query-language/src/main/java/org/baeldung/web/util/SearchOperation.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/util/SpecSearchCriteria.java b/spring-rest-query-language/src/main/java/org/baeldung/web/util/SpecSearchCriteria.java similarity index 100% rename from spring-security-rest-full/src/main/java/org/baeldung/web/util/SpecSearchCriteria.java rename to spring-rest-query-language/src/main/java/org/baeldung/web/util/SpecSearchCriteria.java diff --git a/spring-rest-query-language/src/main/resources/application.properties b/spring-rest-query-language/src/main/resources/application.properties new file mode 100644 index 0000000000..01eaee7040 --- /dev/null +++ b/spring-rest-query-language/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port=8082 +server.context-path=/spring-rest-query-language \ No newline at end of file diff --git a/spring-security-rest-full/src/main/resources/data.sql b/spring-rest-query-language/src/main/resources/data.sql similarity index 100% rename from spring-security-rest-full/src/main/resources/data.sql rename to spring-rest-query-language/src/main/resources/data.sql diff --git a/spring-rest-query-language/src/main/resources/logback.xml b/spring-rest-query-language/src/main/resources/logback.xml new file mode 100644 index 0000000000..ec0dc2469a --- /dev/null +++ b/spring-rest-query-language/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-rest-query-language/src/main/resources/persistence-h2.properties b/spring-rest-query-language/src/main/resources/persistence-h2.properties new file mode 100644 index 0000000000..839a466533 --- /dev/null +++ b/spring-rest-query-language/src/main/resources/persistence-h2.properties @@ -0,0 +1,22 @@ +## jdbc.X +#jdbc.driverClassName=com.mysql.jdbc.Driver +#jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true +#jdbc.user=tutorialuser +#jdbc.pass=tutorialmy5ql +# +## hibernate.X +#hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +#hibernate.show_sql=false +#hibernate.hbm2ddl.auto=create-drop + + +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +jdbc.user=sa +jdbc.pass= + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop diff --git a/spring-rest-query-language/src/main/resources/persistence-mysql.properties b/spring-rest-query-language/src/main/resources/persistence-mysql.properties new file mode 100644 index 0000000000..8263b0d9ac --- /dev/null +++ b/spring-rest-query-language/src/main/resources/persistence-mysql.properties @@ -0,0 +1,10 @@ +# jdbc.X +jdbc.driverClassName=com.mysql.jdbc.Driver +jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true +jdbc.user=tutorialuser +jdbc.pass=tutorialmy5ql + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop diff --git a/spring-rest-query-language/src/main/resources/springDataPersistenceConfig.xml b/spring-rest-query-language/src/main/resources/springDataPersistenceConfig.xml new file mode 100644 index 0000000000..d6d0ec6e47 --- /dev/null +++ b/spring-rest-query-language/src/main/resources/springDataPersistenceConfig.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/spring-rest-query-language/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest-query-language/src/main/webapp/WEB-INF/api-servlet.xml new file mode 100644 index 0000000000..4ba9642448 --- /dev/null +++ b/spring-rest-query-language/src/main/webapp/WEB-INF/api-servlet.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/spring-rest-query-language/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-rest-query-language/src/main/webapp/WEB-INF/view/homepage.jsp new file mode 100644 index 0000000000..7cc14b5dcd --- /dev/null +++ b/spring-rest-query-language/src/main/webapp/WEB-INF/view/homepage.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample view

+ + \ No newline at end of file diff --git a/spring-rest-query-language/src/main/webapp/WEB-INF/web.xml b/spring-rest-query-language/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..4472afd112 --- /dev/null +++ b/spring-rest-query-language/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,42 @@ + + + + Spring REST Query language Application + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + org.baeldung.spring + + + + org.springframework.web.context.ContextLoaderListener + + + + + api + org.springframework.web.servlet.DispatcherServlet + 1 + + + api + / + + + + + index.html + + + \ No newline at end of file diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java b/spring-rest-query-language/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java rename to spring-rest-query-language/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslIntegrationTest.java b/spring-rest-query-language/src/test/java/org/baeldung/persistence/query/JPAQuerydslIntegrationTest.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslIntegrationTest.java rename to spring-rest-query-language/src/test/java/org/baeldung/persistence/query/JPAQuerydslIntegrationTest.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationIntegrationTest.java b/spring-rest-query-language/src/test/java/org/baeldung/persistence/query/JPASpecificationIntegrationTest.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationIntegrationTest.java rename to spring-rest-query-language/src/test/java/org/baeldung/persistence/query/JPASpecificationIntegrationTest.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java b/spring-rest-query-language/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java similarity index 78% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java rename to spring-rest-query-language/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java index 07b47dd8b6..044029c679 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java +++ b/spring-rest-query-language/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java @@ -1,16 +1,15 @@ package org.baeldung.persistence.query; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import io.restassured.RestAssured; import io.restassured.response.Response; -import io.restassured.specification.RequestSpecification; + import org.baeldung.persistence.model.User; import org.junit.Before; import org.junit.Test; import org.springframework.test.context.ActiveProfiles; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - //@RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration(classes = { ConfigTest.class, // PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) @@ -24,7 +23,7 @@ public class JPASpecificationLiveTest { private User userTom; - private final String URL_PREFIX = "http://localhost:8082/spring-security-rest-full/auth/users/spec?search="; + private final String URL_PREFIX = "http://localhost:8082/spring-rest-query-language/auth/users/spec?search="; @Before public void init() { @@ -43,11 +42,11 @@ public class JPASpecificationLiveTest { // repository.save(userTom); } - private final String EURL_PREFIX = "http://localhost:8082/spring-security-rest-full/auth/users/espec?search="; + private final String EURL_PREFIX = "http://localhost:8082/spring-rest-query-language/auth/users/espec?search="; @Test public void givenFirstOrLastName_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get(EURL_PREFIX + "firstName:john,'lastName:doe"); + final Response response = RestAssured.get(EURL_PREFIX + "firstName:john,'lastName:doe"); final String result = response.body() .asString(); assertTrue(result.contains(userJohn.getEmail())); @@ -56,7 +55,7 @@ public class JPASpecificationLiveTest { @Test public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get(URL_PREFIX + "firstName:john,lastName:doe"); + final Response response = RestAssured.get(URL_PREFIX + "firstName:john,lastName:doe"); final String result = response.body() .asString(); @@ -66,7 +65,7 @@ public class JPASpecificationLiveTest { @Test public void givenFirstNameInverse_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get(URL_PREFIX + "firstName!john"); + final Response response = RestAssured.get(URL_PREFIX + "firstName!john"); final String result = response.body() .asString(); @@ -76,7 +75,7 @@ public class JPASpecificationLiveTest { @Test public void givenMinAge_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get(URL_PREFIX + "age>25"); + final Response response = RestAssured.get(URL_PREFIX + "age>25"); final String result = response.body() .asString(); @@ -86,7 +85,7 @@ public class JPASpecificationLiveTest { @Test public void givenFirstNamePrefix_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get(URL_PREFIX + "firstName:jo*"); + final Response response = RestAssured.get(URL_PREFIX + "firstName:jo*"); final String result = response.body() .asString(); @@ -96,7 +95,7 @@ public class JPASpecificationLiveTest { @Test public void givenFirstNameSuffix_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get(URL_PREFIX + "firstName:*n"); + final Response response = RestAssured.get(URL_PREFIX + "firstName:*n"); final String result = response.body() .asString(); @@ -106,7 +105,7 @@ public class JPASpecificationLiveTest { @Test public void givenFirstNameSubstring_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get(URL_PREFIX + "firstName:*oh*"); + final Response response = RestAssured.get(URL_PREFIX + "firstName:*oh*"); final String result = response.body() .asString(); @@ -116,7 +115,7 @@ public class JPASpecificationLiveTest { @Test public void givenAgeRange_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get(URL_PREFIX + "age>20,age<25"); + final Response response = RestAssured.get(URL_PREFIX + "age>20,age<25"); final String result = response.body() .asString(); @@ -124,11 +123,11 @@ public class JPASpecificationLiveTest { assertFalse(result.contains(userTom.getEmail())); } - private final String ADV_URL_PREFIX = "http://localhost:8082/spring-security-rest-full/auth/users/spec/adv?search="; + private final String ADV_URL_PREFIX = "http://localhost:8082/spring-rest-query-language/auth/users/spec/adv?search="; @Test public void givenFirstOrLastName_whenGettingAdvListOfUsers_thenCorrect() { - final Response response = givenAuth().get(ADV_URL_PREFIX + "firstName:john OR lastName:doe"); + final Response response = RestAssured.get(ADV_URL_PREFIX + "firstName:john OR lastName:doe"); final String result = response.body() .asString(); assertTrue(result.contains(userJohn.getEmail())); @@ -137,17 +136,11 @@ public class JPASpecificationLiveTest { @Test public void givenFirstOrFirstNameAndAge_whenGettingAdvListOfUsers_thenCorrect() { - final Response response = givenAuth().get(ADV_URL_PREFIX + "( firstName:john OR firstName:tom ) AND age>22"); + final Response response = RestAssured.get(ADV_URL_PREFIX + "( firstName:john OR firstName:tom ) AND age>22"); final String result = response.body() .asString(); assertFalse(result.contains(userJohn.getEmail())); assertTrue(result.contains(userTom.getEmail())); } - private final RequestSpecification givenAuth() { - return RestAssured.given() - .auth() - .preemptive() - .basic("user1", "user1Pass"); - } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java b/spring-rest-query-language/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java similarity index 100% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java rename to spring-rest-query-language/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java b/spring-rest-query-language/src/test/java/org/baeldung/web/MyUserLiveTest.java similarity index 94% rename from spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java rename to spring-rest-query-language/src/test/java/org/baeldung/web/MyUserLiveTest.java index b598463da0..a478016280 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java +++ b/spring-rest-query-language/src/test/java/org/baeldung/web/MyUserLiveTest.java @@ -1,20 +1,19 @@ package org.baeldung.web; import static org.junit.Assert.assertEquals; +import io.restassured.RestAssured; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; import org.baeldung.persistence.model.MyUser; import org.junit.Test; import org.springframework.test.context.ActiveProfiles; -import io.restassured.RestAssured; -import io.restassured.response.Response; -import io.restassured.specification.RequestSpecification; - @ActiveProfiles("test") public class MyUserLiveTest { private final MyUser userJohn = new MyUser("john", "doe", "john@doe.com", 11); - private String URL_PREFIX = "http://localhost:8082/spring-security-rest-full/auth/api/myusers"; + private String URL_PREFIX = "http://localhost:8082/spring-rest-query-language/auth/api/myusers"; @Test public void whenGettingListOfUsers_thenCorrect() { diff --git a/spring-rest-query-language/src/test/resources/.gitignore b/spring-rest-query-language/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-rest-query-language/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-rest-shell/README.md b/spring-rest-shell/README.md new file mode 100644 index 0000000000..06e18450c6 --- /dev/null +++ b/spring-rest-shell/README.md @@ -0,0 +1,5 @@ +## Spring REST Shell Project + +### Relevant Articles + +- [Spring REST Shell](http://www.baeldung.com/) \ No newline at end of file diff --git a/spring-rest-shell/pom.xml b/spring-rest-shell/pom.xml new file mode 100644 index 0000000000..fe255b397f --- /dev/null +++ b/spring-rest-shell/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + com.baeldung + spring-rest-shell + 0.0.1-SNAPSHOT + jar + + spring-rest-shell + A simple project to demonstrate Spring REST Shell features. + + + org.springframework.boot + spring-boot-starter-parent + 1.5.8.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-data-rest + + + + + com.h2database + h2 + runtime + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-rest-shell/src/main/java/com/baeldung/Application.java b/spring-rest-shell/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..37dbe7dab8 --- /dev/null +++ b/spring-rest-shell/src/main/java/com/baeldung/Application.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-rest-shell/src/main/java/com/baeldung/acticle/Article.java b/spring-rest-shell/src/main/java/com/baeldung/acticle/Article.java new file mode 100644 index 0000000000..6a55517f9f --- /dev/null +++ b/spring-rest-shell/src/main/java/com/baeldung/acticle/Article.java @@ -0,0 +1,40 @@ +package com.baeldung.acticle; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public final class Article { + + @Id + @GeneratedValue + private Long id; + private String title; + private String content; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + +} diff --git a/spring-rest-shell/src/main/java/com/baeldung/acticle/ArticleRepository.java b/spring-rest-shell/src/main/java/com/baeldung/acticle/ArticleRepository.java new file mode 100644 index 0000000000..83daf819f0 --- /dev/null +++ b/spring-rest-shell/src/main/java/com/baeldung/acticle/ArticleRepository.java @@ -0,0 +1,18 @@ +package com.baeldung.acticle; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +import java.util.Optional; + +@RepositoryRestResource( + path = "articles", + collectionResourceRel = "articles", + itemResourceRel = "article" +) +public interface ArticleRepository extends CrudRepository { + + Optional
findByTitle(@Param("title") String title); + +} diff --git a/spring-security-rest-full/.springBeans b/spring-security-rest-full/.springBeans deleted file mode 100644 index b01040d91b..0000000000 --- a/spring-security-rest-full/.springBeans +++ /dev/null @@ -1,17 +0,0 @@ - - - 1 - - - - - - - - - src/main/webapp/WEB-INF/api-servlet.xml - java:org.baeldung.spring.Application - - - - diff --git a/spring-security-rest-full/src/main/resources/application.properties b/spring-security-rest-full/src/main/resources/application.properties deleted file mode 100644 index c3e1f0b4bb..0000000000 --- a/spring-security-rest-full/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -server.port=8082 -server.context-path=/spring-security-rest-full -endpoints.metrics.enabled=true \ No newline at end of file diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java deleted file mode 100644 index fda7b01c7a..0000000000 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.persistence; - -import org.baeldung.persistence.query.JPACriteriaQueryIntegrationTest; -import org.baeldung.persistence.query.JPAQuerydslIntegrationTest; -import org.baeldung.persistence.query.JPASpecificationIntegrationTest; -import org.baeldung.persistence.query.RsqlIntegrationTest; -import org.baeldung.persistence.service.FooServicePersistenceIntegrationTest; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - // @formatter:off - RsqlIntegrationTest.class - ,JPASpecificationIntegrationTest.class - ,FooServicePersistenceIntegrationTest.class - ,JPAQuerydslIntegrationTest.class - ,JPACriteriaQueryIntegrationTest.class -}) // -public class PersistenceTestSuite { - -}