diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java b/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java new file mode 100644 index 0000000000..35d6c8b424 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java @@ -0,0 +1,21 @@ +package com.baeldung.algorithms.linesintersection; + +import java.awt.Point; +import java.util.Optional; + +public class LinesIntersectionService { + + public Optional calculateIntersectionPoint(double m1, double b1, double m2, double b2) { + + if (m1 == m2) { + return Optional.empty(); + } + + double x = (b2 - b1) / (m1 - m2); + double y = m1 * x + b1; + + Point point = new Point(); + point.setLocation(x, y); + return Optional.of(point); + } +} diff --git a/core-java/src/test/java/com/baeldung/linesintersection/LinesIntersectionServiceUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java similarity index 69% rename from core-java/src/test/java/com/baeldung/linesintersection/LinesIntersectionServiceUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java index 90c93fe050..22371107f3 100644 --- a/core-java/src/test/java/com/baeldung/linesintersection/LinesIntersectionServiceUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.linesintersection; +package com.baeldung.algorithms.linesintersection; import java.awt.Point; import java.util.Optional; @@ -14,24 +14,24 @@ public class LinesIntersectionServiceUnitTest { @Test public void givenNotParallelLines_whenCalculatePoint_thenPresent() { - float m1 = 0; - float b1 = 0; - float m2 = 1; - float b2 = -1; + double m1 = 0; + double b1 = 0; + double m2 = 1; + double b2 = -1; Optional point = service.calculateIntersectionPoint(m1, b1, m2, b2); assertTrue(point.isPresent()); - assertEquals(point.get().x, 1); - assertEquals(point.get().y, 0); + assertEquals(point.get().getX(), 1, 0.001); + assertEquals(point.get().getY(), 0, 0.001); } @Test public void givenParallelLines_whenCalculatePoint_thenEmpty() { - float m1 = 1; - float b1 = 0; - float m2 = 1; - float b2 = -1; + double m1 = 1; + double b1 = 0; + double m2 = 1; + double b2 = -1; Optional point = service.calculateIntersectionPoint(m1, b1, m2, b2); diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java index 8b5fa409c9..930e913109 100644 --- a/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java @@ -1,70 +1,91 @@ package com.baeldung.test.dependencyinjection; -import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor; -import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor; -import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor; -import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor; -import com.baeldung.dependencyinjection.loggers.TimeLogger; -import java.text.SimpleDateFormat; -import java.util.Calendar; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; + +import java.text.ParseException; +import java.time.LocalTime; +import java.time.temporal.ChronoUnit; + import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.junit.BeforeClass; import org.junit.Test; +import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor; +import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor; +import com.baeldung.dependencyinjection.loggers.TimeLogger; + public class ImageProcessorUnitTest { - + private static ImageFileProcessor imageFileProcessor; - private static SimpleDateFormat dateFormat; - private static Calendar calendar; - - + @BeforeClass public static void setImageProcessorInstance() { Weld weld = new Weld(); WeldContainer container = weld.initialize(); - imageFileProcessor = container.select(ImageFileProcessor.class).get(); + imageFileProcessor = container.select(ImageFileProcessor.class) + .get(); container.shutdown(); } - - @BeforeClass - public static void setSimpleDateFormatInstance() { - dateFormat = new SimpleDateFormat("HH:mm"); - } - - @BeforeClass - public static void setCalendarInstance() { - calendar = Calendar.getInstance(); - } - + @Test public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() { assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class); assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class); } - + @Test - public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() { - String currentTime = dateFormat.format(calendar.getTime()); - assertThat(imageFileProcessor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png at: " + currentTime); + public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String openFileLog = imageFileProcessor.openFile("file1.png"); + assertThat(openFileLog).contains("Opening PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(openFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); } - + @Test - public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() { - String currentTime = dateFormat.format(calendar.getTime()); - assertThat(imageFileProcessor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png at: " + currentTime); + public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String editFileLog = imageFileProcessor.editFile("file1.png"); + assertThat(editFileLog).contains("Editing PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(editFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); } - + @Test - public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() { - String currentTime = dateFormat.format(calendar.getTime()); - assertThat(imageFileProcessor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png at: " + currentTime); + public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String writeFileLog = imageFileProcessor.writeFile("file1.png"); + assertThat(writeFileLog).contains("Writing PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(writeFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); } - + @Test - public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() { - String currentTime = dateFormat.format(calendar.getTime()); - assertThat(imageFileProcessor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png at: " + currentTime); + public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String saveFileLog = imageFileProcessor.saveFile("file1.png"); + assertThat(saveFileLog).contains("Saving PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(saveFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); + } + + private LocalTime getLoggedTime(String log) throws ParseException { + String logTimeString = log.split("at: ")[1]; + + int hour = Integer.valueOf(logTimeString.split(":")[0]); + int minutes = Integer.valueOf(logTimeString.split(":")[1]); + + LocalTime loggedTime = LocalTime.of(hour, minutes); + return loggedTime; } } \ No newline at end of file diff --git a/core-java-8/README.md b/core-java-8/README.md index 4d463482fb..e23a2a6d1e 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -15,24 +15,17 @@ - [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing) - [Guide To Java 8 Optional](http://www.baeldung.com/java-optional) - [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java) -- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) - [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode) - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) -- [Copy a File with Java](http://www.baeldung.com/java-copy-file) - [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods) - [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency) -- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) -- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection) - [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator) - [Java 8 Math New Methods](http://www.baeldung.com/java-8-math) - [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations) - [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max) - [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization) -- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) - [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get) -- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table) - [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) - [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic) - [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference) -- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) - [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time) diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java index 4df3482633..df6c72d346 100644 --- a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java @@ -5,25 +5,22 @@ */ package com.baeldung.nullsafecollectionstreams; +import static org.junit.Assert.assertEquals; + import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.stream.Stream; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; + import org.junit.Test; -import static org.junit.Assert.*; /** * * @author Kwaje Anthony */ public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { - - private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = - new NullSafeCollectionStreamsUsingJava8OptionalContainer(); + + private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = new NullSafeCollectionStreamsUsingJava8OptionalContainer(); @Test public void whenCollectionIsNull_thenExpectAnEmptyStream() { @@ -49,5 +46,5 @@ public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { assertEquals(iter1.next(), iter2.next()); assert !iter1.hasNext() && !iter2.hasNext(); } - + } diff --git a/core-java-8/src/test/java/com/baeldung/streamordering/BenchmarkUnitTest.java b/core-java-8/src/test/java/com/baeldung/streamordering/BenchmarkUnitTest.java deleted file mode 100644 index 9ae0a16514..0000000000 --- a/core-java-8/src/test/java/com/baeldung/streamordering/BenchmarkUnitTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.baeldung.streamordering; - -import org.junit.Test; -import org.openjdk.jmh.annotations.*; -import org.openjdk.jmh.infra.Blackhole; -import org.openjdk.jmh.runner.Runner; -import org.openjdk.jmh.runner.options.Options; -import org.openjdk.jmh.runner.options.OptionsBuilder; -import org.openjdk.jmh.runner.options.TimeValue; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import java.util.stream.IntStream; - - -public class BenchmarkUnitTest -{ - - @Test - public void - launchBenchmark() throws Exception { - - Options opt = new OptionsBuilder() - // Specify which benchmarks to run. - // You can be more specific if you'd like to run only one benchmark per test. - .include(this.getClass().getName() + ".*") - // Set the following options as needed - .mode (Mode.AverageTime) - .timeUnit(TimeUnit.MICROSECONDS) - .warmupTime(TimeValue.seconds(1)) - .warmupIterations(2) - .measurementTime(TimeValue.seconds(1)) - .measurementIterations(2) - .threads(2) - .forks(1) - .shouldFailOnError(true) - .shouldDoGC(true) - //.jvmArgs("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining") - //.addProfiler(WinPerfAsmProfiler.class) - .build(); - - new Runner(opt).run(); - - - } - - @Benchmark - public void givenOrderedStreamInput_whenStreamFiltered_showOpsPerMS(){ - IntStream.range(1, 100_000_000).parallel().filter(i -> i % 10 == 0).toArray(); - } - - @Benchmark - public void givenUnorderedStreamInput_whenStreamFiltered_showOpsPerMS(){ - IntStream.range(1,100_000_000).unordered().parallel().filter(i -> i % 10 == 0).toArray(); - } - - @Benchmark - public void givenUnorderedStreamInput_whenStreamDistinct_showOpsPerMS(){ - IntStream.range(1, 1_000_000).unordered().parallel().distinct().toArray(); - } - - @Benchmark - public void givenOrderedStreamInput_whenStreamDistinct_showOpsPerMS() { - //section 5.1. - IntStream.range(1, 1_000_000).parallel().distinct().toArray(); - } - - - // The JMH samples are the best documentation for how to use it - // http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/ - @State(Scope.Thread) - public static class BenchmarkState - { - List list; - - @Setup(Level.Trial) public void - initialize() { - - Random rand = new Random(); - - list = new ArrayList<>(); - for (int i = 0; i < 1000; i++) - list.add (rand.nextInt()); - } - } - - @Benchmark public void - benchmark1 (BenchmarkState state, Blackhole bh) { - - List list = state.list; - - for (int i = 0; i < 1000; i++) - bh.consume (list.get (i)); - } -} diff --git a/core-java-8/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java b/core-java-8/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java deleted file mode 100644 index 43a233d353..0000000000 --- a/core-java-8/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.baeldung.streamordering; - -import org.junit.Before; -import org.junit.Test; - -import java.util.*; -import java.util.function.Function; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static org.junit.Assert.assertEquals; - -public class StreamsOrderingUnitTest { - - Logger logger = Logger.getLogger( StreamsOrderingUnitTest.class.getName()); - - @Before - public void setUp() throws Exception { - logger.setLevel(Level.ALL); - } - - @Test - public void givenTwoCollections_whenStreamed_thenCheckOutputDifferent(){ - - List list = Arrays.asList("B", "A", "C", "D", "F"); - Set set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F")); - - Object[] listOutput = list.stream().toArray(); - Object[] setOutput = set.stream().toArray(); - - assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput)); - assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput)); - - } - - @Test - public void givenTwoCollections_whenStreamedInParallel_thenCheckOutputDifferent(){ - - List list = Arrays.asList("B", "A", "C", "D", "F"); - Set set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F")); - - Object[] listOutput = list.stream().parallel().toArray(); - Object[] setOutput = set.stream().parallel().toArray(); - - assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput)); - assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput)); - - } - - - - @Test - public void givenOrderedInput_whenUnorderedAndOrderedCompared_thenCheckUnorderedOutputChanges(){ - Set set = new TreeSet<>( - Arrays.asList(-9, -5, -4, -2, 1, 2, 4, 5, 7, 9, 12, 13, 16, 29, 23, 34, 57, 68, 90, 102, 230)); - - Object[] orderedArray = set.stream() - .parallel() - .limit(5) - .toArray(); - Object[] unorderedArray = set.stream() - .unordered() - .parallel() - .limit(5) - .toArray(); - - logger.info(Arrays.toString(orderedArray)); - logger.info(Arrays.toString(unorderedArray)); - } - - - @Test - public void givenUnsortedStreamInput_whenStreamSorted_thenCheckOrderChanged(){ - - List list = Arrays.asList(-3,10,-4,1,3); - - Object[] listOutput = list.stream().toArray(); - Object[] listOutputSorted = list.stream().sorted().toArray(); - - assertEquals("[-3, 10, -4, 1, 3]", Arrays.toString(listOutput)); - assertEquals("[-4, -3, 1, 3, 10]", Arrays.toString(listOutputSorted)); - - } - - @Test - public void givenUnsortedStreamInput_whenStreamDistinct_thenShowTimeTaken(){ - long start, end; - start = System.currentTimeMillis(); - IntStream.range(1,1_000_000).unordered().parallel().distinct().toArray(); - end = System.currentTimeMillis(); - System.out.println(String.format("Time taken when unordered: %d ms", (end - start))); - } - - - @Test - public void givenSameCollection_whenStreamTerminated_thenCheckEachVsEachOrdered(){ - - List list = Arrays.asList("B", "A", "C", "D", "F"); - - list.stream().parallel().forEach(e -> logger.log(Level.INFO, e)); - list.stream().parallel().forEachOrdered(e -> logger.log(Level.INFO, e)); - - } - - @Test - public void givenSameCollection_whenStreamCollected_thenCheckOutput(){ - - List list = Arrays.asList("B", "A", "C", "D", "F"); - - List collectionList = list.stream().parallel().collect(Collectors.toList()); - Set collectionSet = list.stream().parallel().collect(Collectors.toCollection(TreeSet::new)); - - assertEquals("[B, A, C, D, F]", collectionList.toString()); - assertEquals("[A, B, C, D, F]", collectionSet.toString()); - - } - - - @Test - public void givenListIterationOrder_whenStreamCollectedToMap_thenCeckOrderChanged() { - List list = Arrays.asList("A", "BB", "CCC"); - - Map hashMap = list.stream().collect(Collectors.toMap(Function.identity(), String::length)); - - Object[] keySet = hashMap.keySet().toArray(); - - assertEquals("[BB, A, CCC]", Arrays.toString(keySet)); - - } - - @Test - public void givenListIteration_whenStreamCollectedtoHashMap_thenCheckOrderMaintained() { - List list = Arrays.asList("A", "BB", "CCC", "CCC"); - - Map linkedHashMap = list.stream().collect(Collectors.toMap( - Function.identity(), - String::length, - (u, v) -> u, - LinkedHashMap::new - )); - - Object[] keySet = linkedHashMap.keySet().toArray(); - - assertEquals("[A, BB, CCC]", Arrays.toString(keySet)); - } - -} diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java index 1689a5054d..ec20b7794b 100644 --- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java @@ -1,7 +1,6 @@ package com.baeldung.util; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import java.time.Clock; import java.time.Instant; @@ -10,8 +9,6 @@ import java.time.LocalTime; import java.time.ZoneId; import java.time.temporal.ChronoField; -import org.joda.time.DateTime; -import org.joda.time.DateTimeUtils; import org.junit.Test; public class CurrentDateTimeUnitTest { diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java b/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java new file mode 100644 index 0000000000..46c2e688ce --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java @@ -0,0 +1,15 @@ +package com.baeldung.java9.process; + +import java.util.Scanner; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class ChildProcess { + + public static void main(String[] args) { + @SuppressWarnings("resource") + Scanner input = new Scanner(System.in); + Logger log = Logger.getLogger(ChildProcess.class.getName()); + log.log(Level.INFO, input.nextLine()); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java b/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java new file mode 100644 index 0000000000..443847916a --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java @@ -0,0 +1,16 @@ +package com.baeldung.java9.process; + +import java.util.logging.Level; +import java.util.logging.Logger; + +public class OutputStreamExample { + + public static void main(String[] args) { + Logger log = Logger.getLogger(OutputStreamExample.class.getName()); + log.log(Level.INFO, Integer.toString(sum(1,2))); + } + + public static int sum(int a, int b) { + return a + b; + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java new file mode 100644 index 0000000000..8b6ae0b441 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java @@ -0,0 +1,7 @@ +package com.baeldung.java9.process; + +public class ProcessCompilationError { + //This method has been written to generate error to display + //how process errorStream() can consume error + public static void(); +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java new file mode 100644 index 0000000000..74101ba3da --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java @@ -0,0 +1,110 @@ +package com.baeldung.java9.process; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class ProcessUnderstanding { + + public static int compileAndRunJavaProgram() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); + process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + int value = Integer.parseInt(output.readLine()); + return value; + } + + public static String getErrorStreamExample() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java"); + BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); + String errorString = error.readLine(); + return errorString; + } + + public static void creatingNewProcess() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + } + + public static int filterProcessWithStreamsInSpecificRangeReturnCount() { + return (int) ProcessHandle.allProcesses() + .filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000)) + .count(); + } + + public static void destroyingProcessCreatedBySameProcess() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + } + + public static void destroyingProcessCreatedByDifferentProcess() { + // find out the process id of current running task by checking + // task manager in windows and enter the integer value + Optional optionalProcessHandle = ProcessHandle.of(5232); + ProcessHandle processHandle = optionalProcessHandle.get(); + processHandle.destroy(); + } + + public static int waitForExample() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + return process.waitFor(); + } + + public static int exitValueExample() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + process.destroy(); + return process.exitValue(); + } + + public static void destroyExample() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + } + + public static void destroyForciblyExample() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + if (process.isAlive()) { + process.destroyForcibly(); + } + } + + public static void outputStreamDemo() throws IOException, InterruptedException { + Logger log = Logger.getLogger(ProcessUnderstanding.class.getName()); + Process pr = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java"); + final Process process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess"); + try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) { + w.write("send to child\n"); + } + new Thread(() -> { + try { + int c; + while ((c = process.getInputStream() + .read()) != -1) + System.out.write((byte) c); + } catch (Exception e) { + e.printStackTrace(); + } + }).start(); + // send to child + log.log(Level.INFO, "rc=" + process.waitFor()); + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java new file mode 100644 index 0000000000..2f61846c1c --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java @@ -0,0 +1,121 @@ +package com.baeldung.java9.process; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.String; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.lang.Integer; + +import org.junit.jupiter.api.Test; + +class ProcessUnderstandingTest { + + @Test + public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); + process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + int value = Integer.parseInt(output.readLine()); + assertEquals(3, value); + } + + @Test + public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); + process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + int value = Integer.parseInt(output.readLine()); + assertEquals(3, value); + } + + @Test + public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java"); + BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); + String errorString = error.readLine(); + assertNotNull(errorString); + } + + //@Test - windows specific + public void givenSubProcess_thenStartSuccessIsAlive() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + assertTrue(builder.start().isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenDestroying_thenProcessNotAlive() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + assertFalse(process.isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + if (process.isAlive()) { + process.destroyForcibly(); + } + assertFalse(process.isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_checkAlive() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + assertFalse(process.isAlive()); + } + + @Test + public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() { + Optional optionalProcessHandle = ProcessHandle.of(5232); + ProcessHandle processHandle = optionalProcessHandle.get(); + processHandle.destroy(); + assertFalse(processHandle.isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + assertThat(process.waitFor() >= 0); + } + + //@Test - windows specific + public void givenSubProcess_whenCurrentThreadWaitsAndSubProcessNotTerminated_thenProcessWaitForReturnsFalse() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + assertFalse(process.waitFor(1, TimeUnit.SECONDS)); + } + + //@Test - windows specific + public void givenSubProcess_whenCurrentThreadWillNotWaitIndefinitelyforSubProcessToEnd_thenProcessExitValueReturnsGrt0() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + assertThat(process.exitValue() >= 0); + } + + @Test + public void givenRunningProcesses_whenFilterOnProcessIdRange_thenGetSelectedProcessPid() { + assertThat(((int) ProcessHandle.allProcesses() + .filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000)) + .count()) > 0); + } +} diff --git a/core-java-collections/README.md b/core-java-collections/README.md index 99d03cad26..ab13ba7c01 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -37,3 +37,9 @@ - [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map) - [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset) - [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element) +- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) +- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection) +- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) +- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table) +- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) +- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) diff --git a/core-java-8/src/main/java/com/baeldung/findanelement/Customer.java b/core-java-collections/src/main/java/com/baeldung/findanelement/Customer.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/findanelement/Customer.java rename to core-java-collections/src/main/java/com/baeldung/findanelement/Customer.java diff --git a/core-java-8/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java b/core-java-collections/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java rename to core-java-collections/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java diff --git a/core-java-8/src/main/java/com/baeldung/hashtable/Word.java b/core-java-collections/src/main/java/com/baeldung/hashtable/Word.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/hashtable/Word.java rename to core-java-collections/src/main/java/com/baeldung/hashtable/Word.java diff --git a/core-java-8/src/main/java/com/baeldung/iterators/Iterators.java b/core-java-collections/src/main/java/com/baeldung/iterators/Iterators.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/iterators/Iterators.java rename to core-java-collections/src/main/java/com/baeldung/iterators/Iterators.java diff --git a/core-java-8/src/main/java/com/baeldung/list/CopyListService.java b/core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java similarity index 98% rename from core-java-8/src/main/java/com/baeldung/list/CopyListService.java rename to core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java index 55d5bb9379..5c92d856aa 100644 --- a/core-java-8/src/main/java/com/baeldung/list/CopyListService.java +++ b/core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java @@ -1,4 +1,4 @@ -package com.baeldung.list; +package com.baeldung.java.list; import java.util.ArrayList; import java.util.Collections; diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Car.java b/core-java-collections/src/main/java/com/baeldung/java_8_features/Car.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Car.java rename to core-java-collections/src/main/java/com/baeldung/java_8_features/Car.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Person.java b/core-java-collections/src/main/java/com/baeldung/java_8_features/Person.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Person.java rename to core-java-collections/src/main/java/com/baeldung/java_8_features/Person.java diff --git a/core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java b/core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java b/core-java-collections/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java similarity index 95% rename from core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java index 348747111f..bc1611038c 100644 --- a/core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java @@ -1,13 +1,17 @@ -package com.baeldung.list; +package com.baeldung.java.list; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; public class CopyListServiceUnitTest { diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/linesintersection/LinesIntersectionService.java b/core-java/src/main/java/com/baeldung/linesintersection/LinesIntersectionService.java deleted file mode 100644 index e4fed5a22e..0000000000 --- a/core-java/src/main/java/com/baeldung/linesintersection/LinesIntersectionService.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.linesintersection; - -import java.awt.Point; -import java.util.Optional; - -public class LinesIntersectionService { - - public Optional calculateIntersectionPoint(float m1, float b1, float m2, float b2) { - - if (m1 == m2) { - return Optional.empty(); - } - - float x = (b2 - b1) / (m1 - m2); - float y = m1 * x + b1; - - Point point = new Point(Math.round(x), Math.round(y)); - - return Optional.of(point); - } -} diff --git a/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java b/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java new file mode 100644 index 0000000000..bebffe52f1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java @@ -0,0 +1,45 @@ +/** + * + */ +package com.baeldung.string; + +/** + * @author swpraman + * + */ +public class AppendCharAtPositionX { + + public String addCharUsingCharArray(String str, char ch, int position) { + validate(str, position); + int len = str.length(); + char[] updatedArr = new char[len + 1]; + str.getChars(0, position, updatedArr, 0); + updatedArr[position] = ch; + str.getChars(position, len, updatedArr, position + 1); + return new String(updatedArr); + } + + public String addCharUsingSubstring(String str, char ch, int position) { + validate(str, position); + return str.substring(0, position) + ch + str.substring(position); + } + + public String addCharUsingStringBuilder(String str, char ch, int position) { + validate(str, position); + StringBuilder sb = new StringBuilder(str); + sb.insert(position, ch); + return sb.toString(); + } + + private void validate(String str, int position) { + if (str == null) { + throw new IllegalArgumentException("Str should not be null"); + } + int len = str.length(); + if (position < 0 || position > len) { + throw new IllegalArgumentException("position[" + position + "] should be " + + "in the range 0.." + len + " for string " + str); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java b/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java new file mode 100644 index 0000000000..bdf6684f78 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java @@ -0,0 +1,23 @@ +package com.baeldung.synthetic; + +import java.util.Comparator; + +/** + * Class which contains a synthetic bridge method. + * + * @author Donato Rimenti + * + */ +public class BridgeMethodDemo implements Comparator { + + /* + * (non-Javadoc) + * + * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) + */ + @Override + public int compare(Integer o1, Integer o2) { + return 0; + } + +} diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java new file mode 100644 index 0000000000..d3d75ac05e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java @@ -0,0 +1,34 @@ +package com.baeldung.synthetic; + +/** + * Wrapper for a class which contains a synthetic constructor. + * + * @author Donato Rimenti + * + */ +public class SyntheticConstructorDemo { + + /** + * We need to instantiate the {@link NestedClass} using a private + * constructor from the enclosing instance in order to generate a synthetic + * constructor. + */ + private NestedClass nestedClass = new NestedClass(); + + /** + * Class which contains a synthetic constructor. + * + * @author Donato Rimenti + * + */ + class NestedClass { + + /** + * In order to generate a synthetic constructor, this class must have a + * private constructor. + */ + private NestedClass() { + } + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java new file mode 100644 index 0000000000..1813e03953 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java @@ -0,0 +1,22 @@ +package com.baeldung.synthetic; + +/** + * Wrapper for a class which contains a synthetic field reference to the outer + * class. + * + * @author Donato Rimenti + * + */ +public class SyntheticFieldDemo { + + /** + * Class which contains a synthetic field reference to the outer class. + * + * @author Donato Rimenti + * + */ + class NestedClass { + + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java new file mode 100644 index 0000000000..59be4e1429 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java @@ -0,0 +1,48 @@ +package com.baeldung.synthetic; + +/** + * Wrapper for a class which contains two synthetic methods accessors to a + * private field. + * + * @author Donato Rimenti + * + */ +public class SyntheticMethodDemo { + + /** + * Class which contains two synthetic methods accessors to a private field. + * + * @author Donato Rimenti + * + */ + class NestedClass { + + /** + * Field for which will be generated synthetic methods accessors. It's + * important that this field is private for this purpose. + */ + private String nestedField; + } + + /** + * Gets the private nested field. We need to read the nested field in order + * to generate the synthetic getter. + * + * @return the {@link NestedClass#nestedField} + */ + public String getNestedField() { + return new NestedClass().nestedField; + } + + /** + * Sets the private nested field. We need to write the nested field in order + * to generate the synthetic setter. + * + * @param nestedField + * the {@link NestedClass#nestedField} + */ + public void setNestedField(String nestedField) { + new NestedClass().nestedField = nestedField; + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java b/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java new file mode 100644 index 0000000000..2cdf6145d3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java @@ -0,0 +1,110 @@ +/** + * + */ +package com.baeldung.string; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * @author swpraman + * + */ +public class AppendCharAtPositionXUnitTest { + + private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX(); + private String word = "Titanc"; + private char letter = 'i'; + + @Test + public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() { + assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0)); + } + + @Test + public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() { + assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0)); + } + + @Test + public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() { + assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0)); + } + + @Test + public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() { + assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3)); + } + + @Test + public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() { + assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3)); + } + + @Test + public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() { + assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3)); + } + + @Test + public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() { + assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length())); + } + + @Test + public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() { + assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length())); + } + + @Test + public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() { + assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length())); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3); + } + +} diff --git a/core-java/src/test/java/com/baeldung/synthetic/SyntheticUnitTest.java b/core-java/src/test/java/com/baeldung/synthetic/SyntheticUnitTest.java new file mode 100644 index 0000000000..20f7647f48 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/synthetic/SyntheticUnitTest.java @@ -0,0 +1,99 @@ +package com.baeldung.synthetic; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Unit test for {@link SyntheticFieldDemo}, {@link SyntheticMethodDemo}, + * {@link SyntheticConstructorDemo} and {@link BridgeMethodDemo} classes. + * + * @author Donato Rimenti + * + */ +public class SyntheticUnitTest { + + /** + * Tests that the {@link SyntheticMethodDemo.NestedClass} contains two synthetic + * methods. + */ + @Test + public void givenSyntheticMethod_whenIsSinthetic_thenTrue() { + // Checks that the nested class contains exactly two synthetic methods. + Method[] methods = SyntheticMethodDemo.NestedClass.class.getDeclaredMethods(); + Assert.assertEquals("This class should contain only two methods", 2, methods.length); + + for (Method m : methods) { + System.out.println("Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic()); + Assert.assertTrue("All the methods of this class should be synthetic", m.isSynthetic()); + } + } + + /** + * Tests that {@link SyntheticConstructorDemo.NestedClass} contains a synthetic + * constructor. + */ + @Test + public void givenSyntheticConstructor_whenIsSinthetic_thenTrue() { + // Checks that the nested class contains exactly a synthetic + // constructor. + int syntheticConstructors = 0; + Constructor[] constructors = SyntheticConstructorDemo.NestedClass.class.getDeclaredConstructors(); + Assert.assertEquals("This class should contain only two constructors", 2, constructors.length); + + for (Constructor c : constructors) { + System.out.println("Constructor: " + c.getName() + ", isSynthetic: " + c.isSynthetic()); + + // Counts the synthetic constructors. + if (c.isSynthetic()) { + syntheticConstructors++; + } + } + + // Checks that there's exactly one synthetic constructor. + Assert.assertEquals(1, syntheticConstructors); + } + + /** + * Tests that {@link SyntheticFieldDemo.NestedClass} contains a synthetic field. + */ + @Test + public void givenSyntheticField_whenIsSinthetic_thenTrue() { + // This class should contain exactly one synthetic field. + Field[] fields = SyntheticFieldDemo.NestedClass.class.getDeclaredFields(); + Assert.assertEquals("This class should contain only one field", 1, fields.length); + + for (Field f : fields) { + System.out.println("Field: " + f.getName() + ", isSynthetic: " + f.isSynthetic()); + Assert.assertTrue("All the fields of this class should be synthetic", f.isSynthetic()); + } + } + + /** + * Tests that {@link BridgeMethodDemo} contains a synthetic bridge method. + */ + @Test + public void givenBridgeMethod_whenIsBridge_thenTrue() { + // This class should contain exactly one synthetic bridge method. + int syntheticMethods = 0; + Method[] methods = BridgeMethodDemo.class.getDeclaredMethods(); + for (Method m : methods) { + System.out.println( + "Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic() + ", isBridge: " + m.isBridge()); + + // Counts the synthetic methods and checks that they are also bridge + // methods. + if (m.isSynthetic()) { + syntheticMethods++; + Assert.assertTrue("The synthetic method in this class should also be a bridge method", m.isBridge()); + } + } + + // Checks that there's exactly one synthetic bridge method. + Assert.assertEquals("There should be exactly 1 synthetic bridge method in this class", 1, syntheticMethods); + } + +} \ No newline at end of file diff --git a/java-streams/pom.xml b/java-streams/pom.xml index 75914f0247..4f8651a756 100644 --- a/java-streams/pom.xml +++ b/java-streams/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung java-streams 0.1.0-SNAPSHOT jar @@ -15,17 +14,17 @@ - - - org.openjdk.jmh - jmh-core - ${jmh.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh.version} - provided + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + provided org.apache.commons diff --git a/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java index 2c88dc5ec7..67954f0bba 100644 --- a/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java @@ -1,15 +1,14 @@ package com.baeldung.stream; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Test; public class PrimitiveStreamsUnitTest { @@ -17,7 +16,7 @@ public class PrimitiveStreamsUnitTest { @Test public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() { - int[] integers = new int[] {20, 98, 12, 7, 35}; + int[] integers = new int[] { 20, 98, 12, 7, 35 }; int min = streams.min(integers); // returns 7 assertEquals(7, min); @@ -66,19 +65,14 @@ public class PrimitiveStreamsUnitTest { @Test public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() { - int sum = Stream.of(33,45) - .mapToInt(i -> i) - .sum(); + int sum = Stream.of(33, 45).mapToInt(i -> i).sum(); assertEquals(78, sum); } @Test public void givenAnIntStreamThenGetTheEvenIntegers() { - List evenInts = IntStream.rangeClosed(1, 10) - .filter(i -> i % 2 == 0) - .boxed() - .collect(Collectors.toList()); + List evenInts = IntStream.rangeClosed(1, 10).filter(i -> i % 2 == 0).boxed().collect(Collectors.toList()); List expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList()); diff --git a/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkUnitTest.java b/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkUnitTest.java index 9ae0a16514..ba1cb1f726 100644 --- a/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkUnitTest.java @@ -18,7 +18,6 @@ import java.util.stream.IntStream; public class BenchmarkUnitTest { - @Test public void launchBenchmark() throws Exception { diff --git a/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java b/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java new file mode 100644 index 0000000000..c4f684383d --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java @@ -0,0 +1,29 @@ +package com.baeldung.string.sorting; + +import java.util.Arrays; + +public class AnagramValidator { + + public static boolean isValid(String text, String anagram) { + text = prepare(text); + anagram = prepare(anagram); + + String sortedText = sort(text); + String sortedAnagram = sort(anagram); + + return sortedText.equals(sortedAnagram); + } + + private static String sort(String text) { + char[] chars = prepare(text).toCharArray(); + + Arrays.sort(chars); + return new String(chars); + } + + private static String prepare(String text) { + return text.toLowerCase() + .trim() + .replaceAll("\\s+", ""); + } +} \ No newline at end of file diff --git a/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java b/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java new file mode 100644 index 0000000000..f236c641c3 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.string.formatter; + +import org.junit.BeforeClass; +import org.junit.Test; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import static org.junit.Assert.assertEquals; + +public class DateToStringFormatterUnitTest { + + private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a"; + private static final String EXPECTED_STRING_DATE = "Aug 1, 2018 12:00 PM"; + private static Date date; + + @BeforeClass + public static void setUp() { + TimeZone.setDefault(TimeZone.getTimeZone("CET")); + Calendar calendar = Calendar.getInstance(); + calendar.set(2018, Calendar.AUGUST, 1, 12, 0); + date = calendar.getTime(); + } + + @Test + public void whenDateConvertedUsingSimpleDateFormatToString_thenCorrect() { + DateFormat formatter = new SimpleDateFormat(DATE_FORMAT); + String formattedDate = formatter.format(date); + + assertEquals(EXPECTED_STRING_DATE, formattedDate); + } + + @Test + public void whenDateConvertedUsingDateFormatToString_thenCorrect() { + String formattedDate = DateFormat + .getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT) + .format(date); + + assertEquals(EXPECTED_STRING_DATE, formattedDate); + } + + @Test + public void whenDateConvertedUsingFormatterToString_thenCorrect() { + String formattedDate = String.format("%1$tb %1$te, %1$tY %1$tI:%1$tM %1$Tp", date); + + assertEquals(EXPECTED_STRING_DATE, formattedDate); + } + + @Test + public void whenDateConvertedUsingDateTimeApiToString_thenCorrect() { + DateTimeFormatter fmt = DateTimeFormatter.ofPattern(DATE_FORMAT); + Instant instant = date.toInstant(); + LocalDateTime ldt = instant + .atZone(ZoneId.of("CET")) + .toLocalDateTime(); + String formattedDate = ldt.format(fmt); + + assertEquals(EXPECTED_STRING_DATE, formattedDate); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/sorting/AnagramValidatorUnitTest.java b/java-strings/src/test/java/com/baeldung/string/sorting/AnagramValidatorUnitTest.java new file mode 100644 index 0000000000..07d31c7187 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/sorting/AnagramValidatorUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.string.sorting; + + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.jupiter.api.Test; + +import com.baeldung.string.sorting.AnagramValidator; + +class AnagramValidatorUnitTest { + + @Test + void givenValidAnagrams_whenSorted_thenEqual() { + boolean isValidAnagram = AnagramValidator.isValid("Avida Dollars", "Salvador Dali"); + + assertTrue(isValidAnagram); + } + + @Test + void givenNotValidAnagrams_whenSorted_thenNotEqual() { + boolean isValidAnagram = AnagramValidator.isValid("abc", "def"); + + assertFalse(isValidAnagram); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/sorting/SortStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/sorting/SortStringUnitTest.java new file mode 100644 index 0000000000..90d1dad554 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/sorting/SortStringUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.string.sorting; + +import java.util.Arrays; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SortStringUnitTest { + + @Test + void givenString_whenSort_thenSorted() { + String abcd = "bdca"; + char[] chars = abcd.toCharArray(); + + Arrays.sort(chars); + String sorted = new String(chars); + + assertThat(sorted).isEqualTo("abcd"); + } + + @Test + void givenString_whenSortJava8_thenSorted() { + String sorted = "bdca".chars() + .sorted() + .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) + .toString(); + + assertThat(sorted).isEqualTo("abcd"); + } +} diff --git a/jersey-client-rx/pom.xml b/jersey-client-rx/pom.xml deleted file mode 100644 index 24894869a5..0000000000 --- a/jersey-client-rx/pom.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - 4.0.0 - com.baeldung.samples - jersey-client-rx - 1.0 - jar - - - org.glassfish.jersey.inject - jersey-hk2 - 2.27 - - - org.glassfish.jersey.core - jersey-client - 2.27 - - - org.glassfish.jersey.ext.rx - jersey-rx-client-rxjava - 2.27 - - - org.glassfish.jersey.ext.rx - jersey-rx-client-rxjava2 - 2.27 - - - com.github.tomakehurst - wiremock - 1.58 - test - - - org.junit.vintage - junit-vintage-engine - 5.2.0 - - - org.glassfish.jersey.media - jersey-media-json-jackson - 2.25 - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - 2.4.1 - - - org.slf4j - slf4j-jdk14 - 1.7.25 - - - org.assertj - assertj-core - 3.10.0 - test - - - - UTF-8 - 1.8 - 1.8 - - \ No newline at end of file diff --git a/jersey-client-rx/readme.md b/jersey-client-rx/readme.md deleted file mode 100644 index d1bc4e950b..0000000000 --- a/jersey-client-rx/readme.md +++ /dev/null @@ -1,3 +0,0 @@ -# Fluent, Reactive Jersey Client Orchestration # - -### Sample code demonstrating the options for asynchronous, reactive RESTful service consumption with JAX-RS ### diff --git a/jersey/src/main/java/com/baeldung/jersey/server/Responder.java b/jersey/src/main/java/com/baeldung/jersey/server/Responder.java new file mode 100644 index 0000000000..cb0c976fe3 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/Responder.java @@ -0,0 +1,102 @@ +package com.baeldung.jersey.server; + +import com.baeldung.jersey.server.model.Person; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@Path("/response") +public class Responder { + + @GET + @Path("/ok") + public Response getOkResponse() { + + String message = "This is a text response"; + + return Response + .status(Response.Status.OK) + .entity(message) + .build(); + } + + @GET + @Path("/not_ok") + public Response getNOkTextResponse() { + + String message = "There was an internal server error"; + + return Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(message) + .build(); + } + + @GET + @Path("/text_plain") + public Response getTextResponseTypeDefined() { + + String message = "This is a plain text response"; + + return Response + .status(Response.Status.OK) + .entity(message) + .type(MediaType.TEXT_PLAIN) + .build(); + } + + @GET + @Path("/text_plain_annotation") + @Produces({ MediaType.TEXT_PLAIN }) + public Response getTextResponseTypeAnnotated() { + + String message = "This is a plain text response via annotation"; + + return Response + .status(Response.Status.OK) + .entity(message) + .build(); + } + + @GET + @Path("/pojo") + public Response getPojoResponse() { + + Person person = new Person("Abh", "Nepal"); + + return Response + .status(Response.Status.OK) + .entity(person) + .build(); + } + + @GET + @Path("/json") + public Response getJsonResponse() { + + String message = "{\"hello\": \"This is a JSON response\"}"; + + return Response + .status(Response.Status.OK) + .entity(message) + .type(MediaType.APPLICATION_JSON) + .build(); + } + + @GET + @Path("/xml") + @Produces(MediaType.TEXT_XML) + public String sayXMLHello() { + return "" + " This is a xml response "; + } + + @GET + @Path("/html") + @Produces(MediaType.TEXT_HTML) + public String sayHtmlHello() { + return " " + "" + " This is a html title " + "

" + " This is a html response body " + "

" + " "; + } +} \ No newline at end of file diff --git a/jersey/src/main/java/com/baeldung/jersey/server/model/Person.java b/jersey/src/main/java/com/baeldung/jersey/server/model/Person.java new file mode 100644 index 0000000000..98c86bbc3d --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/model/Person.java @@ -0,0 +1,32 @@ +package com.baeldung.jersey.server.model; + +public class Person { + String name; + String address; + + public Person(String name, String address) { + this.name = name; + this.address = address; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + @Override + public String toString() { + return "Person [name: " + getName() + " address: " + getAddress() + "]"; + } +} \ No newline at end of file diff --git a/jpa-storedprocedure/README.md b/jpa-storedprocedure/README.md deleted file mode 100644 index 39d6784d8b..0000000000 --- a/jpa-storedprocedure/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) diff --git a/jpa-storedprocedure/pom.xml b/jpa-storedprocedure/pom.xml deleted file mode 100644 index 79fa637cb6..0000000000 --- a/jpa-storedprocedure/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - 4.0.0 - com.baeldung - jpa-storedprocedure - 1.0 - jar - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - - javax - javaee-api - ${jee.version} - provided - - - org.hibernate - hibernate-entitymanager - ${hibernate.version} - - - - mysql - mysql-connector-java - ${mysql.version} - - - commons-io - commons-io - ${commons-io.version} - - - - - JpaStoredProcedure - - - maven-assembly-plugin - - ${project.basedir} - - - jar-with-dependencies - - - - - - - - 7.0 - 5.2.5.Final - 6.0.5 - 2.5 - - - \ No newline at end of file diff --git a/jpa-storedprocedure/src/main/resources/META-INF/persistence.xml b/jpa-storedprocedure/src/main/resources/META-INF/persistence.xml deleted file mode 100644 index 4c443cb7cf..0000000000 --- a/jpa-storedprocedure/src/main/resources/META-INF/persistence.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.model.Car - - - - - - - - - - \ No newline at end of file diff --git a/jpa-storedprocedure/src/main/resources/logback.xml b/jpa-storedprocedure/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/jpa-storedprocedure/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/libraries-server/README.md b/libraries-server/README.md new file mode 100644 index 0000000000..c25e9a10ab --- /dev/null +++ b/libraries-server/README.md @@ -0,0 +1,9 @@ +### Relevant articles + +- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded) +- [Introduction to Netty](http://www.baeldung.com/netty) +- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling) +- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup) +- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic) +- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel) + diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml index 517cf6a07c..6fca09faf4 100644 --- a/libraries-server/pom.xml +++ b/libraries-server/pom.xml @@ -14,6 +14,73 @@ org.eclipse.paho org.eclipse.paho.client.mqttv3 1.2.0 -
+
+ + + org.assertj + assertj-core + ${assertj.version} + + + org.eclipse.jetty + jetty-server + ${jetty.version} + + + org.eclipse.jetty + jetty-servlet + ${jetty.version} + + + org.eclipse.jetty + jetty-webapp + ${jetty.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + commons-logging + commons-logging + + + + + commons-io + commons-io + ${commons.io.version} + + + io.netty + netty-all + ${netty.version} + + + junit + junit + ${junit.version} + test + + + + + org.apache.tomcat + tomcat-catalina + ${tomcat.version} +
-
\ No newline at end of file + + + 3.6.2 + 4.5.3 + 2.5 + 9.4.8.v20171121 + 4.1.20.Final + 4.1 + 4.12 + 8.5.24 + + + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jetty/AsyncServlet.java b/libraries-server/src/main/java/com/baeldung/jetty/AsyncServlet.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/AsyncServlet.java rename to libraries-server/src/main/java/com/baeldung/jetty/AsyncServlet.java diff --git a/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java b/libraries-server/src/main/java/com/baeldung/jetty/BlockingServlet.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java rename to libraries-server/src/main/java/com/baeldung/jetty/BlockingServlet.java diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java b/libraries-server/src/main/java/com/baeldung/jetty/JettyServer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/JettyServer.java rename to libraries-server/src/main/java/com/baeldung/jetty/JettyServer.java diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java b/libraries-server/src/main/java/com/baeldung/jetty/JettyServerFactory.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java rename to libraries-server/src/main/java/com/baeldung/jetty/JettyServerFactory.java diff --git a/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java b/libraries-server/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java rename to libraries-server/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java b/libraries-server/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerA.java b/libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerA.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ChannelHandlerA.java rename to libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerA.java diff --git a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java b/libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerB.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java rename to libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerB.java diff --git a/libraries/src/main/java/com/baeldung/netty/ClientHandler.java b/libraries-server/src/main/java/com/baeldung/netty/ClientHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ClientHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/ClientHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/HttpMessageHandler.java b/libraries-server/src/main/java/com/baeldung/netty/HttpMessageHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/HttpMessageHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/HttpMessageHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/NettyClient.java b/libraries-server/src/main/java/com/baeldung/netty/NettyClient.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/NettyClient.java rename to libraries-server/src/main/java/com/baeldung/netty/NettyClient.java diff --git a/libraries/src/main/java/com/baeldung/netty/NettyServer.java b/libraries-server/src/main/java/com/baeldung/netty/NettyServer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/NettyServer.java rename to libraries-server/src/main/java/com/baeldung/netty/NettyServer.java diff --git a/libraries/src/main/java/com/baeldung/netty/NettyServerB.java b/libraries-server/src/main/java/com/baeldung/netty/NettyServerB.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/NettyServerB.java rename to libraries-server/src/main/java/com/baeldung/netty/NettyServerB.java diff --git a/libraries/src/main/java/com/baeldung/netty/Operation.java b/libraries-server/src/main/java/com/baeldung/netty/Operation.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/Operation.java rename to libraries-server/src/main/java/com/baeldung/netty/Operation.java diff --git a/libraries/src/main/java/com/baeldung/netty/ProcessingHandler.java b/libraries-server/src/main/java/com/baeldung/netty/ProcessingHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ProcessingHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/ProcessingHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/RequestData.java b/libraries-server/src/main/java/com/baeldung/netty/RequestData.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/RequestData.java rename to libraries-server/src/main/java/com/baeldung/netty/RequestData.java diff --git a/libraries/src/main/java/com/baeldung/netty/RequestDataEncoder.java b/libraries-server/src/main/java/com/baeldung/netty/RequestDataEncoder.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/RequestDataEncoder.java rename to libraries-server/src/main/java/com/baeldung/netty/RequestDataEncoder.java diff --git a/libraries/src/main/java/com/baeldung/netty/RequestDecoder.java b/libraries-server/src/main/java/com/baeldung/netty/RequestDecoder.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/RequestDecoder.java rename to libraries-server/src/main/java/com/baeldung/netty/RequestDecoder.java diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseData.java b/libraries-server/src/main/java/com/baeldung/netty/ResponseData.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ResponseData.java rename to libraries-server/src/main/java/com/baeldung/netty/ResponseData.java diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseDataDecoder.java b/libraries-server/src/main/java/com/baeldung/netty/ResponseDataDecoder.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ResponseDataDecoder.java rename to libraries-server/src/main/java/com/baeldung/netty/ResponseDataDecoder.java diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseDataEncoder.java b/libraries-server/src/main/java/com/baeldung/netty/ResponseDataEncoder.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ResponseDataEncoder.java rename to libraries-server/src/main/java/com/baeldung/netty/ResponseDataEncoder.java diff --git a/libraries/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java b/libraries-server/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java diff --git a/libraries/src/main/java/com/baeldung/tomcat/MyFilter.java b/libraries-server/src/main/java/com/baeldung/tomcat/MyFilter.java similarity index 100% rename from libraries/src/main/java/com/baeldung/tomcat/MyFilter.java rename to libraries-server/src/main/java/com/baeldung/tomcat/MyFilter.java diff --git a/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java b/libraries-server/src/main/java/com/baeldung/tomcat/MyServlet.java similarity index 100% rename from libraries/src/main/java/com/baeldung/tomcat/MyServlet.java rename to libraries-server/src/main/java/com/baeldung/tomcat/MyServlet.java diff --git a/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java b/libraries-server/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java similarity index 100% rename from libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java rename to libraries-server/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java b/libraries-server/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java rename to libraries-server/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java b/libraries-server/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java rename to libraries-server/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java b/libraries-server/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java rename to libraries-server/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java b/libraries-server/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java rename to libraries-server/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java diff --git a/libraries/src/test/resources/jetty-embedded-demo-app.war b/libraries-server/src/test/resources/jetty-embedded-demo-app.war similarity index 100% rename from libraries/src/test/resources/jetty-embedded-demo-app.war rename to libraries-server/src/test/resources/jetty-embedded-demo-app.war diff --git a/libraries/README.md b/libraries/README.md index aad3a644ad..c2c4b2718a 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -5,13 +5,11 @@ - [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang) - [Introduction to Javatuples](http://www.baeldung.com/java-tuples) - [Introduction to Javassist](http://www.baeldung.com/javassist) -- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded) - [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink) - [Introduction to JSONassert](http://www.baeldung.com/jsonassert) - [Intro to JaVers](http://www.baeldung.com/javers) - [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math) - [Intro to Serenity BDD](http://www.baeldung.com/serenity-bdd) -- [Introduction to Netty](http://www.baeldung.com/netty) - [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) - [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay) - [Introduction to Quartz](http://www.baeldung.com/quartz) @@ -54,10 +52,7 @@ - [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle) - [Guide to google-http-client](http://www.baeldung.com/google-http-client) - [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client) -- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup) - [A Docker Guide for Java](http://www.baeldung.com/docker-java-api) -- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling) -- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic) - [Introduction To OpenCSV](http://www.baeldung.com/opencsv) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client) @@ -77,7 +72,6 @@ - [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client) - [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools) - [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) -- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel) - [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices) - [Introduction to JavaPoet](http://www.baeldung.com/java-poet) - [Introduction to Joda-Time](http://www.baeldung.com/joda-time) diff --git a/libraries/pom.xml b/libraries/pom.xml index 6b1f842aeb..c8135d8d2a 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -106,21 +106,6 @@ javers-core ${javers.version} - - org.eclipse.jetty - jetty-server - ${jetty.version} - - - org.eclipse.jetty - jetty-servlet - ${jetty.version} - - - org.eclipse.jetty - jetty-webapp - ${jetty.version} - io.nats @@ -169,6 +154,17 @@ commons-dbutils ${commons.dbutils.version} + + org.apache.flink + flink-connector-kafka-0.11_2.11 + ${flink.version} + + + org.apache.flink + flink-streaming-java_2.11 + ${flink.version} + + org.apache.flink flink-core @@ -193,7 +189,7 @@ org.apache.flink - flink-test-utils_2.10 + flink-test-utils_2.11 ${flink.version} test @@ -243,6 +239,11 @@ jackson-databind ${jackson.version} + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson.version} + org.datanucleus @@ -379,11 +380,6 @@ jmh-generator-annprocess ${jmh.version} - - io.netty - netty-all - ${netty.version} - junit junit @@ -658,13 +654,7 @@ test test - - - - org.apache.tomcat - tomcat-catalina - ${tomcat.version} - + org.milyn milyn-smooks-all @@ -924,12 +914,11 @@ 2.5 1.6 1.4.196 - 9.4.8.v20171121 1.0 4.5.3 2.5 - 1.2.0 + 1.5.0 2.8.5 2.92 1.9.26 @@ -937,7 +926,6 @@ 1.9.0 1.9.27 1.1.0 - 4.1.20.Final 4.1 4.12 0.10 @@ -966,7 +954,6 @@ 1.0.0 1.7.0 3.0.14 - 8.5.24 2.2.0 9.1.5.Final 4.1 diff --git a/libraries/src/main/java/com/baeldung/flink/FlinkDataPipeline.java b/libraries/src/main/java/com/baeldung/flink/FlinkDataPipeline.java new file mode 100644 index 0000000000..d02b1bcb83 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/FlinkDataPipeline.java @@ -0,0 +1,82 @@ +package com.baeldung.flink; + + +import com.baeldung.flink.model.Backup; +import com.baeldung.flink.model.InputMessage; +import com.baeldung.flink.operator.BackupAggregator; +import com.baeldung.flink.operator.InputMessageTimestampAssigner; +import com.baeldung.flink.operator.WordsCapitalizer; +import org.apache.flink.streaming.api.TimeCharacteristic; +import org.apache.flink.streaming.api.datastream.DataStream; +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.windowing.time.Time; +import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011; +import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011; + +import static com.baeldung.flink.connector.Consumers.*; +import static com.baeldung.flink.connector.Producers.*; + +public class FlinkDataPipeline { + + public static void capitalize() throws Exception { + String inputTopic = "flink_input"; + String outputTopic = "flink_output"; + String consumerGroup = "baeldung"; + String address = "localhost:9092"; + + StreamExecutionEnvironment environment = + StreamExecutionEnvironment.getExecutionEnvironment(); + + FlinkKafkaConsumer011 flinkKafkaConsumer = + createStringConsumerForTopic(inputTopic, address, consumerGroup); + flinkKafkaConsumer.setStartFromEarliest(); + + DataStream stringInputStream = + environment.addSource(flinkKafkaConsumer); + + FlinkKafkaProducer011 flinkKafkaProducer = + createStringProducer(outputTopic, address); + + stringInputStream + .map(new WordsCapitalizer()) + .addSink(flinkKafkaProducer); + + environment.execute(); + } + +public static void createBackup () throws Exception { + String inputTopic = "flink_input"; + String outputTopic = "flink_output"; + String consumerGroup = "baeldung"; + String kafkaAddress = "localhost:9092"; + + StreamExecutionEnvironment environment = + StreamExecutionEnvironment.getExecutionEnvironment(); + + environment.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); + + FlinkKafkaConsumer011 flinkKafkaConsumer = + createInputMessageConsumer(inputTopic, kafkaAddress, consumerGroup); + flinkKafkaConsumer.setStartFromEarliest(); + + flinkKafkaConsumer + .assignTimestampsAndWatermarks(new InputMessageTimestampAssigner()); + FlinkKafkaProducer011 flinkKafkaProducer = + createBackupProducer(outputTopic, kafkaAddress); + + DataStream inputMessagesStream = + environment.addSource(flinkKafkaConsumer); + + inputMessagesStream + .timeWindowAll(Time.hours(24)) + .aggregate(new BackupAggregator()) + .addSink(flinkKafkaProducer); + + environment.execute(); +} + + public static void main(String[] args) throws Exception { + createBackup(); + } + +} diff --git a/libraries/src/main/java/com/baeldung/flink/connector/Consumers.java b/libraries/src/main/java/com/baeldung/flink/connector/Consumers.java new file mode 100644 index 0000000000..514085f9c4 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/connector/Consumers.java @@ -0,0 +1,32 @@ +package com.baeldung.flink.connector; + +import com.baeldung.flink.model.InputMessage; +import com.baeldung.flink.schema.InputMessageDeserializationSchema; +import org.apache.flink.api.common.serialization.SimpleStringSchema; +import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011; + +import java.util.Properties; + +public class Consumers { + +public static FlinkKafkaConsumer011 createStringConsumerForTopic( + String topic, String kafkaAddress, String kafkaGroup ) { + Properties props = new Properties(); + props.setProperty("bootstrap.servers", kafkaAddress); + props.setProperty("group.id",kafkaGroup); + FlinkKafkaConsumer011 consumer = + new FlinkKafkaConsumer011<>(topic, new SimpleStringSchema(),props); + + return consumer; +} + + public static FlinkKafkaConsumer011 createInputMessageConsumer(String topic, String kafkaAddress, String kafkaGroup ) { + Properties properties = new Properties(); + properties.setProperty("bootstrap.servers", kafkaAddress); + properties.setProperty("group.id",kafkaGroup); + FlinkKafkaConsumer011 consumer = new FlinkKafkaConsumer011( + topic, new InputMessageDeserializationSchema(),properties); + + return consumer; + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/connector/Producers.java b/libraries/src/main/java/com/baeldung/flink/connector/Producers.java new file mode 100644 index 0000000000..8e6f3f8f37 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/connector/Producers.java @@ -0,0 +1,17 @@ +package com.baeldung.flink.connector; + +import com.baeldung.flink.model.Backup; +import com.baeldung.flink.schema.BackupSerializationSchema; +import org.apache.flink.api.common.serialization.SimpleStringSchema; +import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011; + +public class Producers { + + public static FlinkKafkaProducer011 createStringProducer(String topic, String kafkaAddress) { + return new FlinkKafkaProducer011<>(kafkaAddress, topic, new SimpleStringSchema()); + } + + public static FlinkKafkaProducer011 createBackupProducer(String topic, String kafkaAddress) { + return new FlinkKafkaProducer011(kafkaAddress, topic, new BackupSerializationSchema()); + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/model/Backup.java b/libraries/src/main/java/com/baeldung/flink/model/Backup.java new file mode 100644 index 0000000000..268ceec7f3 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/model/Backup.java @@ -0,0 +1,27 @@ +package com.baeldung.flink.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.UUID; + +public class Backup { + + @JsonProperty("inputMessages") + List inputMessages; + @JsonProperty("backupTimestamp") + LocalDateTime backupTimestamp; + @JsonProperty("uuid") + UUID uuid; + + public Backup(List inputMessages, LocalDateTime backupTimestamp) { + this.inputMessages = inputMessages; + this.backupTimestamp = backupTimestamp; + this.uuid = UUID.randomUUID(); + } + + public List getInputMessages() { + return inputMessages; + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/model/InputMessage.java b/libraries/src/main/java/com/baeldung/flink/model/InputMessage.java new file mode 100644 index 0000000000..183fa69c11 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/model/InputMessage.java @@ -0,0 +1,72 @@ +package com.baeldung.flink.model; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.google.common.base.Objects; + +import java.time.LocalDateTime; + +@JsonSerialize +public class InputMessage { + String sender; + String recipient; + LocalDateTime sentAt; + String message; + + public InputMessage() { + } + + public String getSender() { + return sender; + } + + public void setSender(String sender) { + this.sender = sender; + } + + public String getRecipient() { + return recipient; + } + + public void setRecipient(String recipient) { + this.recipient = recipient; + } + + public LocalDateTime getSentAt() { + return sentAt; + } + + public void setSentAt(LocalDateTime sentAt) { + this.sentAt = sentAt; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public InputMessage(String sender, String recipient, LocalDateTime sentAt, String message) { + this.sender = sender; + this.recipient = recipient; + this.sentAt = sentAt; + this.message = message; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + InputMessage message1 = (InputMessage) o; + return Objects.equal(sender, message1.sender) && + Objects.equal(recipient, message1.recipient) && + Objects.equal(sentAt, message1.sentAt) && + Objects.equal(message, message1.message); + } + + @Override + public int hashCode() { + return Objects.hashCode(sender, recipient, sentAt, message); + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/operator/BackupAggregator.java b/libraries/src/main/java/com/baeldung/flink/operator/BackupAggregator.java new file mode 100644 index 0000000000..c39b8413d1 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/operator/BackupAggregator.java @@ -0,0 +1,34 @@ +package com.baeldung.flink.operator; + +import com.baeldung.flink.model.Backup; +import com.baeldung.flink.model.InputMessage; +import org.apache.flink.api.common.functions.AggregateFunction; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + + public class BackupAggregator implements AggregateFunction, Backup> { + @Override + public List createAccumulator() { + return new ArrayList<>(); + } + + @Override + public List add(InputMessage inputMessage, List inputMessages) { + inputMessages.add(inputMessage); + return inputMessages; + } + + @Override + public Backup getResult(List inputMessages) { + Backup backup = new Backup(inputMessages, LocalDateTime.now()); + return backup; + } + + @Override + public List merge(List inputMessages, List acc1) { + inputMessages.addAll(acc1); + return inputMessages; + } + } diff --git a/libraries/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java b/libraries/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java new file mode 100644 index 0000000000..05828d9588 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java @@ -0,0 +1,23 @@ +package com.baeldung.flink.operator; + +import com.baeldung.flink.model.InputMessage; +import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks; +import org.apache.flink.streaming.api.watermark.Watermark; + +import javax.annotation.Nullable; +import java.time.ZoneId; + +public class InputMessageTimestampAssigner implements AssignerWithPunctuatedWatermarks { + + @Override + public long extractTimestamp(InputMessage element, long previousElementTimestamp) { + ZoneId zoneId = ZoneId.systemDefault(); + return element.getSentAt().atZone(zoneId).toEpochSecond() * 1000; + } + + @Nullable + @Override + public Watermark checkAndGetNextWatermark(InputMessage lastElement, long extractedTimestamp) { + return new Watermark(extractedTimestamp - 15); + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java b/libraries/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java new file mode 100644 index 0000000000..f9103d225c --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java @@ -0,0 +1,11 @@ +package com.baeldung.flink.operator; + +import org.apache.flink.api.common.functions.MapFunction; + +public class WordsCapitalizer implements MapFunction { + + @Override + public String map(String s) { + return s.toUpperCase(); + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java b/libraries/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java new file mode 100644 index 0000000000..967b266bb6 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java @@ -0,0 +1,33 @@ +package com.baeldung.flink.schema; + +import com.baeldung.flink.model.Backup; +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.apache.flink.api.common.serialization.SerializationSchema; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class BackupSerializationSchema + implements SerializationSchema { + + static ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + + Logger logger = LoggerFactory.getLogger(BackupSerializationSchema.class); + + @Override + public byte[] serialize(Backup backupMessage) { + if(objectMapper == null) { + objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); + objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + } + try { + String json = objectMapper.writeValueAsString(backupMessage); + return json.getBytes(); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + logger.error("Failed to parse JSON", e); + } + return new byte[0]; + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java b/libraries/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java new file mode 100644 index 0000000000..1df456bbe5 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java @@ -0,0 +1,34 @@ +package com.baeldung.flink.schema; + +import com.baeldung.flink.model.InputMessage; +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.apache.flink.api.common.serialization.DeserializationSchema; +import org.apache.flink.api.common.typeinfo.TypeInformation; + +import java.io.IOException; + +public class InputMessageDeserializationSchema implements + DeserializationSchema { + + static ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + + + @Override + public InputMessage deserialize(byte[] bytes) throws IOException { + + return objectMapper.readValue(bytes, InputMessage.class); + } + + @Override + public boolean isEndOfStream(InputMessage inputMessage) { + return false; + } + + @Override + public TypeInformation getProducedType() { + return TypeInformation.of(InputMessage.class); + } +} diff --git a/libraries/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java b/libraries/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java new file mode 100644 index 0000000000..ab7d119c16 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java @@ -0,0 +1,103 @@ +package com.baeldung.flink; + +import com.baeldung.flink.model.Backup; +import com.baeldung.flink.model.InputMessage; +import com.baeldung.flink.operator.BackupAggregator; +import com.baeldung.flink.operator.InputMessageTimestampAssigner; +import com.baeldung.flink.schema.BackupSerializationSchema; +import com.baeldung.flink.schema.InputMessageDeserializationSchema; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.apache.commons.collections.ListUtils; +import org.apache.flink.api.common.serialization.DeserializationSchema; +import org.apache.flink.api.common.serialization.SerializationSchema; +import org.apache.flink.streaming.api.TimeCharacteristic; +import org.apache.flink.streaming.api.datastream.DataStreamSource; +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.functions.sink.SinkFunction; +import org.apache.flink.streaming.api.windowing.time.Time; +import org.awaitility.Awaitility; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class BackupCreatorIntegrationTest { + public static ObjectMapper mapper; + + @Before + public void setup() { + mapper = new ObjectMapper().registerModule(new JavaTimeModule()); + } + + @Test + public void givenProperJson_whenDeserializeIsInvoked_thenProperObjectIsReturned() throws IOException { + InputMessage message = new InputMessage("Me", "User", LocalDateTime.now(), "Test Message"); + byte[] messageSerialized = mapper.writeValueAsBytes(message); + DeserializationSchema deserializationSchema = new InputMessageDeserializationSchema(); + InputMessage messageDeserialized = deserializationSchema.deserialize(messageSerialized); + + assertEquals(message, messageDeserialized); + } + + @Test + public void givenMultipleInputMessagesFromDifferentDays_whenBackupCreatorIsUser_thenMessagesAreGroupedProperly() throws Exception { + LocalDateTime currentTime = LocalDateTime.now(); + InputMessage message = new InputMessage("Me", "User", currentTime, "First TestMessage"); + InputMessage secondMessage = new InputMessage("Me", "User", currentTime.plusHours(1), "First TestMessage"); + InputMessage thirdMessage = new InputMessage("Me", "User", currentTime.plusHours(2), "First TestMessage"); + InputMessage fourthMessage = new InputMessage("Me", "User", currentTime.plusHours(3), "First TestMessage"); + InputMessage fifthMessage = new InputMessage("Me", "User", currentTime.plusHours(25), "First TestMessage"); + InputMessage sixthMessage = new InputMessage("Me", "User", currentTime.plusHours(26), "First TestMessage"); + + List firstBackupMessages = Arrays.asList(message, secondMessage, thirdMessage, fourthMessage); + List secondBackupMessages = Arrays.asList(fifthMessage, sixthMessage); + List inputMessages = ListUtils.union(firstBackupMessages, secondBackupMessages); + + StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); + env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); + env.setParallelism(1); + DataStreamSource testDataSet = env.fromCollection(inputMessages); + CollectingSink sink = new CollectingSink(); + testDataSet.assignTimestampsAndWatermarks(new InputMessageTimestampAssigner()) + .timeWindowAll(Time.hours(24)) + .aggregate(new BackupAggregator()) + .addSink(sink); + + env.execute(); + + Awaitility.await().until(() -> sink.backups.size() == 2); + assertEquals(2, sink.backups.size()); + assertEquals(firstBackupMessages, sink.backups.get(0).getInputMessages()); + assertEquals(secondBackupMessages, sink.backups.get(1).getInputMessages()); + + } + + @Test + public void givenProperBackupObject_whenSerializeIsInvoked_thenObjectIsProperlySerialized() throws IOException { + InputMessage message = new InputMessage("Me", "User", LocalDateTime.now(), "Test Message"); + List messages = Arrays.asList(message); + Backup backup = new Backup(messages, LocalDateTime.now()); + byte[] backupSerialized = mapper.writeValueAsBytes(backup); + SerializationSchema serializationSchema = new BackupSerializationSchema(); + byte[] backupProcessed = serializationSchema.serialize(backup); + + assertEquals(backupSerialized, backupProcessed); + } + + private static class CollectingSink implements SinkFunction { + + public static List backups = new ArrayList<>(); + + @Override + public synchronized void invoke(Backup value, Context context) throws Exception { + backups.add(value); + } + } +} diff --git a/libraries/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java b/libraries/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java new file mode 100644 index 0000000000..8a98dae4b5 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.flink; + +import com.baeldung.flink.operator.WordsCapitalizer; +import org.apache.flink.api.java.DataSet; +import org.apache.flink.api.java.ExecutionEnvironment; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class WordCapitalizerIntegrationTest { + + @Test + public void givenDataSet_whenExecuteWordCapitalizer_thenReturnCapitalizedWords() throws Exception { + ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); + List data = Arrays.asList("dog", "cat", "wolf", "pig"); + + DataSet testDataSet = env.fromCollection(data); + + + List dataProcessed = testDataSet + .map(new WordsCapitalizer()) + .collect(); + + List testDataCapitalized = data.stream() + .map(String::toUpperCase) + .collect(Collectors.toList()); + + Assert.assertEquals(testDataCapitalized, dataProcessed); + } + +} diff --git a/optaplanner/pom.xml b/optaplanner/pom.xml new file mode 100644 index 0000000000..22abbedc8c --- /dev/null +++ b/optaplanner/pom.xml @@ -0,0 +1,27 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + optaplanner + + + + org.optaplanner + optaplanner-core + 7.9.0.Final + + + + + + + + + \ No newline at end of file diff --git a/optaplanner/src/main/java/com/baeldung/optaplanner/CourseSchedule.java b/optaplanner/src/main/java/com/baeldung/optaplanner/CourseSchedule.java new file mode 100644 index 0000000000..8a820ab56e --- /dev/null +++ b/optaplanner/src/main/java/com/baeldung/optaplanner/CourseSchedule.java @@ -0,0 +1,63 @@ +package com.baeldung.optaplanner; + +import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty; +import org.optaplanner.core.api.domain.solution.PlanningScore; +import org.optaplanner.core.api.domain.solution.PlanningSolution; +import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty; +import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +@PlanningSolution +public class CourseSchedule { + + Logger logger = LoggerFactory.getLogger("CourseSchedule"); + + private List roomList; + private List periodList; + private List lectureList; + private HardSoftScore score; + + public CourseSchedule(){ + roomList = new ArrayList<>(); + periodList = new ArrayList<>(); + lectureList = new ArrayList<>(); + } + + @ValueRangeProvider(id = "availableRooms") + @ProblemFactCollectionProperty + public List getRoomList() { + return roomList; + } + + @ValueRangeProvider(id = "availablePeriods") + @ProblemFactCollectionProperty + public List getPeriodList() { + return periodList; + } + + @PlanningEntityCollectionProperty + public List getLectureList() { + return lectureList; + } + + @PlanningScore + public HardSoftScore getScore() { + return score; + } + + public void setScore(HardSoftScore score) { + this.score = score; + } + + public void printCourseSchedule() { + lectureList.stream() + .map(c -> "Lecture in Room " + c.getRoomNumber().toString() + " during Period " + c.getPeriod().toString()) + .forEach(k -> logger.info(k)); + } + +} diff --git a/optaplanner/src/main/java/com/baeldung/optaplanner/Lecture.java b/optaplanner/src/main/java/com/baeldung/optaplanner/Lecture.java new file mode 100644 index 0000000000..48af4e89d1 --- /dev/null +++ b/optaplanner/src/main/java/com/baeldung/optaplanner/Lecture.java @@ -0,0 +1,30 @@ +package com.baeldung.optaplanner; + +import org.optaplanner.core.api.domain.entity.PlanningEntity; +import org.optaplanner.core.api.domain.variable.PlanningVariable; + +@PlanningEntity +public class Lecture { + + private Integer roomNumber; + private Integer period; + + @PlanningVariable(valueRangeProviderRefs = {"availablePeriods"}) + public Integer getPeriod() { + return period; + } + + @PlanningVariable(valueRangeProviderRefs = {"availableRooms"}) + public Integer getRoomNumber() { + return roomNumber; + } + + public void setPeriod(Integer period) { + this.period = period; + } + + public void setRoomNumber(Integer roomNumber) { + this.roomNumber = roomNumber; + } + +} diff --git a/optaplanner/src/main/java/com/baeldung/optaplanner/ScoreCalculator.java b/optaplanner/src/main/java/com/baeldung/optaplanner/ScoreCalculator.java new file mode 100644 index 0000000000..11e5e4a5be --- /dev/null +++ b/optaplanner/src/main/java/com/baeldung/optaplanner/ScoreCalculator.java @@ -0,0 +1,32 @@ +package com.baeldung.optaplanner; + +import org.optaplanner.core.api.score.Score; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; +import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator; + +import java.util.HashSet; + +public class ScoreCalculator implements EasyScoreCalculator { + + @Override + public Score calculateScore(CourseSchedule courseSchedule) { + int hardScore = 0; + int softScore = 0; + + HashSet occupiedRooms = new HashSet<>(); + for (Lecture lecture : courseSchedule.getLectureList()) { + if(lecture.getPeriod() != null && lecture.getRoomNumber() != null) { + String roomInUse = lecture.getPeriod().toString() + ":" + lecture.getRoomNumber().toString(); + if (occupiedRooms.contains(roomInUse)) { + hardScore += -1; + } else { + occupiedRooms.add(roomInUse); + } + } else { + hardScore += -1; + } + } + + return HardSoftScore.valueOf(hardScore, softScore); + } +} diff --git a/optaplanner/src/main/resources/courseSchedule.drl b/optaplanner/src/main/resources/courseSchedule.drl new file mode 100644 index 0000000000..9372a24976 --- /dev/null +++ b/optaplanner/src/main/resources/courseSchedule.drl @@ -0,0 +1,14 @@ +package com.baeldung.optaplanner + +import com.baeldung.optaplanner.Lecture; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder; + +global HardSoftScoreHolder scoreHolder; + +rule "noNullRoomPeriod" + when + Lecture( roomNumber == null ); + Lecture( period == null ); + then + scoreHolder.addHardConstraintMatch(kcontext, -1); +end \ No newline at end of file diff --git a/optaplanner/src/main/resources/courseScheduleSolverConfigDrools.xml b/optaplanner/src/main/resources/courseScheduleSolverConfigDrools.xml new file mode 100644 index 0000000000..7cf95fdcd3 --- /dev/null +++ b/optaplanner/src/main/resources/courseScheduleSolverConfigDrools.xml @@ -0,0 +1,12 @@ + + + + + + courseSchedule.drl + + + + 10 + + \ No newline at end of file diff --git a/optaplanner/src/main/resources/courseScheduleSolverConfiguration.xml b/optaplanner/src/main/resources/courseScheduleSolverConfiguration.xml new file mode 100644 index 0000000000..0ad2264dcd --- /dev/null +++ b/optaplanner/src/main/resources/courseScheduleSolverConfiguration.xml @@ -0,0 +1,12 @@ + + + + + + com.baeldung.optaplanner.ScoreCalculator + + + + 10 + + \ No newline at end of file diff --git a/optaplanner/src/main/resources/logback.xml b/optaplanner/src/main/resources/logback.xml new file mode 100644 index 0000000000..c109aa19e2 --- /dev/null +++ b/optaplanner/src/main/resources/logback.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/optaplanner/src/test/java/com/baeldung/optaplanner/test/OptaPlannerUnitTest.java b/optaplanner/src/test/java/com/baeldung/optaplanner/test/OptaPlannerUnitTest.java new file mode 100644 index 0000000000..2847a233a5 --- /dev/null +++ b/optaplanner/src/test/java/com/baeldung/optaplanner/test/OptaPlannerUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.optaplanner.test; + +import com.baeldung.optaplanner.CourseSchedule; +import com.baeldung.optaplanner.Lecture; +import org.junit.Assert; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.optaplanner.core.api.solver.Solver; +import org.optaplanner.core.api.solver.SolverFactory; +import java.util.Arrays; + +public class OptaPlannerUnitTest { + + static CourseSchedule unsolvedCourseSchedule; + + @BeforeAll + public static void setUp() { + + unsolvedCourseSchedule = new CourseSchedule(); + + for(int i = 0; i < 10; i++){ + unsolvedCourseSchedule.getLectureList().add(new Lecture()); + } + + unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(new Integer[] { 1, 2, 3 })); + unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(new Integer[] { 1, 2 })); + } + + @Test + public void test_whenCustomJavaSolver() { + + SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfiguration.xml"); + Solver solver = solverFactory.buildSolver(); + CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); + + Assert.assertNotNull(solvedCourseSchedule.getScore()); + Assert.assertEquals(-4, solvedCourseSchedule.getScore().getHardScore()); + } + + @Test + public void test_whenDroolsSolver() { + + SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfigDrools.xml"); + Solver solver = solverFactory.buildSolver(); + CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); + + Assert.assertNotNull(solvedCourseSchedule.getScore()); + Assert.assertEquals(0, solvedCourseSchedule.getScore().getHardScore()); + } +} diff --git a/persistence-modules/README.md b/persistence-modules/README.md index 8f8c3eb13d..f12163bd6a 100644 --- a/persistence-modules/README.md +++ b/persistence-modules/README.md @@ -7,6 +7,5 @@ - [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search) - [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) - [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce) -- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) - [A Guide to Jdbi](http://www.baeldung.com/jdbi) - [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index e9aabaaa74..418e0a67e2 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -1,3 +1,4 @@ # Relevant Articles -* [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) +- [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) +- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) \ No newline at end of file diff --git a/jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/Car.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/Car.java similarity index 100% rename from jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/Car.java rename to persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/Car.java diff --git a/jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/QueryParameter.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/QueryParameter.java similarity index 100% rename from jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/QueryParameter.java rename to persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/QueryParameter.java diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index e9230eb6cd..3d881673b2 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -20,4 +20,18 @@ + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.model.Car + + + + + + + + + + \ No newline at end of file diff --git a/jpa-storedprocedure/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql b/persistence-modules/java-jpa/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql similarity index 100% rename from jpa-storedprocedure/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql rename to persistence-modules/java-jpa/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql diff --git a/jpa-storedprocedure/src/main/resources/config/database/create_table_mysql.sql b/persistence-modules/java-jpa/src/main/resources/config/database/create_table_mysql.sql similarity index 100% rename from jpa-storedprocedure/src/main/resources/config/database/create_table_mysql.sql rename to persistence-modules/java-jpa/src/main/resources/config/database/create_table_mysql.sql diff --git a/jpa-storedprocedure/src/main/resources/config/database/insert_cars.sql b/persistence-modules/java-jpa/src/main/resources/config/database/insert_cars.sql similarity index 100% rename from jpa-storedprocedure/src/main/resources/config/database/insert_cars.sql rename to persistence-modules/java-jpa/src/main/resources/config/database/insert_cars.sql diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java similarity index 100% rename from jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java rename to persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java diff --git a/jpa-storedprocedure/src/test/resources/persistence.xml b/persistence-modules/java-jpa/src/test/resources/persistence.xml similarity index 100% rename from jpa-storedprocedure/src/test/resources/persistence.xml rename to persistence-modules/java-jpa/src/test/resources/persistence.xml diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index 02d4306ecb..1c89f2453d 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -9,20 +9,15 @@ - [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa) - [JPA Pagination](http://www.baeldung.com/jpa-pagination) - [Sorting with JPA](http://www.baeldung.com/jpa-sort) -- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) - [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) - [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) - [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate) - [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database) -- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories) - [A Guide to Spring AbstractRoutingDatasource](http://www.baeldung.com/spring-abstract-routing-data-source) -- [Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) - [A Guide to Hibernate with Spring 4](http://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) - [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types) - [Obtaining Auto-generated Keys in Spring JDBC](http://www.baeldung.com/spring-jdbc-autogenerated-keys) - [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring) -- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) -- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java deleted file mode 100644 index 439c6cb602..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.baeldung.config; - -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.baeldung.extended.persistence.dao.ExtendedRepositoryImpl; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -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.annotation.EnableTransactionManagement; - -@Configuration -@EnableJpaRepositories(basePackages = "org.baeldung.extended.persistence.dao", repositoryBaseClass = ExtendedRepositoryImpl.class) -@PropertySource("persistence-student-h2.properties") -@EnableTransactionManagement -public class StudentJPAH2Config { - - @Autowired - private Environment env; - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); - dataSource.setUrl(env.getProperty("jdbc.url")); - dataSource.setUsername(env.getProperty("jdbc.user")); - dataSource.setPassword(env.getProperty("jdbc.pass")); - - return dataSource; - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.inmemory.persistence.model" }); - em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); - em.setJpaProperties(additionalProperties()); - return em; - } - - @Bean - JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { - JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(entityManagerFactory); - return transactionManager; - } - - 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.show_sql", env.getProperty("hibernate.show_sql")); - hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); - hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); - - return hibernateProperties; - } -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java deleted file mode 100644 index 7e2efc72bc..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.baeldung.extended.persistence.dao; - -import org.baeldung.inmemory.persistence.model.Student; - -public interface ExtendedStudentRepository extends ExtendedRepository { -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/User.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/User.java deleted file mode 100644 index f84a10cf76..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/User.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.baeldung.persistence.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "users") -public class User { - - @Id - @GeneratedValue - private Integer id; - private String name; - private Integer status; - - public User() { - } - - public User(String name, Integer status) { - this.name = name; - this.status = status; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java deleted file mode 100644 index e250a291bc..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.multiple.dao.user; - -import org.baeldung.persistence.multiple.model.user.User; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface UserRepository extends JpaRepository { - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java index 079888155e..7aff5f51d0 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java @@ -1,10 +1,6 @@ package org.baeldung.persistence.multiple.model.user; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import javax.persistence.*; @Entity @Table(schema = "spring_jpa_user") diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java index 61904198f5..6fb9de4a47 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java @@ -1,15 +1,8 @@ package org.baeldung.persistence.multiple.model.user; +import javax.persistence.*; import java.util.List; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; - @Entity @Table(schema = "spring_jpa_user") public class User { diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java index aa2dfb5293..beaa51f5f9 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java @@ -8,7 +8,6 @@ import org.junit.runners.Suite; FooPaginationPersistenceIntegrationTest.class ,FooServicePersistenceIntegrationTest.class ,FooServiceSortingIntegrationTest.class - ,JpaMultipleDBIntegrationTest.class ,FooServiceSortingWitNullsManualIntegrationTest.class }) // @formatter:on public class PersistenceTestSuite { diff --git a/pom.xml b/pom.xml index 938315f5dc..be6029a946 100644 --- a/pom.xml +++ b/pom.xml @@ -398,7 +398,6 @@ jee-7 jhipster/jhipster-monolithic jjwt - jpa-storedprocedure jsf json-path json @@ -585,7 +584,6 @@ spring-security-thymeleaf persistence-modules/java-jdbi jersey - jersey-client-rx java-spi performance-tests twilio @@ -594,6 +592,7 @@ spring-webflux-amqp antlr maven-archetype + optaplanner apache-meecrowave spring-reactive-kotlin jnosql @@ -750,6 +749,7 @@ spring-data-elasticsearch spring-data-keyvalue spring-data-mongodb + spring-data-jpa persistence-modules/spring-data-neo4j persistence-modules/spring-data-redis spring-data-rest @@ -950,7 +950,6 @@ jgroups jee-7 jjwt - jpa-storedprocedure jsf json-path json @@ -1298,4 +1297,4 @@ 3.8 - + \ No newline at end of file diff --git a/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java b/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java index ff1fb87393..c5f63486fe 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java +++ b/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java @@ -13,7 +13,7 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter @Controller public class ResponseBodyEmitterController { - private ExecutorService nonBlockingService = Executors.newSingleThreadExecutor(); + private ExecutorService nonBlockingService = Executors.newCachedThreadPool(); @GetMapping(Constants.API_RBE) public ResponseEntity handleRbe() { diff --git a/spring-5-mvc/src/main/java/com/baeldung/web/SseEmitterController.java b/spring-5-mvc/src/main/java/com/baeldung/web/SseEmitterController.java index b11c93fb08..00113c5ff7 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/web/SseEmitterController.java +++ b/spring-5-mvc/src/main/java/com/baeldung/web/SseEmitterController.java @@ -1,12 +1,16 @@ package com.baeldung.web; -import com.baeldung.Constants; +import java.time.LocalTime; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; + import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter.SseEventBuilder; + +import com.baeldung.Constants; @Controller public class SseEmitterController { @@ -29,4 +33,27 @@ public class SseEmitterController { return emitter; } + @GetMapping("/stream-sse-mvc") + public SseEmitter streamSseMvc() { + SseEmitter emitter = new SseEmitter(); + ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor(); + + sseMvcExecutor.execute(() -> { + try { + for (int i = 0; true; i++) { + SseEventBuilder event = SseEmitter.event() + .data("SSE MVC - " + LocalTime.now() + .toString()) + .id(String.valueOf(i)) + .name("sse event - mvc"); + emitter.send(event); + Thread.sleep(1000); + } + } catch (Exception ex) { + emitter.completeWithError(ex); + } + }); + return emitter; + } + } diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index e81d3d8b79..5f455c3906 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -94,6 +94,12 @@ ${project-reactor-test} test + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + @@ -117,6 +123,7 @@ 1.0 4.1 3.1.6.RELEASE + 1.2.0 diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java new file mode 100644 index 0000000000..3997607ef0 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.reactive.serversentevents.consumer; + +import java.util.Collections; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; + +@SpringBootApplication +@EnableAsync +public class ConsumerSSEApplication { + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(ConsumerSSEApplication.class); + app.setDefaultProperties(Collections.singletonMap("server.port", "8082")); + app.run(args); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java new file mode 100644 index 0000000000..69a6bc396c --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java @@ -0,0 +1,83 @@ +package com.baeldung.reactive.serversentevents.consumer.controller; + +import java.time.LocalTime; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.MediaType; +import org.springframework.http.codec.ServerSentEvent; +import org.springframework.scheduling.annotation.Async; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClient; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@RestController +@RequestMapping("/sse-consumer") +public class ClientController { + + private static Logger logger = LoggerFactory.getLogger(ClientController.class); + private WebClient client = WebClient.create("http://localhost:8081/sse-server"); + + @GetMapping("/launch-sse-client") + public String launchSSEFromSSEWebClient() { + consumeSSE(); + return "LAUNCHED EVENT CLIENT!!! Check the logs..."; + } + + @GetMapping("/launch-flux-client") + public String launchcFluxFromSSEWebClient() { + consumeFlux(); + return "LAUNCHED EVENT CLIENT!!! Check the logs..."; + } + + @GetMapping("/launch-sse-from-flux-endpoint-client") + public String launchFluxFromFluxWebClient() { + consumeSSEFromFluxEndpoint(); + return "LAUNCHED EVENT CLIENT!!! Check the logs..."; + } + + @Async + public void consumeSSE() { + ParameterizedTypeReference> type = new ParameterizedTypeReference>() { + }; + + Flux> eventStream = client.get() + .uri("/stream-sse") + .retrieve() + .bodyToFlux(type); + + eventStream.subscribe(content -> logger.info("Current time: {} - Received SSE: name[{}], id [{}], content[{}] ", LocalTime.now(), content.event(), content.id(), content.data()), error -> logger.error("Error receiving SSE: {}", error), + () -> logger.info("Completed!!!")); + } + + @Async + public void consumeFlux() { + Flux stringStream = client.get() + .uri("/stream-flux") + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(String.class); + + stringStream.subscribe(content -> logger.info("Current time: {} - Received content: {} ", LocalTime.now(), content), error -> logger.error("Error retrieving content: {}", error), () -> logger.info("Completed!!!")); + } + + @Async + public void consumeSSEFromFluxEndpoint() { + ParameterizedTypeReference> type = new ParameterizedTypeReference>() { + }; + + Flux> eventStream = client.get() + .uri("/stream-flux") + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(type); + + eventStream.subscribe(content -> logger.info("Current time: {} - Received SSE: name[{}], id [{}], content[{}] ", LocalTime.now(), content.event(), content.id(), content.data()), error -> logger.error("Error receiving SSE: {}", error), + () -> logger.info("Completed!!!")); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java new file mode 100644 index 0000000000..2750e6616d --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.reactive.serversentevents.server; + +import java.util.Collections; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ServerSSEApplication { + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(ServerSSEApplication.class); + app.setDefaultProperties(Collections.singletonMap("server.port", "8081")); + app.run(args); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java new file mode 100644 index 0000000000..1ad8e848cf --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java @@ -0,0 +1,35 @@ +package com.baeldung.reactive.serversentevents.server.controllers; + +import java.time.Duration; +import java.time.LocalTime; + +import org.springframework.http.MediaType; +import org.springframework.http.codec.ServerSentEvent; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Flux; + +@RestController +@RequestMapping("/sse-server") +public class ServerController { + + @GetMapping("/stream-sse") + public Flux> streamEvents() { + return Flux.interval(Duration.ofSeconds(1)) + .map(sequence -> ServerSentEvent. builder() + .id(String.valueOf(sequence)) + .event("periodic-event") + .data("SSE - " + LocalTime.now() + .toString()) + .build()); + } + + @GetMapping(path = "/stream-flux", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux streamFlux() { + return Flux.interval(Duration.ofSeconds(1)) + .map(sequence -> "Flux - " + LocalTime.now() + .toString()); + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java new file mode 100644 index 0000000000..53f4a3b1bb --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java @@ -0,0 +1,49 @@ +package com.baeldung.reactive.serversentsevents; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(JUnitPlatform.class) +@SpringBootTest +public class ServiceSentEventLiveTest { + + private WebTestClient client = WebTestClient.bindToServer() + .baseUrl("http://localhost:8081/sse-server") + .build(); + + @Test + public void whenSSEEndpointIsCalled_thenEventStreamingBegins() { + + Executable sseStreamingCall = () -> client.get() + .uri("/stream-sse") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_EVENT_STREAM) + .expectBody(String.class); + + Assertions.assertThrows(IllegalStateException.class, sseStreamingCall, "Expected test to timeout and throw IllegalStateException, but it didn't"); + } + + @Test + public void whenFluxEndpointIsCalled_thenEventStreamingBegins() { + + Executable sseStreamingCall = () -> client.get() + .uri("/stream-flux") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_EVENT_STREAM) + .expectBody(String.class); + + Assertions.assertThrows(IllegalStateException.class, sseStreamingCall, "Expected test to timeout and throw IllegalStateException, but it didn't"); + } +} diff --git a/spring-boot-persistence/pom.xml b/spring-boot-persistence/pom.xml index a16d953581..08989edfa9 100644 --- a/spring-boot-persistence/pom.xml +++ b/spring-boot-persistence/pom.xml @@ -1,57 +1,75 @@ - - 4.0.0 + + + 4.0.0 + + com.baeldung + spring-boot-persistence + 0.1.0 + + + parent-boot-2 com.baeldung - spring-boot-persistence 0.0.1-SNAPSHOT - jar - spring-boot-persistence - This is a simple Spring Data Repositories test - - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - com.h2database - h2 - - - org.springframework.boot - spring-boot-starter - - - - - spring-boot-persistence - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-war-plugin - - - pl.project13.maven - git-commit-id-plugin - ${git-commit-id-plugin.version} - - - - - - 2.2.4 - - \ No newline at end of file + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.zaxxer + HikariCP + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.apache.tomcat + tomcat-jdbc + ${tomcat-jdbc.version} + + + mysql + mysql-connector-java + ${mysql-connector-java.version} + + + com.h2database + h2 + ${h2database.version} + runtime + + + + + UTF-8 + 1.8 + 8.0.12 + 9.0.10 + 1.4.197 + + + + spring-boot-persistence + + + src/main/resources + true + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java new file mode 100644 index 0000000000..ff37442cd4 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java @@ -0,0 +1,22 @@ +package com.baeldung.tomcatconnectionpool.application; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@SpringBootApplication +@EnableAutoConfiguration +@ComponentScan(basePackages={"com.baeldung.tomcatconnectionpool.application"}) +@EnableJpaRepositories(basePackages="com.baeldung.tomcatconnectionpool.application.repositories") +@EnableTransactionManagement +@EntityScan(basePackages="com.baeldung.tomcatconnectionpool.application.entities") +public class SpringBootConsoleApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootConsoleApplication.class); + } +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java new file mode 100644 index 0000000000..4003d5aca9 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java @@ -0,0 +1,53 @@ +package com.baeldung.tomcatconnectionpool.application.entities; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "customers") +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + @Column(name = "first_name") + private String firstName; + @Column(name = "last_name") + private String lastName; + + public Customer() {} + + public Customer(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public long getId() { + return id; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + @Override + public String toString() { + return "Customer{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + '}'; + } +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java new file mode 100644 index 0000000000..770906439c --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.tomcatconnectionpool.application.repositories; + +import com.baeldung.tomcatconnectionpool.application.entities.Customer; +import java.util.List; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CustomerRepository extends CrudRepository { + + List findByLastName(String lastName); +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java new file mode 100644 index 0000000000..9666bac5a5 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java @@ -0,0 +1,37 @@ +package com.baeldung.tomcatconnectionpool.application.runners; + +import com.baeldung.tomcatconnectionpool.application.entities.Customer; +import com.baeldung.tomcatconnectionpool.application.repositories.CustomerRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +@Component +public class CommandLineCrudRunner implements CommandLineRunner { + + private static final Logger logger = LoggerFactory.getLogger(CommandLineCrudRunner.class); + + @Autowired + private CustomerRepository customerRepository; + + @Override + public void run(String... args) throws Exception { + customerRepository.save(new Customer("John", "Doe")); + customerRepository.save(new Customer("Jennifer", "Wilson")); + + logger.info("Customers found with findAll():"); + customerRepository.findAll().forEach(c -> logger.info(c.toString())); + + logger.info("Customer found with findById(1L):"); + Customer customer = customerRepository.findById(1L) + .orElseGet(() -> new Customer("Non-existing customer", "")); + logger.info(customer.toString()); + + logger.info("Customer found with findByLastName('Wilson'):"); + customerRepository.findByLastName("Wilson").forEach(c -> { + logger.info(c.toString()); + }); + } +} diff --git a/spring-boot-persistence/src/main/resources/application.properties b/spring-boot-persistence/src/main/resources/application.properties index d0fb785fe8..303ce33c25 100644 --- a/spring-boot-persistence/src/main/resources/application.properties +++ b/spring-boot-persistence/src/main/resources/application.properties @@ -1,2 +1,16 @@ -spring.jpa.show-sql=true -spring.jpa.hibernate.ddl-auto=none \ No newline at end of file +spring.datasource.tomcat.initial-size=15 +spring.datasource.tomcat.max-wait=20000 +spring.datasource.tomcat.max-active=50 +spring.datasource.tomcat.max-idle=15 +spring.datasource.tomcat.min-idle=8 +spring.datasource.tomcat.default-auto-commit=true +spring.datasource.url=jdbc:h2:mem:test +spring.datasource.username=root +spring.datasource.password= +spring.datasource.driver-class-name=org.h2.Driver + +spring.jpa.show-sql=false +spring.jpa.hibernate.ddl-auto=update +spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect +spring.jpa.properties.hibernate.id.new_generator_mappings=false diff --git a/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java new file mode 100644 index 0000000000..c68e137fb0 --- /dev/null +++ b/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.tomcatconnectionpool.test.application; + +import javax.sql.DataSource; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit4.SpringRunner; +import static org.assertj.core.api.Assertions.*; +import org.springframework.boot.test.context.SpringBootTest; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringBootTomcatConnectionPoolIntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenTomcatConnectionPoolInstance_whenCheckedPoolClassName_thenCorrect() { + assertThat(dataSource.getClass().getName()).isEqualTo("org.apache.tomcat.jdbc.pool.DataSource"); + } +} diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index 5283a69c2d..18d292c8a1 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -44,6 +44,23 @@ org.springframework.boot spring-boot-starter-web + + + + org.springframework.security + spring-security-taglibs + + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + javax.servlet + jstl + org.springframework.boot diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java new file mode 100644 index 0000000000..dccbace106 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java @@ -0,0 +1,13 @@ +package com.baeldung.integrationtesting; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; + +@Configuration +@EnableGlobalMethodSecurity( + prePostEnabled = true, + securedEnabled = true) +public class MethodSecurityConfigurer extends GlobalMethodSecurityConfiguration { + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java new file mode 100644 index 0000000000..18469e4752 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.integrationtesting; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SecuredApplication { + + public static void main(String[] args) { + SpringApplication.run(SecuredApplication.class, args); + } + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java new file mode 100644 index 0000000000..495c358784 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java @@ -0,0 +1,21 @@ +package com.baeldung.integrationtesting; + +import java.util.Arrays; +import java.util.List; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SecuredController { + + @GetMapping("/public/hello") + public List publicHello() { + return Arrays.asList("Hello", "World", "from", "Public"); + } + + @GetMapping("/private/hello") + public List privateHello() { + return Arrays.asList("Hello", "World", "from", "Private"); + } + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java new file mode 100644 index 0000000000..25253f163a --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java @@ -0,0 +1,13 @@ +package com.baeldung.integrationtesting; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; + +@Service +public class SecuredService { + + @PreAuthorize("authenticated") + public String sayHelloSecured() { + return "Hello user."; + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java new file mode 100644 index 0000000000..32a48ce612 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java @@ -0,0 +1,31 @@ +package com.baeldung.integrationtesting; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("spring") + .password("secret") + .roles("USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/private/**") + .hasRole("USER") + .antMatchers("/public/**") + .permitAll() + .and() + .httpBasic(); + } + + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java new file mode 100644 index 0000000000..eca093a76f --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java @@ -0,0 +1,14 @@ +package com.baeldung.springsecuritytaglibs; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/") +public class HomeController { + + @RequestMapping + public String home() { + return "home"; + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java new file mode 100644 index 0000000000..397ea47f96 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java @@ -0,0 +1,9 @@ +package com.baeldung.springsecuritytaglibs; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +@PropertySource("classpath:application-taglibs.properties") +public class SpringBootSecurityTagLibsApplication { +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java new file mode 100644 index 0000000000..665dd0bce9 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.springsecuritytaglibs.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SpringBootSecurityTagLibsConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("testUser") + .password("password") + .roles("ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http.csrf() + .and() + .authorizeRequests() + .antMatchers("/userManagement").hasRole("ADMIN") + .anyRequest().permitAll().and().httpBasic(); + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-boot-security/src/main/resources/application-taglibs.properties b/spring-boot-security/src/main/resources/application-taglibs.properties new file mode 100644 index 0000000000..218868405f --- /dev/null +++ b/spring-boot-security/src/main/resources/application-taglibs.properties @@ -0,0 +1,3 @@ +#jsp config +spring.mvc.view.prefix: /WEB-INF/views/ +spring.mvc.view.suffix: .jsp diff --git a/spring-boot-security/src/main/resources/application.properties b/spring-boot-security/src/main/resources/application.properties index c2b8d70dc6..e776132359 100644 --- a/spring-boot-security/src/main/resources/application.properties +++ b/spring-boot-security/src/main/resources/application.properties @@ -1,4 +1,4 @@ #spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration #security.user.password=password #security.oauth2.client.client-id=client -#security.oauth2.client.client-secret=secret +#security.oauth2.client.client-secret=secret \ No newline at end of file diff --git a/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp new file mode 100644 index 0000000000..80ecd61cb5 --- /dev/null +++ b/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp @@ -0,0 +1,38 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib prefix="sec" + uri="http://www.springframework.org/security/tags"%> + + + + + +Home Page + + + + Login + + + + Logout + + + +

+ Welcome back, +

+ + Manage Users + +
+ + Text Field:
+ + + + Manage Users + +
+ + \ No newline at end of file diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java new file mode 100644 index 0000000000..c224058155 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.integrationtesting; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class SecuredControllerRestTemplateIntegrationTest { + + @Autowired + private TestRestTemplate template; + + @Test + public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { + ResponseEntity result = template.getForEntity("/private/hello", String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); + } + + @Test + public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + ResponseEntity result = template.withBasicAuth("spring", "secret") + .getForEntity("/private/hello", String.class); + assertEquals(HttpStatus.OK, result.getStatusCode()); + } + +} diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java new file mode 100644 index 0000000000..ce9e6de917 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.integrationtesting; + +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class SecuredControllerSpringBootIntegrationTest { + + @Autowired + private WebApplicationContext context; + + private MockMvc mvc; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + @Test + public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { + mvc.perform(get("/private/hello") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isUnauthorized()); + } + + @WithMockUser("spring") + @Test + public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + mvc.perform(get("/private/hello") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + +} diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java new file mode 100644 index 0000000000..7281648856 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.integrationtesting; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.integrationtesting.SecuredController; + +@RunWith(SpringRunner.class) +@WebMvcTest(SecuredController.class) +public class SecuredControllerWebMvcIntegrationTest { + + @Autowired + private MockMvc mvc; + + @Test + public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { + mvc.perform(get("/private/hello") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isUnauthorized()); + } + + @WithMockUser(value = "spring") + @Test + public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + mvc.perform(get("/private/hello") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + +} diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java new file mode 100644 index 0000000000..816b05bd5a --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.integrationtesting; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.integrationtesting.SecuredService; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SecuredMethodSpringBootIntegrationTest { + + @Autowired + private SecuredService service; + + @Test(expected = AuthenticationCredentialsNotFoundException.class) + public void givenUnauthenticated_whenCallService_thenThrowsException() { + service.sayHelloSecured(); + } + + @WithMockUser(username="spring") + @Test + public void givenAuthenticated_whenCallServiceWithSecured_thenOk() { + assertThat(service.sayHelloSecured()).isNotBlank(); + } +} diff --git a/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java new file mode 100644 index 0000000000..0585c06a59 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.springsecuritytaglibs; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class) +public class HomeControllerUnitTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void whenUserIsAuthenticatedThenAuthenticatedSectionsShowOnSite() throws Exception { + String body = this.restTemplate.withBasicAuth("testUser", "password") + .getForEntity("/", String.class) + .getBody(); + + // test + assertFalse(body.contains("Login")); + + // test + assertTrue(body.contains("Logout")); + + // test + assertTrue(body.contains("Manage Users")); + + // test + assertTrue(body.contains("testUser")); + + // test + assertTrue(body.contains("")); + + // test + assertTrue(body.contains(" + assertTrue(body.contains("")); + } + + @Test + public void whenUserIsNotAuthenticatedThenOnlyAnonymousSectionsShowOnSite() throws Exception { + String body = this.restTemplate.getForEntity("/", String.class) + .getBody(); + + // test + assertTrue(body.contains("Login")); + + // test + assertFalse(body.contains("Logout")); + } +} diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 5d1170b905..f11ea1b7ed 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -20,7 +20,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Boot and Togglz Aspect](http://www.baeldung.com/spring-togglz) - [Getting Started with GraphQL and Spring Boot](http://www.baeldung.com/spring-graphql) - [Guide to Spring Type Conversions](http://www.baeldung.com/spring-type-conversions) -- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) - [An Introduction to Kong](http://www.baeldung.com/kong) - [Spring Boot Customize Whitelabel Error Page](http://www.baeldung.com/spring-boot-custom-error-page) - [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class) diff --git a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java index cba504b6c6..7335af2616 100644 --- a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java @@ -24,8 +24,6 @@ public interface UserRepository extends JpaRepository { Optional findOneByName(String name); - Stream findAllByName(String name); - @Async CompletableFuture findOneByStatus(Integer status); diff --git a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java index 72d204820e..04bb1170f8 100644 --- a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java @@ -52,30 +52,6 @@ public class UserRepositoryIntegrationTest { .getName()).isEqualTo(USER_NAME_ADAM); } - @Test - @Transactional - public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - userRepository.save(user3); - - User user4 = new User(); - user4.setName("SAMPLE"); - userRepository.save(user4); - - try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { - assertThat(foundUsersStream.count()).isEqualTo(3l); - } - } - @Test public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException { User user = new User(); diff --git a/spring-data-jpa/README.md b/spring-data-jpa/README.md new file mode 100644 index 0000000000..f54764e05c --- /dev/null +++ b/spring-data-jpa/README.md @@ -0,0 +1,22 @@ +========= + +## Spring Data JPA Example Project + +### Relevant Articles: +- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) +- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories) +- [Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) +- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) +- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) +- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) +- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) + +### Eclipse Config +After importing the project into Eclipse, you may see the following error: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator + diff --git a/spring-data-jpa/pom.xml b/spring-data-jpa/pom.xml index 517d43bd0e..c4893df759 100644 --- a/spring-data-jpa/pom.xml +++ b/spring-data-jpa/pom.xml @@ -17,10 +17,30 @@ org.springframework.boot spring-boot-starter-data-jpa
+ + org.hibernate + hibernate-ehcache + + + org.hibernate + hibernate-envers + com.h2database h2 + + + org.springframework.security + spring-security-test + test + + + + com.google.guava + guava + 21.0 + \ No newline at end of file diff --git a/spring-data-jpa/src/main/java/com/baeldung/Application.java b/spring-data-jpa/src/main/java/com/baeldung/Application.java index 43888c2d67..4e14f94311 100644 --- a/spring-data-jpa/src/main/java/com/baeldung/Application.java +++ b/spring-data-jpa/src/main/java/com/baeldung/Application.java @@ -1,14 +1,17 @@ package com.baeldung; +import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ApplicationContext; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication +@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class) public class Application { - private static ApplicationContext applicationContext; public static void main(String[] args) { - applicationContext = SpringApplication.run(Application.class, args); + SpringApplication.run(Application.class, args); } + } diff --git a/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java new file mode 100644 index 0000000000..16407e510a --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java @@ -0,0 +1,102 @@ +package com.baeldung.config; + +import com.baeldung.services.IBarService; +import com.baeldung.services.impl.BarSpringDataJpaService; +import com.google.common.base.Preconditions; +import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; +import com.baeldung.services.IFooService; +import com.baeldung.services.impl.FooService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.*; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; +import java.util.Properties; + +@Configuration +@ComponentScan({"com.baeldung.dao", "com.baeldung.services"}) +@EnableTransactionManagement +@EnableJpaRepositories(basePackages = {"com.baeldung.dao"}, repositoryBaseClass = ExtendedRepositoryImpl.class) +@EnableJpaAuditing +@PropertySource("classpath:persistence.properties") +public class PersistenceConfiguration { + + @Autowired + private Environment env; + + public PersistenceConfiguration() { + super(); + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(dataSource()); + emf.setPackagesToScan("com.baeldung.domain"); + + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + emf.setJpaVendorAdapter(vendorAdapter); + emf.setJpaProperties(hibernateProperties()); + + return emf; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + @Bean + public IBarService barSpringDataJpaService() { + return new BarSpringDataJpaService(); + } + + @Bean + public IFooService fooService() { + return new FooService(); + } + + private final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + + hibernateProperties.setProperty("hibernate.show_sql", "true"); + // hibernateProperties.setProperty("hibernate.format_sql", "true"); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + + // Envers properties + hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); + + return hibernateProperties; + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java similarity index 84% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java rename to spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java index 13f8f4b27c..207fba9bc5 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java +++ b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java @@ -1,9 +1,6 @@ -package org.baeldung.config; - -import java.util.HashMap; - -import javax.sql.DataSource; +package com.baeldung.config; +import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -16,16 +13,17 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; -import com.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.HashMap; @Configuration -@PropertySource({ "classpath:persistence-multiple-db.properties" }) -@EnableJpaRepositories(basePackages = "org.baeldung.persistence.multiple.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") -public class ProductConfig { +@PropertySource({"classpath:persistence-multiple-db.properties"}) +@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") +public class PersistenceProductConfiguration { @Autowired private Environment env; - public ProductConfig() { + public PersistenceProductConfiguration() { super(); } @@ -35,7 +33,7 @@ public class ProductConfig { public LocalContainerEntityManagerFactoryBean productEntityManager() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(productDataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.multiple.model.product" }); + em.setPackagesToScan("com.baeldung.domain.product"); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java similarity index 85% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java rename to spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java index 8e85f5d8e0..dd32477755 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java +++ b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java @@ -1,9 +1,6 @@ -package org.baeldung.config; - -import java.util.HashMap; - -import javax.sql.DataSource; +package com.baeldung.config; +import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -17,16 +14,17 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; -import com.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.HashMap; @Configuration -@PropertySource({ "classpath:persistence-multiple-db.properties" }) -@EnableJpaRepositories(basePackages = "org.baeldung.persistence.multiple.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") -public class UserConfig { +@PropertySource({"classpath:persistence-multiple-db.properties"}) +@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") +public class PersistenceUserConfiguration { @Autowired private Environment env; - public UserConfig() { + public PersistenceUserConfiguration() { super(); } @@ -37,7 +35,7 @@ public class UserConfig { public LocalContainerEntityManagerFactoryBean userEntityManager() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(userDataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.multiple.model.user" }); + em.setPackagesToScan("com.baeldung.domain.user"); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/IFooDao.java b/spring-data-jpa/src/main/java/com/baeldung/dao/IFooDao.java new file mode 100644 index 0000000000..bb3c229945 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/IFooDao.java @@ -0,0 +1,12 @@ +package com.baeldung.dao; + +import com.baeldung.domain.Foo; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface IFooDao extends JpaRepository { + + @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)") + Foo retrieveByName(@Param("name") String name); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/repository/ArticleRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ArticleRepository.java similarity index 95% rename from spring-data-jpa/src/main/java/com/baeldung/repository/ArticleRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ArticleRepository.java index 4e1b109430..8402c099d9 100644 --- a/spring-data-jpa/src/main/java/com/baeldung/repository/ArticleRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ArticleRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.repository; +package com.baeldung.dao.repositories; import com.baeldung.domain.Article; import org.springframework.data.jpa.repository.JpaRepository; diff --git a/spring-data-jpa/src/main/java/com/baeldung/repository/CustomItemRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java similarity index 83% rename from spring-data-jpa/src/main/java/com/baeldung/repository/CustomItemRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java index 91eddb800a..ba077ccf1f 100644 --- a/spring-data-jpa/src/main/java/com/baeldung/repository/CustomItemRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java @@ -1,15 +1,15 @@ -package com.baeldung.repository; - -import org.springframework.stereotype.Repository; - -import com.baeldung.domain.Item; - -@Repository -public interface CustomItemRepository { - - void deleteCustom(Item entity); - - Item findItemById(Long id); - - void findThenDelete(Long id); -} +package com.baeldung.dao.repositories; + +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.Item; + +@Repository +public interface CustomItemRepository { + + void deleteCustom(Item entity); + + Item findItemById(Long id); + + void findThenDelete(Long id); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/repository/CustomItemTypeRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemTypeRepository.java similarity index 82% rename from spring-data-jpa/src/main/java/com/baeldung/repository/CustomItemTypeRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemTypeRepository.java index 77bbf294a0..81ebdf3fda 100644 --- a/spring-data-jpa/src/main/java/com/baeldung/repository/CustomItemTypeRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemTypeRepository.java @@ -1,13 +1,13 @@ -package com.baeldung.repository; - -import org.springframework.stereotype.Repository; - -import com.baeldung.domain.ItemType; - -@Repository -public interface CustomItemTypeRepository { - - void deleteCustom(ItemType entity); - - void findThenDelete(Long id); -} +package com.baeldung.dao.repositories; + +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.ItemType; + +@Repository +public interface CustomItemTypeRepository { + + void deleteCustom(ItemType entity); + + void findThenDelete(Long id); +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedRepository.java similarity index 69% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedRepository.java index 9c9c12029a..9e82f02fa6 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.extended.persistence.dao; +package com.baeldung.dao.repositories; import java.io.Serializable; import java.util.List; @@ -8,5 +8,7 @@ import org.springframework.data.repository.NoRepositoryBean; @NoRepositoryBean public interface ExtendedRepository extends JpaRepository { - public List findByAttributeContainsText(String attributeName, String text); + + List findByAttributeContainsText(String attributeName, String text); + } diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedStudentRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedStudentRepository.java new file mode 100644 index 0000000000..199e4e5ff6 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedStudentRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.domain.Student; + +public interface ExtendedStudentRepository extends ExtendedRepository { +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/IBarCrudRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/IBarCrudRepository.java new file mode 100644 index 0000000000..54a7d77691 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/IBarCrudRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.domain.Bar; +import org.springframework.data.repository.CrudRepository; + +import java.io.Serializable; + +public interface IBarCrudRepository extends CrudRepository { + // +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/repository/ItemTypeRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ItemTypeRepository.java similarity index 87% rename from spring-data-jpa/src/main/java/com/baeldung/repository/ItemTypeRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ItemTypeRepository.java index c3146aa297..2af83bc322 100644 --- a/spring-data-jpa/src/main/java/com/baeldung/repository/ItemTypeRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ItemTypeRepository.java @@ -1,10 +1,10 @@ -package com.baeldung.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.domain.ItemType; - -@Repository -public interface ItemTypeRepository extends JpaRepository, CustomItemTypeRepository, CustomItemRepository { -} +package com.baeldung.dao.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.ItemType; + +@Repository +public interface ItemTypeRepository extends JpaRepository, CustomItemTypeRepository, CustomItemRepository { +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/repository/LocationRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/LocationRepository.java similarity index 86% rename from spring-data-jpa/src/main/java/com/baeldung/repository/LocationRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/LocationRepository.java index f119ff916b..27bbe27af0 100644 --- a/spring-data-jpa/src/main/java/com/baeldung/repository/LocationRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/LocationRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.repository; +package com.baeldung.dao.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; diff --git a/spring-data-jpa/src/main/java/com/baeldung/repository/ReadOnlyLocationRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ReadOnlyLocationRepository.java similarity index 87% rename from spring-data-jpa/src/main/java/com/baeldung/repository/ReadOnlyLocationRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ReadOnlyLocationRepository.java index 2107712484..8f68cdbbe5 100644 --- a/spring-data-jpa/src/main/java/com/baeldung/repository/ReadOnlyLocationRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ReadOnlyLocationRepository.java @@ -1,15 +1,15 @@ -package com.baeldung.repository; - -import java.util.Optional; - -import org.springframework.data.repository.Repository; - -import com.baeldung.domain.Location; - -@org.springframework.stereotype.Repository -public interface ReadOnlyLocationRepository extends Repository { - - Optional findById(Long id); - - Location save(Location location); -} +package com.baeldung.dao.repositories; + +import java.util.Optional; + +import org.springframework.data.repository.Repository; + +import com.baeldung.domain.Location; + +@org.springframework.stereotype.Repository +public interface ReadOnlyLocationRepository extends Repository { + + Optional findById(Long id); + + Location save(Location location); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/repository/StoreRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/StoreRepository.java similarity index 87% rename from spring-data-jpa/src/main/java/com/baeldung/repository/StoreRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/StoreRepository.java index 939ca1dacb..9318c32ee9 100644 --- a/spring-data-jpa/src/main/java/com/baeldung/repository/StoreRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/StoreRepository.java @@ -1,13 +1,13 @@ -package com.baeldung.repository; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.domain.Store; - -@Repository -public interface StoreRepository extends JpaRepository { - List findStoreByLocationId(Long locationId); -} +package com.baeldung.dao.repositories; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.Store; + +@Repository +public interface StoreRepository extends JpaRepository { + List findStoreByLocationId(Long locationId); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/repository/impl/CustomItemRepositoryImpl.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java similarity index 85% rename from spring-data-jpa/src/main/java/com/baeldung/repository/impl/CustomItemRepositoryImpl.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java index 44492a8f35..53def88af0 100644 --- a/spring-data-jpa/src/main/java/com/baeldung/repository/impl/CustomItemRepositoryImpl.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java @@ -1,32 +1,32 @@ -package com.baeldung.repository.impl; - -import javax.persistence.EntityManager; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; - -import com.baeldung.domain.Item; -import com.baeldung.repository.CustomItemRepository; - -@Repository -public class CustomItemRepositoryImpl implements CustomItemRepository { - - @Autowired - private EntityManager entityManager; - - @Override - public void deleteCustom(Item item) { - entityManager.remove(item); - } - - @Override - public Item findItemById(Long id) { - return entityManager.find(Item.class, id); - } - - @Override - public void findThenDelete(Long id) { - final Item item = entityManager.find(Item.class, id); - entityManager.remove(item); - } -} +package com.baeldung.dao.repositories.impl; + +import javax.persistence.EntityManager; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.Item; +import com.baeldung.dao.repositories.CustomItemRepository; + +@Repository +public class CustomItemRepositoryImpl implements CustomItemRepository { + + @Autowired + private EntityManager entityManager; + + @Override + public void deleteCustom(Item item) { + entityManager.remove(item); + } + + @Override + public Item findItemById(Long id) { + return entityManager.find(Item.class, id); + } + + @Override + public void findThenDelete(Long id) { + final Item item = entityManager.find(Item.class, id); + entityManager.remove(item); + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/repository/impl/CustomItemTypeRepositoryImpl.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemTypeRepositoryImpl.java similarity index 86% rename from spring-data-jpa/src/main/java/com/baeldung/repository/impl/CustomItemTypeRepositoryImpl.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemTypeRepositoryImpl.java index 594fd24ea9..2b49f2380c 100644 --- a/spring-data-jpa/src/main/java/com/baeldung/repository/impl/CustomItemTypeRepositoryImpl.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemTypeRepositoryImpl.java @@ -1,31 +1,31 @@ -package com.baeldung.repository.impl; - -import javax.persistence.EntityManager; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; - -import com.baeldung.domain.ItemType; -import com.baeldung.repository.CustomItemTypeRepository; - -@Repository -public class CustomItemTypeRepositoryImpl implements CustomItemTypeRepository { - - private static final Logger LOGGER = LoggerFactory.getLogger(CustomItemTypeRepositoryImpl.class); - - @Autowired - private EntityManager entityManager; - - @Override - public void deleteCustom(ItemType itemType) { - entityManager.remove(itemType); - } - - @Override - public void findThenDelete(Long id) { - ItemType itemTypeToDelete = entityManager.find(ItemType.class, id); - entityManager.remove(itemTypeToDelete); - } -} +package com.baeldung.dao.repositories.impl; + +import javax.persistence.EntityManager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.ItemType; +import com.baeldung.dao.repositories.CustomItemTypeRepository; + +@Repository +public class CustomItemTypeRepositoryImpl implements CustomItemTypeRepository { + + private static final Logger LOGGER = LoggerFactory.getLogger(CustomItemTypeRepositoryImpl.class); + + @Autowired + private EntityManager entityManager; + + @Override + public void deleteCustom(ItemType itemType) { + entityManager.remove(itemType); + } + + @Override + public void findThenDelete(Long id) { + ItemType itemTypeToDelete = entityManager.find(ItemType.class, id); + entityManager.remove(itemTypeToDelete); + } +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/ExtendedRepositoryImpl.java similarity index 93% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/ExtendedRepositoryImpl.java index 7ed652dc4d..f6f06efb51 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/ExtendedRepositoryImpl.java @@ -1,4 +1,4 @@ -package org.baeldung.extended.persistence.dao; +package com.baeldung.dao.repositories.impl; import java.io.Serializable; import java.util.List; @@ -10,6 +10,7 @@ import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.transaction.Transactional; +import com.baeldung.dao.repositories.ExtendedRepository; import org.springframework.data.jpa.repository.support.JpaEntityInformation; import org.springframework.data.jpa.repository.support.SimpleJpaRepository; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java similarity index 54% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java index bad0170a3a..7044d57e53 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.multiple.dao.product; +package com.baeldung.dao.repositories.product; -import org.baeldung.persistence.multiple.model.product.Product; +import com.baeldung.domain.product.Product; import org.springframework.data.jpa.repository.JpaRepository; public interface ProductRepository extends JpaRepository { diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/PossessionRepository.java similarity index 55% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/PossessionRepository.java index 34913632d8..f0eeb475c1 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/PossessionRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.multiple.dao.user; +package com.baeldung.dao.repositories.user; -import org.baeldung.persistence.multiple.model.user.Possession; +import com.baeldung.domain.user.Possession; import org.springframework.data.jpa.repository.JpaRepository; public interface PossessionRepository extends JpaRepository { diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/repository/UserRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java similarity index 74% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/repository/UserRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java index eadac9a0d7..5bb0232e4a 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/repository/UserRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.repository; +package com.baeldung.dao.repositories.user; -import org.baeldung.persistence.model.User; +import com.baeldung.domain.user.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -8,24 +8,25 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.List; +import java.util.stream.Stream; -@Repository("userRepository") public interface UserRepository extends JpaRepository { + Stream findAllByName(String name); + @Query("SELECT u FROM User u WHERE u.status = 1") Collection findAllActiveUsers(); - @Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true) + @Query(value = "SELECT * FROM USERS.USERS u WHERE u.status = 1", nativeQuery = true) Collection findAllActiveUsersNative(); @Query("SELECT u FROM User u WHERE u.status = ?1") User findUserByStatus(Integer status); - @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) + @Query(value = "SELECT * FROM USERS.Users u WHERE u.status = ?1", nativeQuery = true) User findUserByStatusNative(Integer status); @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") @@ -34,7 +35,7 @@ public interface UserRepository extends JpaRepository { @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); - @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) + @Query(value = "SELECT * FROM USERS.Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") @@ -46,7 +47,7 @@ public interface UserRepository extends JpaRepository { @Query("SELECT u FROM User u WHERE u.name like :name%") User findUserByNameLikeNamedParam(@Param("name") String name); - @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) + @Query(value = "SELECT * FROM USERS.users u WHERE u.name LIKE ?1%", nativeQuery = true) User findUserByNameLikeNative(String name); @Query(value = "SELECT u FROM User u") @@ -55,7 +56,7 @@ public interface UserRepository extends JpaRepository { @Query(value = "SELECT u FROM User u ORDER BY id") Page findAllUsersWithPagination(Pageable pageable); - @Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) + @Query(value = "SELECT * FROM USERS.Users ORDER BY id", countQuery = "SELECT count(*) FROM USERS.Users", nativeQuery = true) Page findAllUsersWithPaginationNative(Pageable pageable); @Modifying @@ -63,7 +64,6 @@ public interface UserRepository extends JpaRepository { int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); @Modifying - @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) + @Query(value = "UPDATE USERS.Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) int updateUserSetStatusForNameNative(Integer status, String name); - } diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Bar.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Bar.java new file mode 100644 index 0000000000..efd297bafc --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Bar.java @@ -0,0 +1,220 @@ +package com.baeldung.domain; + +import com.google.common.collect.Sets; +import org.hibernate.annotations.OrderBy; +import org.hibernate.envers.Audited; +import org.jboss.logging.Logger; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; +import java.util.Set; + +@Entity +@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") +@Audited +@EntityListeners(AuditingEntityListener.class) +public class Bar implements Serializable { + + private static Logger logger = Logger.getLogger(Bar.class); + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private int id; + + @Column(name = "name") + private String name; + @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @OrderBy(clause = "NAME DESC") + // @NotAudited + private Set fooSet = Sets.newHashSet(); + @Column(name = "operation") + private String operation; + @Column(name = "timestamp") + private long timestamp; + @Column(name = "created_date", updatable = false, nullable = false) + @CreatedDate + private long createdDate; + @Column(name = "modified_date") + @LastModifiedDate + private long modifiedDate; + @Column(name = "created_by") + @CreatedBy + private String createdBy; + @Column(name = "modified_by") + @LastModifiedBy + private String modifiedBy; + + public Bar() { + super(); + } + + public Bar(final String name) { + super(); + + this.name = name; + } + + public Set getFooSet() { + return fooSet; + } + + // API + + public void setFooSet(final Set fooSet) { + this.fooSet = fooSet; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public OPERATION getOperation() { + return OPERATION.parse(operation); + } + + public void setOperation(final String operation) { + this.operation = operation; + } + + public void setOperation(final OPERATION operation) { + this.operation = operation.getValue(); + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(final long timestamp) { + this.timestamp = timestamp; + } + + public long getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(final long createdDate) { + this.createdDate = createdDate; + } + + public long getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(final long modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(final String createdBy) { + this.createdBy = createdBy; + } + + public String getModifiedBy() { + return modifiedBy; + } + + public void setModifiedBy(final String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Bar other = (Bar) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Bar [name=").append(name).append("]"); + return builder.toString(); + } + + @PrePersist + public void onPrePersist() { + logger.info("@PrePersist"); + audit(OPERATION.INSERT); + } + + @PreUpdate + public void onPreUpdate() { + logger.info("@PreUpdate"); + audit(OPERATION.UPDATE); + } + + @PreRemove + public void onPreRemove() { + logger.info("@PreRemove"); + audit(OPERATION.DELETE); + } + + private void audit(final OPERATION operation) { + setOperation(operation); + setTimestamp((new Date()).getTime()); + } + + public enum OPERATION { + INSERT, UPDATE, DELETE; + private String value; + + OPERATION() { + value = toString(); + } + + public static OPERATION parse(final String value) { + OPERATION operation = null; + for (final OPERATION op : OPERATION.values()) { + if (op.getValue().equals(value)) { + operation = op; + break; + } + } + return operation; + } + + public String getValue() { + return value; + } + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Foo.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Foo.java new file mode 100644 index 0000000000..ef88840746 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Foo.java @@ -0,0 +1,94 @@ +package com.baeldung.domain; + +import org.hibernate.envers.Audited; + +import javax.persistence.*; +import java.io.Serializable; + +@NamedNativeQueries({@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class)}) +@Entity +@Audited +// @Proxy(lazy = false) +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; + + @Column(name = "name", nullable = false) + private String name; + + @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "BAR_ID") + private Bar bar = new Bar(); + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + this.name = name; + } + + // + + public Bar getBar() { + return bar; + } + + public void setBar(final Bar bar) { + this.bar = bar; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + // + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/KVTag.java b/spring-data-jpa/src/main/java/com/baeldung/domain/KVTag.java new file mode 100644 index 0000000000..b3e7d78b30 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/KVTag.java @@ -0,0 +1,34 @@ +package com.baeldung.domain; + +import javax.persistence.Embeddable; + +@Embeddable +public class KVTag { + private String key; + private String value; + + public KVTag() { + } + + public KVTag(String key, String value) { + super(); + this.key = key; + this.value = value; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/SkillTag.java b/spring-data-jpa/src/main/java/com/baeldung/domain/SkillTag.java new file mode 100644 index 0000000000..1f2778c589 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/SkillTag.java @@ -0,0 +1,30 @@ +package com.baeldung.domain; + +import javax.persistence.Embeddable; + +@Embeddable +public class SkillTag { + private String name; + private int value; + + public SkillTag() { + } + + public SkillTag(String name, int value) { + super(); + this.name = name; + this.value = value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public String getName() { + return name; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Student.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Student.java new file mode 100644 index 0000000000..bd7eaeb24b --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Student.java @@ -0,0 +1,74 @@ +package com.baeldung.domain; + +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.Id; +import java.util.ArrayList; +import java.util.List; + +@Entity +public class Student { + + @Id + private long id; + private String name; + + @ElementCollection + private List tags = new ArrayList<>(); + + @ElementCollection + private List skillTags = new ArrayList<>(); + + @ElementCollection + private List kvTags = new ArrayList<>(); + + public Student() { + } + + public Student(long id, String name) { + super(); + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags.addAll(tags); + } + + public List getSkillTags() { + return skillTags; + } + + public void setSkillTags(List skillTags) { + this.skillTags.addAll(skillTags); + } + + public List getKVTags() { + return this.kvTags; + } + + public void setKVTags(List kvTags) { + this.kvTags.addAll(kvTags); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java b/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java similarity index 90% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java rename to spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java index 8490ed397d..42e6dd8f45 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java @@ -1,11 +1,11 @@ -package org.baeldung.persistence.multiple.model.product; +package com.baeldung.domain.product; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity -@Table(schema = "spring_jpa_product") +@Table(schema = "products") public class Product { @Id diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java b/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java new file mode 100644 index 0000000000..614e13df36 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java @@ -0,0 +1,86 @@ +package com.baeldung.domain.user; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(schema = "users") +public class Possession { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + public Possession() { + super(); + } + + public Possession(final String name) { + super(); + + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + (int) (id ^ (id >>> 32)); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Possession other = (Possession) obj; + if (id != other.id) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java b/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java new file mode 100644 index 0000000000..3a8b617d9a --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java @@ -0,0 +1,86 @@ +package com.baeldung.domain.user; + +import javax.persistence.*; +import java.util.List; + +@Entity +@Table(name = "users", schema = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + private String name; + private int age; + @Column(unique = true, nullable = false) + private String email; + private Integer status; + @OneToMany + List possessionList; + + public User() { + super(); + } + + public User(String name, String email, Integer status) { + this.name = name; + this.email = email; + this.status = status; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(final String email) { + this.email = email; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public int getAge() { + return age; + } + + public void setAge(final int age) { + this.age = age; + } + + public List getPossessionList() { + return possessionList; + } + + public void setPossessionList(List possessionList) { + this.possessionList = possessionList; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [name=").append(name).append(", id=").append(id).append("]"); + return builder.toString(); + } + +} \ No newline at end of file diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/IBarService.java b/spring-data-jpa/src/main/java/com/baeldung/services/IBarService.java new file mode 100644 index 0000000000..7e127488db --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/IBarService.java @@ -0,0 +1,7 @@ +package com.baeldung.services; + +import com.baeldung.domain.Bar; + +public interface IBarService extends IOperations { + // +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/IFooService.java b/spring-data-jpa/src/main/java/com/baeldung/services/IFooService.java new file mode 100644 index 0000000000..7e16ace5b6 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/IFooService.java @@ -0,0 +1,13 @@ +package com.baeldung.services; + +import com.baeldung.domain.Foo; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +public interface IFooService extends IOperations { + + Foo retrieveByName(String name); + + Page findPaginated(Pageable pageable); + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/IOperations.java b/spring-data-jpa/src/main/java/com/baeldung/services/IOperations.java new file mode 100644 index 0000000000..d50d465639 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/IOperations.java @@ -0,0 +1,26 @@ +package com.baeldung.services; + +import org.springframework.data.domain.Page; + +import java.io.Serializable; +import java.util.List; + +public interface IOperations { + + T findOne(final long id); + + List findAll(); + + Page findPaginated(int page, int size); + + // write + + T create(final T entity); + + T update(final T entity); + + void delete(final T entity); + + void deleteById(final long entityId); + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractService.java new file mode 100644 index 0000000000..708524225b --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractService.java @@ -0,0 +1,61 @@ +package com.baeldung.services.impl; + +import com.baeldung.services.IOperations; +import com.google.common.collect.Lists; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.transaction.annotation.Transactional; + +import java.io.Serializable; +import java.util.List; + +@Transactional +public abstract class AbstractService implements IOperations { + + // read - one + + @Override + @Transactional(readOnly = true) + public T findOne(final long id) { + return getDao().findById(id).orElse(null); + } + + // read - all + + @Override + @Transactional(readOnly = true) + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public Page findPaginated(final int page, final int size) { + return getDao().findAll(new PageRequest(page, size)); + } + + // write + + @Override + public T create(final T entity) { + return getDao().save(entity); + } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(entityId); + } + + protected abstract PagingAndSortingRepository getDao(); + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractSpringDataJpaService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractSpringDataJpaService.java new file mode 100644 index 0000000000..28c86bee28 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractSpringDataJpaService.java @@ -0,0 +1,45 @@ +package com.baeldung.services.impl; + +import com.baeldung.services.IOperations; +import com.google.common.collect.Lists; +import org.springframework.data.repository.CrudRepository; +import org.springframework.transaction.annotation.Transactional; + +import java.io.Serializable; +import java.util.List; + +@Transactional(value = "transactionManager") +public abstract class AbstractSpringDataJpaService implements IOperations { + + @Override + public T findOne(final long id) { + return getDao().findById(id).orElse(null); + } + + @Override + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public T create(final T entity) { + return getDao().save(entity); + } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(entityId); + } + + protected abstract CrudRepository getDao(); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/BarSpringDataJpaService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/BarSpringDataJpaService.java new file mode 100644 index 0000000000..ca3e5f868d --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/BarSpringDataJpaService.java @@ -0,0 +1,30 @@ +package com.baeldung.services.impl; + +import com.baeldung.domain.Bar; +import com.baeldung.dao.repositories.IBarCrudRepository; +import com.baeldung.services.IBarService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.repository.CrudRepository; + +import java.io.Serializable; + +public class BarSpringDataJpaService extends AbstractSpringDataJpaService implements IBarService { + + @Autowired + private IBarCrudRepository dao; + + public BarSpringDataJpaService() { + super(); + } + + @Override + protected CrudRepository getDao() { + return dao; + } + + @Override + public Page findPaginated(int page, int size) { + throw new UnsupportedOperationException("Not implemented yet"); + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/FooService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/FooService.java new file mode 100644 index 0000000000..319ab3a825 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/FooService.java @@ -0,0 +1,54 @@ +package com.baeldung.services.impl; + +import com.google.common.collect.Lists; +import com.baeldung.dao.IFooDao; +import com.baeldung.domain.Foo; +import com.baeldung.services.IFooService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class FooService extends AbstractService implements IFooService { + + @Autowired + private IFooDao dao; + + public FooService() { + super(); + } + + // API + + @Override + protected PagingAndSortingRepository getDao() { + return dao; + } + + // custom methods + + @Override + public Foo retrieveByName(final String name) { + return dao.retrieveByName(name); + } + + // overridden to be secured + + @Override + @Transactional(readOnly = true) + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public Page findPaginated(Pageable pageable) { + return dao.findAll(pageable); + } + +} diff --git a/spring-data-jpa/src/test/resources/application.properties b/spring-data-jpa/src/main/resources/application.properties similarity index 100% rename from spring-data-jpa/src/test/resources/application.properties rename to spring-data-jpa/src/main/resources/application.properties diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties b/spring-data-jpa/src/main/resources/persistence-multiple-db.properties similarity index 80% rename from persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties rename to spring-data-jpa/src/main/resources/persistence-multiple-db.properties index ce1b6da9ff..53c6cecf8b 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties +++ b/spring-data-jpa/src/main/resources/persistence-multiple-db.properties @@ -1,7 +1,7 @@ # jdbc.X jdbc.driverClassName=org.h2.Driver -user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS SPRING_JPA_USER -product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS SPRING_JPA_PRODUCT +user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS +product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS jdbc.user=sa jdbc.pass= diff --git a/spring-data-jpa/src/main/resources/persistence.properties b/spring-data-jpa/src/main/resources/persistence.properties new file mode 100644 index 0000000000..5e83653401 --- /dev/null +++ b/spring-data-jpa/src/main/resources/persistence.properties @@ -0,0 +1,16 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS +jdbc.user=sa +jdbc.pass= + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=true +hibernate.cache.use_query_cache=true +hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory + +# envers.X +envers.audit_table_suffix=_audit_log \ No newline at end of file diff --git a/spring-data-jpa/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ArticleRepositoryIntegrationTest.java similarity index 85% rename from spring-data-jpa/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java rename to spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ArticleRepositoryIntegrationTest.java index dd1fe66a0d..093e744003 100644 --- a/spring-data-jpa/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ArticleRepositoryIntegrationTest.java @@ -1,7 +1,9 @@ -package com.baeldung.repository; +package com.baeldung.dao.repositories; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; import com.baeldung.domain.Article; -import com.baeldung.repository.ArticleRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -16,7 +18,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) -@DataJpaTest +@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class}) public class ArticleRepositoryIntegrationTest { @Autowired diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ExtendedStudentRepositoryIntegrationTest.java similarity index 72% rename from persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java rename to spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ExtendedStudentRepositoryIntegrationTest.java index f3cf921632..b19a34df82 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ExtendedStudentRepositoryIntegrationTest.java @@ -1,23 +1,21 @@ -package org.baeldung.persistence.repository; +package com.baeldung.dao.repositories; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.List; - -import javax.annotation.Resource; - -import org.baeldung.config.StudentJPAH2Config; -import org.baeldung.extended.persistence.dao.ExtendedStudentRepository; -import org.baeldung.inmemory.persistence.model.Student; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.domain.Student; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { StudentJPAH2Config.class }) +import javax.annotation.Resource; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {PersistenceConfiguration.class}) @DirtiesContext public class ExtendedStudentRepositoryIntegrationTest { @Resource diff --git a/spring-data-jpa/src/test/java/com/baeldung/repository/JpaRepositoriesIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/JpaRepositoriesIntegrationTest.java similarity index 81% rename from spring-data-jpa/src/test/java/com/baeldung/repository/JpaRepositoriesIntegrationTest.java rename to spring-data-jpa/src/test/java/com/baeldung/dao/repositories/JpaRepositoriesIntegrationTest.java index d8b7bc4a88..eaadb9e44a 100644 --- a/spring-data-jpa/src/test/java/com/baeldung/repository/JpaRepositoriesIntegrationTest.java +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/JpaRepositoriesIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.repository; +package com.baeldung.dao.repositories; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertFalse; @@ -9,10 +9,19 @@ import static junit.framework.TestCase.assertTrue; import java.util.List; import java.util.Optional; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; +import com.baeldung.dao.repositories.ItemTypeRepository; +import com.baeldung.dao.repositories.LocationRepository; +import com.baeldung.dao.repositories.ReadOnlyLocationRepository; +import com.baeldung.dao.repositories.StoreRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.domain.Item; @@ -21,7 +30,7 @@ import com.baeldung.domain.Location; import com.baeldung.domain.Store; @RunWith(SpringRunner.class) -@DataJpaTest +@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class}) public class JpaRepositoriesIntegrationTest { @Autowired private LocationRepository locationRepository; diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java similarity index 67% rename from persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java rename to spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java index 9effd4717f..e29161394b 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java @@ -1,23 +1,25 @@ -package org.baeldung.persistence.repository; +package com.baeldung.dao.repositories; -import org.baeldung.config.PersistenceJPAConfigL2Cache; -import org.baeldung.persistence.model.User; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.dao.repositories.user.UserRepository; +import com.baeldung.domain.user.User; import org.junit.After; 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.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.JpaSort; import org.springframework.data.mapping.PropertyReferenceException; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; @@ -25,32 +27,71 @@ import static org.assertj.core.api.Assertions.assertThat; * Created by adam. */ @RunWith(SpringRunner.class) -@ContextConfiguration(classes = PersistenceJPAConfigL2Cache.class) +@SpringBootTest(classes = PersistenceConfiguration.class) @DirtiesContext public class UserRepositoryIntegrationTest { private final String USER_NAME_ADAM = "Adam"; private final String USER_NAME_PETER = "Peter"; + + private final String USER_EMAIL = "email@example.com"; + private final String USER_EMAIL2 = "email2@example.com"; + private final String USER_EMAIL3 = "email3@example.com"; + private final String USER_EMAIL4 = "email4@example.com"; + private final String USER_EMAIL5 = "email5@example.com"; + private final String USER_EMAIL6 = "email6@example.com"; + private final Integer INACTIVE_STATUS = 0; private final Integer ACTIVE_STATUS = 1; @Autowired private UserRepository userRepository; + @Test + @Transactional + public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); + userRepository.save(user3); + + User user4 = new User(); + user4.setName("SAMPLE"); + user4.setEmail(USER_EMAIL4); + userRepository.save(user4); + + try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { + assertThat(foundUsersStream.count()).isEqualTo(3l); + } + } + @Test public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() { User user1 = new User(); user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); user1.setStatus(ACTIVE_STATUS); userRepository.save(user1); User user2 = new User(); user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); user2.setStatus(ACTIVE_STATUS); userRepository.save(user2); User user3 = new User(); user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); user3.setStatus(INACTIVE_STATUS); userRepository.save(user3); @@ -63,16 +104,19 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() { User user1 = new User(); user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); user1.setStatus(ACTIVE_STATUS); userRepository.save(user1); User user2 = new User(); user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); user2.setStatus(ACTIVE_STATUS); userRepository.save(user2); User user3 = new User(); user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); user3.setStatus(INACTIVE_STATUS); userRepository.save(user3); @@ -85,6 +129,7 @@ public class UserRepositoryIntegrationTest { public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); @@ -97,6 +142,7 @@ public class UserRepositoryIntegrationTest { public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); @@ -109,11 +155,13 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); User user2 = new User(); user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); user2.setStatus(ACTIVE_STATUS); userRepository.save(user2); @@ -126,11 +174,13 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); User user2 = new User(); user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); user2.setStatus(ACTIVE_STATUS); userRepository.save(user2); @@ -143,11 +193,13 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); User user2 = new User(); user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); user2.setStatus(ACTIVE_STATUS); userRepository.save(user2); @@ -160,11 +212,13 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); User user2 = new User(); user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); user2.setStatus(ACTIVE_STATUS); userRepository.save(user2); @@ -177,6 +231,7 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); @@ -189,6 +244,7 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); @@ -201,6 +257,7 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); @@ -211,9 +268,9 @@ public class UserRepositoryIntegrationTest { @Test public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); @@ -224,9 +281,9 @@ public class UserRepositoryIntegrationTest { @Test(expected = PropertyReferenceException.class) public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); @@ -239,9 +296,9 @@ public class UserRepositoryIntegrationTest { @Test public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); userRepository.findAllUsers(new Sort("name")); @@ -254,12 +311,12 @@ public class UserRepositoryIntegrationTest { @Test public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", INACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS)); Page usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3)); @@ -271,12 +328,12 @@ public class UserRepositoryIntegrationTest { @Test public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", INACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS)); Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3)); @@ -289,10 +346,10 @@ public class UserRepositoryIntegrationTest { @Test @Transactional public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS)); int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); @@ -302,10 +359,10 @@ public class UserRepositoryIntegrationTest { @Test @Transactional public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS)); userRepository.flush(); int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE"); diff --git a/spring-data-jpa/src/test/java/com/baeldung/services/AbstractServicePersistenceIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/services/AbstractServicePersistenceIntegrationTest.java new file mode 100644 index 0000000000..acac66f2f7 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/services/AbstractServicePersistenceIntegrationTest.java @@ -0,0 +1,251 @@ +package com.baeldung.services; + +import com.baeldung.domain.Foo; +import com.baeldung.util.IDUtil; +import org.hamcrest.Matchers; +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.dao.DataAccessException; + +import java.io.Serializable; +import java.util.List; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.*; + +public abstract class AbstractServicePersistenceIntegrationTest { + + // tests + + // find - one + + @Test + /**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() { + // When + final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong()); + + // Then + assertNull(createdResource); + } + + @Test + public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() { + final Foo existingResource = persistNewEntity(); + getApi().findOne(existingResource.getId()); + } + + @Test + public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() { + getApi().findOne(IDUtil.randomPositiveLong()); + } + + @Test + public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() { + final Foo existingResource = persistNewEntity(); + final Foo retrievedResource = getApi().findOne(existingResource.getId()); + assertNotNull(retrievedResource); + } + + @Test + public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() { + final Foo existingResource = persistNewEntity(); + final Foo retrievedResource = getApi().findOne(existingResource.getId()); + assertEquals(existingResource, retrievedResource); + } + + // find - one - by name + + // find - all + + @Test + /**/public void whenAllResourcesAreRetrieved_thenNoExceptions() { + getApi().findAll(); + } + + @Test + /**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() { + final List resources = getApi().findAll(); + + assertNotNull(resources); + } + + @Test + /**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() { + persistNewEntity(); + + // When + final List allResources = getApi().findAll(); + + // Then + assertThat(allResources, not(Matchers. empty())); + } + + @Test + /**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() { + final Foo existingResource = persistNewEntity(); + + final List resources = getApi().findAll(); + + assertThat(resources, hasItem(existingResource)); + } + + @Test + /**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() { + persistNewEntity(); + + // When + final List allResources = getApi().findAll(); + + // Then + for (final Foo resource : allResources) { + assertNotNull(resource.getId()); + } + } + + // create + + @Test(expected = RuntimeException.class) + /**/public void whenNullResourceIsCreated_thenException() { + getApi().create(null); + } + + @Test + /**/public void whenResourceIsCreated_thenNoExceptions() { + persistNewEntity(); + } + + @Test + /**/public void whenResourceIsCreated_thenResourceIsRetrievable() { + final Foo existingResource = persistNewEntity(); + + assertNotNull(getApi().findOne(existingResource.getId())); + } + + @Test + /**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() { + final Foo originalResource = createNewEntity(); + final Foo savedResource = getApi().create(originalResource); + + assertEquals(originalResource, savedResource); + } + + @Test(expected = RuntimeException.class) + public void whenResourceWithFailedConstraintsIsCreated_thenException() { + final Foo invalidResource = createNewEntity(); + invalidate(invalidResource); + + getApi().create(invalidResource); + } + + /** + * -- specific to the persistence engine + */ + @Test(expected = DataAccessException.class) + @Ignore("Hibernate simply ignores the id silently and still saved (tracking this)") + public void whenResourceWithIdIsCreated_thenDataAccessException() { + final Foo resourceWithId = createNewEntity(); + resourceWithId.setId(IDUtil.randomPositiveLong()); + + getApi().create(resourceWithId); + } + + // update + + @Test(expected = RuntimeException.class) + /**/public void whenNullResourceIsUpdated_thenException() { + getApi().update(null); + } + + @Test + /**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() { + // Given + final Foo existingResource = persistNewEntity(); + + // When + getApi().update(existingResource); + } + + /** + * - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException + */ + @Test(expected = RuntimeException.class) + public void whenResourceIsUpdatedWithFailedConstraints_thenException() { + final Foo existingResource = persistNewEntity(); + invalidate(existingResource); + + getApi().update(existingResource); + } + + @Test + /**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() { + // Given + final Foo existingResource = persistNewEntity(); + + // When + change(existingResource); + getApi().update(existingResource); + + final Foo updatedResource = getApi().findOne(existingResource.getId()); + + // Then + assertEquals(existingResource, updatedResource); + } + + // delete + + // @Test(expected = RuntimeException.class) + // public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() { + // // When + // getApi().delete(IDUtil.randomPositiveLong()); + // } + // + // @Test(expected = RuntimeException.class) + // public void whenResourceIsDeletedByNegativeId_thenException() { + // // When + // getApi().delete(IDUtil.randomNegativeLong()); + // } + // + // @Test + // public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() { + // // Given + // final Foo existingResource = persistNewEntity(); + // + // // When + // getApi().delete(existingResource.getId()); + // } + // + // @Test + // /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() { + // // Given + // final Foo existingResource = persistNewEntity(); + // + // // When + // getApi().delete(existingResource.getId()); + // + // // Then + // assertNull(getApi().findOne(existingResource.getId())); + // } + + // template method + + protected Foo createNewEntity() { + return new Foo(randomAlphabetic(6)); + } + + protected abstract IOperations getApi(); + + private final void invalidate(final Foo entity) { + entity.setName(null); + } + + private final void change(final Foo entity) { + entity.setName(randomAlphabetic(6)); + } + + protected Foo persistNewEntity() { + return getApi().create(createNewEntity()); + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/services/FooServicePersistenceIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/services/FooServicePersistenceIntegrationTest.java new file mode 100644 index 0000000000..fd17d033e1 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/services/FooServicePersistenceIntegrationTest.java @@ -0,0 +1,75 @@ +package com.baeldung.services; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.domain.Foo; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {PersistenceConfiguration.class}, loader = AnnotationConfigContextLoader.class) +public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest { + + @Autowired + private IFooService service; + + // tests + + @Test + public final void whenContextIsBootstrapped_thenNoExceptions() { + // + } + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + service.create(new Foo(randomAlphabetic(6))); + } + + @Test(expected = DataIntegrityViolationException.class) + public final void whenInvalidEntityIsCreated_thenDataException() { + service.create(new Foo()); + } + + @Test(expected = DataIntegrityViolationException.class) + public final void whenEntityWithLongNameIsCreated_thenDataException() { + service.create(new Foo(randomAlphabetic(2048))); + } + + // custom Query method + + @Test + public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() { + final String name = randomAlphabetic(6); + service.create(new Foo(name)); + + final Foo retrievedByName = service.retrieveByName(name); + assertNotNull(retrievedByName); + } + + // work in progress + + @Test(expected = InvalidDataAccessApiUsageException.class) + @Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail") + public final void whenSameEntityIsCreatedTwice_thenDataException() { + final Foo entity = new Foo(randomAlphabetic(8)); + service.create(entity); + service.create(entity); + } + + // API + + @Override + protected final IOperations getApi() { + return service; + } + +} diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/services/JpaMultipleDBIntegrationTest.java similarity index 65% rename from persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java rename to spring-data-jpa/src/test/java/com/baeldung/services/JpaMultipleDBIntegrationTest.java index 6cd187230c..29b96ae597 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java +++ b/spring-data-jpa/src/test/java/com/baeldung/services/JpaMultipleDBIntegrationTest.java @@ -1,19 +1,13 @@ -package org.baeldung.persistence.service; +package com.baeldung.services; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.Arrays; - -import org.baeldung.config.ProductConfig; -import org.baeldung.config.UserConfig; -import org.baeldung.persistence.multiple.dao.product.ProductRepository; -import org.baeldung.persistence.multiple.dao.user.PossessionRepository; -import org.baeldung.persistence.multiple.dao.user.UserRepository; -import org.baeldung.persistence.multiple.model.product.Product; -import org.baeldung.persistence.multiple.model.user.Possession; -import org.baeldung.persistence.multiple.model.user.User; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; +import com.baeldung.dao.repositories.user.PossessionRepository; +import com.baeldung.dao.repositories.product.ProductRepository; +import com.baeldung.dao.repositories.user.UserRepository; +import com.baeldung.domain.user.Possession; +import com.baeldung.domain.product.Product; +import com.baeldung.domain.user.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -21,11 +15,17 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { UserConfig.class, ProductConfig.class }) +import java.util.Collections; +import java.util.Optional; + +import static org.junit.Assert.*; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {PersistenceUserConfiguration.class, PersistenceProductConfiguration.class}) @EnableTransactionManagement @DirtiesContext public class JpaMultipleDBIntegrationTest { @@ -50,12 +50,12 @@ public class JpaMultipleDBIntegrationTest { user.setAge(20); Possession p = new Possession("sample"); p = possessionRepository.save(p); - user.setPossessionList(Arrays.asList(p)); + user.setPossessionList(Collections.singletonList(p)); user = userRepository.save(user); - final User result = userRepository.findOne(user.getId()); - assertNotNull(result); - System.out.println(result.getPossessionList()); - assertTrue(result.getPossessionList().size() == 1); + final Optional result = userRepository.findById(user.getId()); + assertTrue(result.isPresent()); + System.out.println(result.get().getPossessionList()); + assertEquals(1, result.get().getPossessionList().size()); } @Test @@ -66,7 +66,7 @@ public class JpaMultipleDBIntegrationTest { user1.setEmail("john@test.com"); user1.setAge(20); user1 = userRepository.save(user1); - assertNotNull(userRepository.findOne(user1.getId())); + assertTrue(userRepository.findById(user1.getId()).isPresent()); User user2 = new User(); user2.setName("Tom"); @@ -92,7 +92,7 @@ public class JpaMultipleDBIntegrationTest { product.setPrice(20); product = productRepository.save(product); - assertNotNull(productRepository.findOne(product.getId())); + assertTrue(productRepository.findById(product.getId()).isPresent()); } } diff --git a/spring-data-jpa/src/test/java/com/baeldung/services/SpringDataJPABarAuditIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/services/SpringDataJPABarAuditIntegrationTest.java new file mode 100644 index 0000000000..3c36f43192 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/services/SpringDataJPABarAuditIntegrationTest.java @@ -0,0 +1,72 @@ +package com.baeldung.services; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.domain.Bar; +import org.junit.*; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { PersistenceConfiguration.class }, loader = AnnotationConfigContextLoader.class) +public class SpringDataJPABarAuditIntegrationTest { + + private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + @Autowired + @Qualifier("barSpringDataJpaService") + private IBarService barService; + + @Autowired + private EntityManagerFactory entityManagerFactory; + + private EntityManager em; + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + em = entityManagerFactory.createEntityManager(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + em.close(); + } + + @Test + @WithMockUser(username = "tutorialuser") + public final void whenBarsModified_thenBarsAudited() { + Bar bar = new Bar("BAR1"); + barService.create(bar); + assertEquals(bar.getCreatedDate(), bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + bar.setName("BAR2"); + bar = barService.update(bar); + assertTrue(bar.getCreatedDate() < bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + } +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java b/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java new file mode 100644 index 0000000000..45e72e046d --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java @@ -0,0 +1,33 @@ +package com.baeldung.util; + +import java.util.Random; + +public final class IDUtil { + + private IDUtil() { + throw new AssertionError(); + } + + // API + + public static String randomPositiveLongAsString() { + return Long.toString(randomPositiveLong()); + } + + public static String randomNegativeLongAsString() { + return Long.toString(randomNegativeLong()); + } + + public static long randomPositiveLong() { + long id = new Random().nextLong() * 10000; + id = (id < 0) ? (-1 * id) : id; + return id; + } + + private static long randomNegativeLong() { + long id = new Random().nextLong() * 10000; + id = (id > 0) ? (-1 * id) : id; + return id; + } + +} diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 22adf265b1..40dc91a88d 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -76,6 +76,49 @@ test + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey.version} + + + org.glassfish.jersey.ext.rx + jersey-rx-client-rxjava + ${jersey.version} + + + org.glassfish.jersey.ext.rx + jersey-rx-client-rxjava2 + ${jersey.version} + + + com.github.tomakehurst + wiremock + 1.58 + test + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + 2.6.0 + + + com.fasterxml.jackson.core + jackson-databind + 2.6.0 + + + org.slf4j + slf4j-jdk14 + 1.7.25 + + + org.assertj + assertj-core + 3.10.0 + test + + @@ -170,7 +213,7 @@
- 2.26 + 2.27 3.2.0 1.6.1 4.4.9 diff --git a/jersey-client-rx/src/test/java/com/baeldung/samples/jerseyrx/ClientOrchestrationIntegrationTest.java b/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java similarity index 99% rename from jersey-client-rx/src/test/java/com/baeldung/samples/jerseyrx/ClientOrchestrationIntegrationTest.java rename to spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java index 88a8d67a7d..990279a481 100644 --- a/jersey-client-rx/src/test/java/com/baeldung/samples/jerseyrx/ClientOrchestrationIntegrationTest.java +++ b/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.samples.jerseyrx; +package com.baeldung.clientrx; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.assertj.core.api.Assertions.*; diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index baa1ebf51a..81c938a289 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -1,344 +1,344 @@ - 4.0.0 - com.baeldung - spring-rest-full - 0.1-SNAPSHOT - spring-rest-full - war + 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-rest-full + 0.1-SNAPSHOT + spring-rest-full + war - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-1 - + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 + - + - - - 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.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 + 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 - + + org.springframework.boot + spring-boot-starter-tomcat + - + - - org.apache.httpcomponents - httpclient - - - commons-logging - commons-logging - - - - - org.apache.httpcomponents - httpcore - + + 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 - + + 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 - + + javax.servlet + javax.servlet-api + provided + + + javax.servlet + jstl + runtime + - - - com.fasterxml.jackson.core - jackson-databind - - - com.thoughtworks.xstream - xstream - ${xstream.version} - + + + com.fasterxml.jackson.core + jackson-databind + + + com.thoughtworks.xstream + xstream + ${xstream.version} + - + - - com.google.guava - guava - ${guava.version} - + + com.google.guava + guava + ${guava.version} + - + - - org.springframework - spring-test - test - + + org.springframework + spring-test + test + - - - - - - - org.hamcrest - hamcrest-library - test - + + + + + + + org.hamcrest + hamcrest-library + test + - - org.mockito - mockito-core - test - + + org.mockito + mockito-core + test + - + - - spring-rest-full - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-war-plugin - - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*LiveTest.java - **/*TestSuite.java - - - - - 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 - - - - - - + + spring-rest-full + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*LiveTest.java + **/*TestSuite.java + + + + + 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 + + + + + + - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*IntegrationTest.java - **/*IntTest.java - - - **/*LiveTest.java - - - - - - - json - - - - - org.codehaus.cargo - cargo-maven2-plugin - - false - - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - - - - - + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + **/*IntTest.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 + + + 1.4.9 - - 19.0 - 3.5 + + 19.0 + 3.5 - - 1.6.1 - 1.1.3 - + + 1.6.1 + 1.1.3 + \ No newline at end of file diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index 004c925a8f..d39e3a43c1 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -1,339 +1,339 @@ - 4.0.0 - com.baeldung - spring-rest-simple - 0.1-SNAPSHOT - spring-rest-simple - war + 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-rest-simple + 0.1-SNAPSHOT + spring-rest-simple + war - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-1 - + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 + - + - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-devtools - - - org.springframework.boot - spring-boot-starter-test - test - + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-devtools + + + org.springframework.boot + spring-boot-starter-test + test + - - - org.springframework - spring-web - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - - - org.springframework - spring-oxm - - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - - + + + org.springframework + spring-web + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + + + org.springframework + spring-oxm + + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + - - javax.servlet - javax.servlet-api - provided - - - javax.servlet - jstl - runtime - + + javax.servlet + javax.servlet-api + provided + + + javax.servlet + jstl + runtime + - + - - com.fasterxml.jackson.core - jackson-databind - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - - - com.thoughtworks.xstream - xstream - ${xstream.version} - + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.thoughtworks.xstream + xstream + ${xstream.version} + - + - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - + - - org.slf4j - slf4j-api - - - ch.qos.logback - logback-classic - - - - org.slf4j - jcl-over-slf4j - - + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + org.slf4j + jcl-over-slf4j + + - + - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + - + - - junit - junit - test - - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - - - org.mockito - mockito-core - test - - - org.springframework - spring-test - - - com.jayway.restassured - rest-assured - ${jayway-rest-assured.version} - - - com.google.protobuf - protobuf-java - ${protobuf-java.version} - - - com.googlecode.protobuf-java-format - protobuf-java-format - ${protobuf-java-format.version} - - - com.esotericsoftware - kryo - ${kryo.version} - - - com.jayway.jsonpath - json-path - - + + junit + junit + test + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + org.mockito + mockito-core + test + + + org.springframework + spring-test + + + com.jayway.restassured + rest-assured + ${jayway-rest-assured.version} + + + com.google.protobuf + protobuf-java + ${protobuf-java.version} + + + com.googlecode.protobuf-java-format + protobuf-java-format + ${protobuf-java-format.version} + + + com.esotericsoftware + kryo + ${kryo.version} + + + com.jayway.jsonpath + json-path + + - - spring-rest - - - src/main/resources - true - - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - - - tomcat8x - embedded - - - - - - - 8082 - - - - - - + + spring-rest + + + src/main/resources + true + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + + + tomcat8x + embedded + + + + + + + 8082 + + + + + + - - - integration - - - - org.codehaus.cargo - cargo-maven2-plugin - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - - - - - live - - - - org.codehaus.cargo - cargo-maven2-plugin - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - + + + integration + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + + + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*LiveTest.java - - - cargo - - - - - + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + - - - - + + + + - - 1.3.3 - 4.0.0 - 1.4 - 3.1.0 - 3.5 - 1.4.9 + + 1.3.3 + 4.0.0 + 1.4 + 3.1.0 + 3.5 + 1.4.9 - - 20.0 - 2.9.0 + + 20.0 + 2.9.0 - - 1.6.0 - 3.0.4 + + 1.6.0 + 3.0.4 - - 3.4.1 + + 3.4.1 - 2.2.0 - + 2.2.0 + diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index bd17811801..ba74d26c35 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -1,305 +1,305 @@ - 4.0.0 - spring-rest - 0.1-SNAPSHOT - spring-rest - war + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + spring-rest + 0.1-SNAPSHOT + spring-rest + war - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + - + - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-devtools - - - org.springframework.boot - spring-boot-starter-test - + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-devtools + + + org.springframework.boot + spring-boot-starter-test + - - - org.springframework - spring-web - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - - - org.springframework - spring-oxm - - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - + + + org.springframework + spring-web + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + + + org.springframework + spring-oxm + + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + - - - javax.servlet - javax.servlet-api - provided - + + + javax.servlet + javax.servlet-api + provided + - - javax.servlet - jstl - runtime - + + javax.servlet + jstl + runtime + - - - com.fasterxml.jackson.core - jackson-databind - + + + com.fasterxml.jackson.core + jackson-databind + - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + - - com.thoughtworks.xstream - xstream - ${xstream.version} - + + com.thoughtworks.xstream + xstream + ${xstream.version} + - - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-lang3 - + + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-lang3 + - - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + - - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - - - org.mockito - mockito-core - test - - - org.springframework - spring-test - + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + org.mockito + mockito-core + test + + + org.springframework + spring-test + - - - com.google.protobuf - protobuf-java - ${protobuf-java.version} - - - com.googlecode.protobuf-java-format - protobuf-java-format - ${protobuf-java-format.version} - - - com.esotericsoftware - kryo - ${kryo.version} - - - com.jayway.jsonpath - json-path - + + + com.google.protobuf + protobuf-java + ${protobuf-java.version} + + + com.googlecode.protobuf-java-format + protobuf-java-format + ${protobuf-java-format.version} + + + com.esotericsoftware + kryo + ${kryo.version} + + + com.jayway.jsonpath + json-path + - - - commons-io - commons-io - 2.4 - - - au.com.dius - pact-jvm-provider-junit_2.11 - ${pact.version} - - - io.rest-assured - rest-assured - + + + commons-io + commons-io + 2.4 + + + au.com.dius + pact-jvm-provider-junit_2.11 + ${pact.version} + + + io.rest-assured + rest-assured + - + - - spring-rest - - - src/main/resources - true - - + + spring-rest + + + src/main/resources + true + + - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - org.apache.maven.plugins - maven-war-plugin - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${checkstyle-maven-plugin.version} - - checkstyle.xml - - - - - check - - - - - - + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + org.apache.maven.plugins + maven-war-plugin + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${checkstyle-maven-plugin.version} + + checkstyle.xml + + + + + check + + + + + + - - - live - - - - org.codehaus.cargo - cargo-maven2-plugin - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*LiveTest.java - - - cargo - - - - - + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + - - - + + + - + - - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${checkstyle-maven-plugin.version} - - checkstyle.xml - - - - + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${checkstyle-maven-plugin.version} + + checkstyle.xml + + + + - - 1.3.2 - 4.0.0 - 1.4 - 3.1.0 - 3.5 - 1.4.9 + + 1.3.2 + 4.0.0 + 1.4 + 3.1.0 + 3.5 + 1.4.9 - - 20.0 + + 20.0 - - 1.6.0 - 3.0.4 - 3.0.0 - false - - 3.4.1 + + 1.6.0 + 3.0.4 + 3.0.0 + false + + 3.4.1 - 2.2.0 - 3.5.11 - 3.1.0 - + 2.2.0 + 3.5.11 + 3.1.0 + diff --git a/spring-security-mvc-boot/README.MD b/spring-security-mvc-boot/README.MD index 0bae800b1e..eec61f087f 100644 --- a/spring-security-mvc-boot/README.MD +++ b/spring-security-mvc-boot/README.MD @@ -1,7 +1,7 @@ -###The Course +### The Course The "REST With Spring" Classes: http://github.learnspringsecurity.com -###Relevant Articles: +### Relevant Articles: - [A Custom Security Expression with Spring Security](http://www.baeldung.com/spring-security-create-new-custom-security-expression) - [Custom AccessDecisionVoters in Spring Security](http://www.baeldung.com/spring-security-custom-voter) - [Spring Security: Authentication with a Database-backed UserDetailsService](http://www.baeldung.com/spring-security-authentication-with-a-database) @@ -9,4 +9,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [Multiple Entry Points in Spring Security](http://www.baeldung.com/spring-security-multiple-entry-points) - [Multiple Authentication Providers in Spring Security](http://www.baeldung.com/spring-security-multiple-auth-providers) - [Granted Authority Versus Role in Spring Security](http://www.baeldung.com/spring-security-granted-authority-vs-role) -- [Spring Data with Spring Security] (https://www.baeldung.com/spring-data-security) +- [Spring Data with Spring Security](https://www.baeldung.com/spring-data-security)