diff --git a/cas/cas-secured-app/README.md b/cas/cas-secured-app/README.md new file mode 100644 index 0000000000..01c5f91988 --- /dev/null +++ b/cas/cas-secured-app/README.md @@ -0,0 +1,2 @@ +## Relevant articles: +- [CAS SSO With Spring Security](http://www.baeldung.com/spring-security-cas-sso) diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index 543354e8b3..d52597412e 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.BUILD-SNAPSHOT + 2.0.0.M7 @@ -87,14 +87,6 @@ - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - spring-milestones Spring Milestones @@ -106,14 +98,6 @@ - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - spring-milestones Spring Milestones diff --git a/core-java-8/README.md b/core-java-8/README.md index 540a32b0ba..61f8df8f49 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -32,3 +32,4 @@ - [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception) - [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) - [Copy a File with Java](http://www.baeldung.com/java-copy-file) +- [Generating Prime Numbers in Java](http://www.baeldung.com/java-generate-prime-numbers) diff --git a/core-java-9/README.md b/core-java-9/README.md index 98c855caea..ce8a140dc0 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -18,3 +18,4 @@ - [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates) - [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new) - [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string) +- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime) diff --git a/core-java-concurrency/README.md b/core-java-concurrency/README.md index 48c5f2a50c..23509013d5 100644 --- a/core-java-concurrency/README.md +++ b/core-java-concurrency/README.md @@ -31,3 +31,5 @@ - [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent) - [Semaphores in Java](http://www.baeldung.com/java-semaphore) - [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread) +- [Implementing a Runnable vs Extending a Thread](http://www.baeldung.com/java-runnable-vs-extending-thread) +- [How to Kill a Java Thread](http://www.baeldung.com/java-thread-stop) diff --git a/core-java/README.md b/core-java/README.md index 8287a21d1e..ae9e0d96c4 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -121,4 +121,8 @@ - [Copy a File with Java](http://www.baeldung.com/java-copy-file) - [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns) - [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable) - +- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack) +- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break) +- [Java – Append Data to a File](http://www.baeldung.com/java-append-to-file) +- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque) +- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter) diff --git a/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java b/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java new file mode 100644 index 0000000000..977587a06a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java @@ -0,0 +1,21 @@ +package com.baeldung.array; + +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +public class ArrayBenchmarkRunner { + + public static void main(String[] args) throws Exception { + + Options options = new OptionsBuilder() + .include(SearchArrayTest.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true).shouldDoGC(true) + .jvmArgs("-server").build(); + + new Runner(options).run(); + + + } + +} diff --git a/core-java/src/main/java/com/baeldung/array/ArrayInverter.java b/core-java/src/main/java/com/baeldung/array/ArrayInverter.java new file mode 100644 index 0000000000..7f7fcbb5a8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/array/ArrayInverter.java @@ -0,0 +1,41 @@ +package com.baeldung.array; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.IntStream; + +import org.apache.commons.lang3.ArrayUtils; + +import com.google.common.collect.Lists; + +public class ArrayInverter { + + public void invertUsingFor(Object[] array) { + for (int i = 0; i < array.length / 2; i++) { + Object temp = array[i]; + array[i] = array[array.length - 1 - i]; + array[array.length - 1 - i] = temp; + } + } + + public void invertUsingCollectionsReverse(Object[] array) { + List list = Arrays.asList(array); + Collections.reverse(list); + } + + public Object[] invertUsingStreams(final Object[] array) { + return IntStream.range(1, array.length + 1).mapToObj(i -> array[array.length - i]).toArray(); + } + + public void invertUsingCommonsLang(Object[] array) { + ArrayUtils.reverse(array); + } + + public Object[] invertUsingGuava(Object[] array) { + List list = Arrays.asList(array); + List reverted = Lists.reverse(list); + return reverted.toArray(); + } + +} diff --git a/core-java/src/test/java/com/baeldung/array/SearchArrayTest.java b/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java similarity index 58% rename from core-java/src/test/java/com/baeldung/array/SearchArrayTest.java rename to core-java/src/main/java/com/baeldung/array/SearchArrayTest.java index 94911baac9..8b44138b32 100644 --- a/core-java/src/test/java/com/baeldung/array/SearchArrayTest.java +++ b/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java @@ -1,78 +1,77 @@ package com.baeldung.array; -import org.junit.Test; +import org.openjdk.jmh.annotations.*; import java.util.*; +import java.util.concurrent.TimeUnit; +@BenchmarkMode(Mode.AverageTime) +@Warmup(iterations = 5) +@OutputTimeUnit(TimeUnit.MICROSECONDS) public class SearchArrayTest { - - @Test - public void searchArrayAllocNewCollections() { + @Benchmark + public void searchArrayLoop() { int count = 1000; - String[] strings = seedArray(count); + for (int i = 0; i < count; i++) { + searchLoop(strings, "T"); + } + } - long startTime = System.nanoTime(); + @Benchmark + public void searchArrayAllocNewList() { + + int count = 1000; + String[] strings = seedArray(count); for (int i = 0; i < count; i++) { searchList(strings, "W"); } - long duration = System.nanoTime() - startTime; - System.out.println("SearchList: " + duration / 10000); - startTime = System.nanoTime(); - for (int i = 0; i < count; i++) { - searchSet(strings,"S"); - } - duration = System.nanoTime() - startTime; - System.out.println("SearchSet: " + duration / 10000); - - startTime = System.nanoTime(); - for (int i = 0; i < count; i++) { - searchLoop(strings, "T"); - } - duration = System.nanoTime() - startTime; - System.out.println("SearchLoop: " + duration / 10000); } - @Test - public void searchArrayReuseCollections() { + @Benchmark + public void searchArrayAllocNewSet() { - int count = 10000; + int count = 1000; + String[] strings = seedArray(count); + for (int i = 0; i < count; i++) { + searchSet(strings, "S"); + } + } + + + @Benchmark + public void searchArrayReuseList() { + + int count = 1000; String[] strings = seedArray(count); List asList = Arrays.asList(strings); - Set asSet = new HashSet<>(Arrays.asList(strings)); - long startTime = System.nanoTime(); for (int i = 0; i < count; i++) { asList.contains("W"); } - long duration = System.nanoTime() - startTime; - System.out.println("List: " + duration / 10000); - - startTime = System.nanoTime(); - for (int i = 0; i < count; i++) { - asSet.contains("S"); - } - duration = System.nanoTime() - startTime; - System.out.println("Set: " + duration / 10000); - - startTime = System.nanoTime(); - for (int i = 0; i < count; i++) { - searchLoop(strings, "T"); - } - duration = System.nanoTime() - startTime; - System.out.println("Loop: " + duration / 10000); - } - @Test + @Benchmark + public void searchArrayReuseSet() { + + int count = 1000; + String[] strings = seedArray(count); + Set asSet = new HashSet<>(Arrays.asList(strings)); + for (int i = 0; i < count; i++) { + asSet.contains("S"); + } + } + + + @Benchmark public void searchArrayBinarySearch() { - int count = 10000; + int count = 1000; String[] strings = seedArray(count); Arrays.sort(strings); @@ -81,7 +80,7 @@ public class SearchArrayTest { Arrays.binarySearch(strings, "A"); } long duration = System.nanoTime() - startTime; - System.out.println("Binary search: " + duration / 10000); + //System.out.println("Binary search: " + duration / 10000); } diff --git a/core-java/src/main/java/com/baeldung/interfaces/CommaSeparatedCustomers.java b/core-java/src/main/java/com/baeldung/interfaces/CommaSeparatedCustomers.java new file mode 100644 index 0000000000..29ed2d3d26 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/interfaces/CommaSeparatedCustomers.java @@ -0,0 +1,21 @@ +package com.baeldung.interfaces; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class CommaSeparatedCustomers implements Customer.List { + + private List customers = new ArrayList(); + + @Override + public void Add(Customer customer) { + customers.add(customer); + } + + @Override + public String getCustomerNames() { + return customers.stream().map(customer -> customer.getName()).collect(Collectors.joining(",")); + } + +} diff --git a/core-java/src/main/java/com/baeldung/interfaces/Customer.java b/core-java/src/main/java/com/baeldung/interfaces/Customer.java new file mode 100644 index 0000000000..d2f2b48074 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/interfaces/Customer.java @@ -0,0 +1,19 @@ +package com.baeldung.interfaces; + +public class Customer { + public interface List { + void Add(Customer customer); + + String getCustomerNames(); + } + + private String name; + + public Customer(String name) { + this.name = name; + } + + String getName() { + return name; + } +} diff --git a/core-java/src/main/java/com/baeldung/polymorphism/GenericFile.java b/core-java/src/main/java/com/baeldung/polymorphism/GenericFile.java index 4075083c49..03e704f36f 100644 --- a/core-java/src/main/java/com/baeldung/polymorphism/GenericFile.java +++ b/core-java/src/main/java/com/baeldung/polymorphism/GenericFile.java @@ -54,7 +54,7 @@ public class GenericFile { } public String getFileInfo() { - return "File Name: " + this.getName() + "\n" + "Extension: " + this.getExtension() + "\n" + "Date Created: " + this.getDateCreated() + "\n" + "Version: " + this.getVersion() + "\n"; + return String.format("File Name: %s\n" + " Extension: %s\n" + " Date Created: %s\n" + " Version: %s\n", this.getName(), this.getExtension(), this.getDateCreated(), this.getVersion()); } public Object read() { diff --git a/core-java/src/main/java/com/baeldung/polymorphism/ImageFile.java b/core-java/src/main/java/com/baeldung/polymorphism/ImageFile.java index ac72a40993..e237f3f826 100644 --- a/core-java/src/main/java/com/baeldung/polymorphism/ImageFile.java +++ b/core-java/src/main/java/com/baeldung/polymorphism/ImageFile.java @@ -30,7 +30,7 @@ public class ImageFile extends GenericFile { } public String getFileInfo() { - return super.getFileInfo() + "Height: " + this.getHeight() + "\n" + "Width: " + this.getWidth(); + return String.format(" %s Height: %d\n Width: %d", super.getFileInfo(), this.getHeight(), this.getWidth()); } public String read() { diff --git a/core-java/src/main/java/com/baeldung/polymorphism/TextFile.java b/core-java/src/main/java/com/baeldung/polymorphism/TextFile.java index 8280b4ee95..2c28c968b8 100644 --- a/core-java/src/main/java/com/baeldung/polymorphism/TextFile.java +++ b/core-java/src/main/java/com/baeldung/polymorphism/TextFile.java @@ -21,7 +21,7 @@ public class TextFile extends GenericFile { } public String getFileInfo() { - return super.getFileInfo() + "Word Count: " + wordCount; + return String.format(" %s Word Count: %d", super.getFileInfo(), wordCount); } public String read() { diff --git a/core-java/src/main/java/com/baeldung/tree/BinaryTree.java b/core-java/src/main/java/com/baeldung/tree/BinaryTree.java new file mode 100644 index 0000000000..3cc496e348 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/tree/BinaryTree.java @@ -0,0 +1,216 @@ +package com.baeldung.tree; + +import java.util.LinkedList; +import java.util.Queue; + +public class BinaryTree { + + Node root; + + public void add(int value) { + + Node newNode = new Node(value); + + if (root == null) { + root = newNode; + return; + } + + Node parent = root; + Node current = root; + + while (true) { + + if (newNode.value < parent.value) { + current = parent.left; + + if (current == null) { + parent.left = newNode; + break; + } + } else { + current = parent.right; + + if (current == null) { + parent.right = newNode; + break; + } + } + + parent = current; + } + } + + public boolean isEmpty() { + return root == null; + } + + public boolean containsNode(int value) { + + Node current = root; + + while (current != null) { + + if (value == current.value) { + return true; + } + + if (value < current.value) { + current = current.left; + } else { + current = current.right; + } + + } + + return false; + } + + public void delete(int value) { + + Node current = root; + Node parent = root; + Node nodeToDelete = null; + boolean isLeftChild = false; + + while (nodeToDelete == null && current != null) { + + if (value == current.value) { + nodeToDelete = current; + } else if (value < current.value) { + parent = current; + current = current.left; + isLeftChild = true; + } else { + parent = current; + current = current.right; + isLeftChild = false; + } + + } + + if (nodeToDelete == null) { + return; + } + + // Case 1: no children + if (nodeToDelete.left == null && nodeToDelete.right == null) { + if (nodeToDelete == root) { + root = null; + } else if (isLeftChild) { + parent.left = null; + } else { + parent.right = null; + } + } + // Case 2: only 1 child + else if (nodeToDelete.right == null) { + if (nodeToDelete == root) { + root = nodeToDelete.left; + } else if (isLeftChild) { + parent.left = nodeToDelete.left; + } else { + parent.right = nodeToDelete.left; + } + } else if (nodeToDelete.left == null) { + if (nodeToDelete == root) { + root = nodeToDelete.right; + } else if (isLeftChild) { + parent.left = nodeToDelete.right; + } else { + parent.right = nodeToDelete.right; + } + } + // Case 3: 2 children + else if (nodeToDelete.left != null && nodeToDelete.right != null) { + Node replacement = findReplacement(nodeToDelete); + if (nodeToDelete == root) { + root = replacement; + } else if (isLeftChild) { + parent.left = replacement; + } else { + parent.right = replacement; + } + } + + } + + private Node findReplacement(Node nodeToDelete) { + + Node replacement = nodeToDelete; + Node parentReplacement = nodeToDelete; + Node current = nodeToDelete.right; + + while (current != null) { + parentReplacement = replacement; + replacement = current; + current = current.left; + } + + if (replacement != nodeToDelete.right) { + parentReplacement.left = replacement.right; + replacement.right = nodeToDelete.right; + } + + replacement.left = nodeToDelete.left; + + return replacement; + } + + public void traverseInOrder(Node node) { + if (node != null) { + traverseInOrder(node.left); + System.out.print(" " + node.value); + traverseInOrder(node.right); + } + } + + public void traversePreOrder(Node node) { + if (node != null) { + System.out.print(" " + node.value); + traversePreOrder(node.left); + traversePreOrder(node.right); + } + } + + public void traversePostOrder(Node node) { + if (node != null) { + traversePostOrder(node.left); + traversePostOrder(node.right); + + System.out.print(" " + node.value); + } + } + + public void traverseLevelOrder() { + Queue nodes = new LinkedList<>(); + nodes.add(root); + + while (!nodes.isEmpty()) { + + Node node = nodes.remove(); + + System.out.print(" " + node.value); + + if (node.left != null) { + nodes.add(node.left); + } + + if (node.left != null) { + nodes.add(node.right); + } + } + } + + class Node { + int value; + Node left; + Node right; + + Node(int value) { + this.value = value; + right = null; + left = null; + } + } +} diff --git a/core-java/src/main/resources/countries.properties b/core-java/src/main/resources/countries.properties index e743b5a40b..50b5e85653 100644 --- a/core-java/src/main/resources/countries.properties +++ b/core-java/src/main/resources/countries.properties @@ -1,3 +1,3 @@ -UK -US -Germany +UK +US +Germany \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/array/ArrayInverterUnitTest.java b/core-java/src/test/java/com/baeldung/array/ArrayInverterUnitTest.java new file mode 100644 index 0000000000..ca59ee51fb --- /dev/null +++ b/core-java/src/test/java/com/baeldung/array/ArrayInverterUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.array; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class ArrayInverterUnitTest { + + private String[] fruits = { "apples", "tomatoes", "bananas", "guavas", "pineapples", "oranges" }; + + @Test + public void invertArrayWithForLoop() { + ArrayInverter inverter = new ArrayInverter(); + inverter.invertUsingFor(fruits); + + assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits); + } + + @Test + public void invertArrayWithCollectionsReverse() { + ArrayInverter inverter = new ArrayInverter(); + inverter.invertUsingCollectionsReverse(fruits); + + assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits); + } + + @Test + public void invertArrayWithStreams() { + ArrayInverter inverter = new ArrayInverter(); + + assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(inverter.invertUsingStreams(fruits)); + } + + @Test + public void invertArrayWithCommonsLang() { + ArrayInverter inverter = new ArrayInverter(); + inverter.invertUsingCommonsLang(fruits); + + assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits); + } + + @Test + public void invertArrayWithGuava() { + ArrayInverter inverter = new ArrayInverter(); + + assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(inverter.invertUsingGuava(fruits)); + } + +} diff --git a/core-java/src/test/java/com/baeldung/file/FilesTest.java b/core-java/src/test/java/com/baeldung/file/FilesTest.java index e17e8580aa..c5a5b8a3a1 100644 --- a/core-java/src/test/java/com/baeldung/file/FilesTest.java +++ b/core-java/src/test/java/com/baeldung/file/FilesTest.java @@ -91,4 +91,4 @@ public class FilesTest { new FileInputStream(fileName))) .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n"); } -} +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceTests.java b/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceTests.java new file mode 100644 index 0000000000..b19ed76189 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceTests.java @@ -0,0 +1,18 @@ +package com.baeldung.interfaces; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class InnerInterfaceTests { + @Test + public void whenCustomerListJoined_thenReturnsJoinedNames() { + Customer.List customerList = new CommaSeparatedCustomers(); + customerList.Add(new Customer("customer1")); + customerList.Add(new Customer("customer2")); + assertEquals("customer1,customer2", customerList.getCustomerNames()); + } +} diff --git a/core-java/src/test/java/com/baeldung/nestedclass/NewOuter.java b/core-java/src/test/java/com/baeldung/nestedclass/NewOuter.java index a3a723b30e..260f69fd1b 100644 --- a/core-java/src/test/java/com/baeldung/nestedclass/NewOuter.java +++ b/core-java/src/test/java/com/baeldung/nestedclass/NewOuter.java @@ -14,9 +14,9 @@ public class NewOuter { public void run() { System.out.println("a = " + a); System.out.println("b = " + b); - System.out.println("NewOuterTest.this.a = " + NewOuter.this.a); - System.out.println("NewOuterTest.b = " + NewOuter.b); - System.out.println("NewOuterTest.this.b = " + NewOuter.this.b); + System.out.println("NewOuter.this.a = " + NewOuter.this.a); + System.out.println("NewOuter.b = " + NewOuter.b); + System.out.println("NewOuter.this.b = " + NewOuter.this.b); } } diff --git a/core-java/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java b/core-java/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java index 8fb606c2fc..58826766e0 100644 --- a/core-java/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java +++ b/core-java/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java @@ -3,8 +3,6 @@ package com.baeldung.polymorphism; import static org.junit.Assert.*; import java.awt.image.BufferedImage; - -import org.junit.Ignore; import org.junit.Test; public class PolymorphismUnitTest { diff --git a/core-java/src/test/java/com/baeldung/tree/BinaryTreeTest.java b/core-java/src/test/java/com/baeldung/tree/BinaryTreeTest.java new file mode 100644 index 0000000000..2c20c730df --- /dev/null +++ b/core-java/src/test/java/com/baeldung/tree/BinaryTreeTest.java @@ -0,0 +1,85 @@ +package com.baeldung.tree; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class BinaryTreeTest { + + @Test + public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() { + + BinaryTree bt = createBinaryTree(); + + assertTrue(!bt.isEmpty()); + } + + @Test + public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() { + + BinaryTree bt = createBinaryTree(); + + assertTrue(bt.containsNode(6)); + assertTrue(bt.containsNode(4)); + + assertFalse(bt.containsNode(1)); + } + + @Test + public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() { + + BinaryTree bt = createBinaryTree(); + + assertTrue(bt.containsNode(9)); + bt.delete(9); + assertFalse(bt.containsNode(9)); + } + + @Test + public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() { + + BinaryTree bt = createBinaryTree(); + + bt.traverseInOrder(bt.root); + } + + @Test + public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() { + + BinaryTree bt = createBinaryTree(); + + bt.traversePreOrder(bt.root); + } + + @Test + public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() { + + BinaryTree bt = createBinaryTree(); + + bt.traversePostOrder(bt.root); + } + + @Test + public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() { + + BinaryTree bt = createBinaryTree(); + + bt.traverseLevelOrder(); + } + + private BinaryTree createBinaryTree() { + BinaryTree bt = new BinaryTree(); + + bt.add(6); + bt.add(4); + bt.add(8); + bt.add(3); + bt.add(5); + bt.add(7); + bt.add(9); + + return bt; + } + +} diff --git a/drools/README.MD b/drools/README.MD index b2259e2878..5efbe0d3c3 100644 --- a/drools/README.MD +++ b/drools/README.MD @@ -1,3 +1,4 @@ ### Relevant Articles: - [Introduction to Drools](http://www.baeldung.com/drools) - [Drools Using Rules from Excel Files](http://www.baeldung.com/drools-excel) +- [An Example of Backward Chaining in Drools](http://www.baeldung.com/drools-backward-chaining) diff --git a/dubbo/README.md b/dubbo/README.md new file mode 100644 index 0000000000..dec02f5cfc --- /dev/null +++ b/dubbo/README.md @@ -0,0 +1,4 @@ +## Relevant articles: + +- [Intro to Dubbo](http://www.baeldung.com/dubbo-intro) + diff --git a/dubbo/pom.xml b/dubbo/pom.xml new file mode 100644 index 0000000000..3faef99e8d --- /dev/null +++ b/dubbo/pom.xml @@ -0,0 +1,72 @@ + + 4.0.0 + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + dubbo + + + UTF-8 + UTF-8 + 1.8 + 2.5.7 + 3.4.11 + 0.10 + 2.19.1 + + + + + com.alibaba + dubbo + ${dubbo.version} + + + junit + junit + 4.12 + test + + + + org.apache.zookeeper + zookeeper + ${zookeeper.version} + + + + com.101tec + zkclient + ${zkclient.version} + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + maven-surefire-plugin + ${surefire.version} + + + **/*LiveTest.java + + + + + + + diff --git a/dubbo/src/main/java/com/alibaba/dubbo/registry/simple/SimpleRegistryService.java b/dubbo/src/main/java/com/alibaba/dubbo/registry/simple/SimpleRegistryService.java new file mode 100644 index 0000000000..bf4a5e201c --- /dev/null +++ b/dubbo/src/main/java/com/alibaba/dubbo/registry/simple/SimpleRegistryService.java @@ -0,0 +1,210 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.registry.simple; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.ConcurrentHashSet; +import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.common.utils.UrlUtils; +import com.alibaba.dubbo.registry.NotifyListener; +import com.alibaba.dubbo.registry.RegistryService; +import com.alibaba.dubbo.registry.support.AbstractRegistry; +import com.alibaba.dubbo.rpc.RpcContext; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * SimpleRegistryService + * + * @author william.liangf + */ +public class SimpleRegistryService extends AbstractRegistry { + + private final static Logger logger = LoggerFactory.getLogger(SimpleRegistryService.class); + private final ConcurrentMap> remoteRegistered = new ConcurrentHashMap>(); + private final ConcurrentMap>> remoteSubscribed = new ConcurrentHashMap>>(); + + public SimpleRegistryService() { + super(new URL("dubbo", NetUtils.getLocalHost(), 0, RegistryService.class.getName(), "file", "N/A")); + } + + public boolean isAvailable() { + return true; + } + + public List lookup(URL url) { + List urls = new ArrayList(); + for (URL u : getRegistered()) { + if (UrlUtils.isMatch(url, u)) { + urls.add(u); + } + } + return urls; + } + + public void register(URL url) { + String client = RpcContext.getContext().getRemoteAddressString(); + Set urls = remoteRegistered.get(client); + if (urls == null) { + remoteRegistered.putIfAbsent(client, new ConcurrentHashSet()); + urls = remoteRegistered.get(client); + } + urls.add(url); + super.register(url); + registered(url); + } + + public void unregister(URL url) { + String client = RpcContext.getContext().getRemoteAddressString(); + Set urls = remoteRegistered.get(client); + if (urls != null && urls.size() > 0) { + urls.remove(url); + } + super.unregister(url); + unregistered(url); + } + + public void subscribe(URL url, NotifyListener listener) { + if (getUrl().getPort() == 0) { + URL registryUrl = RpcContext.getContext().getUrl(); + if (registryUrl != null && registryUrl.getPort() > 0 + && RegistryService.class.getName().equals(registryUrl.getPath())) { + super.setUrl(registryUrl); + super.register(registryUrl); + } + } + String client = RpcContext.getContext().getRemoteAddressString(); + ConcurrentMap> clientListeners = remoteSubscribed.get(client); + if (clientListeners == null) { + remoteSubscribed.putIfAbsent(client, new ConcurrentHashMap>()); + clientListeners = remoteSubscribed.get(client); + } + Set listeners = clientListeners.get(url); + if (listeners == null) { + clientListeners.putIfAbsent(url, new ConcurrentHashSet()); + listeners = clientListeners.get(url); + } + listeners.add(listener); + super.subscribe(url, listener); + subscribed(url, listener); + } + + public void unsubscribe(URL url, NotifyListener listener) { + if (!Constants.ANY_VALUE.equals(url.getServiceInterface()) + && url.getParameter(Constants.REGISTER_KEY, true)) { + unregister(url); + } + String client = RpcContext.getContext().getRemoteAddressString(); + Map> clientListeners = remoteSubscribed.get(client); + if (clientListeners != null && clientListeners.size() > 0) { + Set listeners = clientListeners.get(url); + if (listeners != null && listeners.size() > 0) { + listeners.remove(listener); + } + } + } + + protected void registered(URL url) { + for (Map.Entry> entry : getSubscribed().entrySet()) { + URL key = entry.getKey(); + if (UrlUtils.isMatch(key, url)) { + List list = lookup(key); + for (NotifyListener listener : entry.getValue()) { + listener.notify(list); + } + } + } + } + + protected void unregistered(URL url) { + for (Map.Entry> entry : getSubscribed().entrySet()) { + URL key = entry.getKey(); + if (UrlUtils.isMatch(key, url)) { + List list = lookup(key); + for (NotifyListener listener : entry.getValue()) { + listener.notify(list); + } + } + } + } + + protected void subscribed(final URL url, final NotifyListener listener) { + if (Constants.ANY_VALUE.equals(url.getServiceInterface())) { + new Thread(new Runnable() { + public void run() { + Map> map = new HashMap>(); + for (URL u : getRegistered()) { + if (UrlUtils.isMatch(url, u)) { + String service = u.getServiceInterface(); + List list = map.get(service); + if (list == null) { + list = new ArrayList(); + map.put(service, list); + } + list.add(u); + } + } + for (List list : map.values()) { + try { + listener.notify(list); + } catch (Throwable e) { + logger.warn("Discard to notify " + url.getServiceKey() + " to listener " + listener); + } + } + } + }, "DubboMonitorNotifier").start(); + } else { + List list = lookup(url); + try { + listener.notify(list); + } catch (Throwable e) { + logger.warn("Discard to notify " + url.getServiceKey() + " to listener " + listener); + } + } + } + + public void disconnect() { + String client = RpcContext.getContext().getRemoteAddressString(); + if (logger.isInfoEnabled()) { + logger.info("Disconnected " + client); + } + Set urls = remoteRegistered.get(client); + if (urls != null && urls.size() > 0) { + for (URL url : urls) { + unregister(url); + } + } + Map> listeners = remoteSubscribed.get(client); + if (listeners != null && listeners.size() > 0) { + for (Map.Entry> entry : listeners.entrySet()) { + URL url = entry.getKey(); + for (NotifyListener listener : entry.getValue()) { + unsubscribe(url, listener); + } + } + } + } + +} \ No newline at end of file diff --git a/dubbo/src/main/java/com/baeldung/dubbo/remote/GreetingsFailoverServiceImpl.java b/dubbo/src/main/java/com/baeldung/dubbo/remote/GreetingsFailoverServiceImpl.java new file mode 100644 index 0000000000..2ad26beac3 --- /dev/null +++ b/dubbo/src/main/java/com/baeldung/dubbo/remote/GreetingsFailoverServiceImpl.java @@ -0,0 +1,14 @@ +package com.baeldung.dubbo.remote; + +/** + * @author aiet + */ +public class GreetingsFailoverServiceImpl implements GreetingsService { + + @Override + public String sayHi(String name) { + System.out.println("failover implementation"); + return "hi, failover " + name; + } + +} diff --git a/dubbo/src/main/java/com/baeldung/dubbo/remote/GreetingsService.java b/dubbo/src/main/java/com/baeldung/dubbo/remote/GreetingsService.java new file mode 100644 index 0000000000..337c4c83e7 --- /dev/null +++ b/dubbo/src/main/java/com/baeldung/dubbo/remote/GreetingsService.java @@ -0,0 +1,10 @@ +package com.baeldung.dubbo.remote; + +/** + * @author aiet + */ +public interface GreetingsService { + + String sayHi(String name); + +} diff --git a/dubbo/src/main/java/com/baeldung/dubbo/remote/GreetingsServiceImpl.java b/dubbo/src/main/java/com/baeldung/dubbo/remote/GreetingsServiceImpl.java new file mode 100644 index 0000000000..a11d9588d8 --- /dev/null +++ b/dubbo/src/main/java/com/baeldung/dubbo/remote/GreetingsServiceImpl.java @@ -0,0 +1,14 @@ +package com.baeldung.dubbo.remote; + +/** + * @author aiet + */ +public class GreetingsServiceImpl implements GreetingsService { + + @Override + public String sayHi(String name) { + System.out.println("default implementation"); + return "hi, " + name; + } + +} diff --git a/dubbo/src/main/java/com/baeldung/dubbo/remote/GreetingsServiceSpecialImpl.java b/dubbo/src/main/java/com/baeldung/dubbo/remote/GreetingsServiceSpecialImpl.java new file mode 100644 index 0000000000..37449da8d8 --- /dev/null +++ b/dubbo/src/main/java/com/baeldung/dubbo/remote/GreetingsServiceSpecialImpl.java @@ -0,0 +1,20 @@ +package com.baeldung.dubbo.remote; + +import static java.util.concurrent.TimeUnit.SECONDS; + +/** + * @author aiet + */ +public class GreetingsServiceSpecialImpl implements GreetingsService { + + @Override + public String sayHi(String name) { + try { + System.out.println("specially called"); + SECONDS.sleep(5); + } catch (Exception ignored) { + } + return "hi, " + name; + } + +} diff --git a/dubbo/src/test/java/com/baeldung/dubbo/APIConfigurationLiveTest.java b/dubbo/src/test/java/com/baeldung/dubbo/APIConfigurationLiveTest.java new file mode 100644 index 0000000000..27c77bf9df --- /dev/null +++ b/dubbo/src/test/java/com/baeldung/dubbo/APIConfigurationLiveTest.java @@ -0,0 +1,57 @@ +package com.baeldung.dubbo; + +import com.alibaba.dubbo.config.ApplicationConfig; +import com.alibaba.dubbo.config.ReferenceConfig; +import com.alibaba.dubbo.config.RegistryConfig; +import com.alibaba.dubbo.config.ServiceConfig; +import com.baeldung.dubbo.remote.GreetingsService; +import com.baeldung.dubbo.remote.GreetingsServiceImpl; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * @author aiet + */ +public class APIConfigurationLiveTest { + + @Before + public void initProvider() { + ApplicationConfig application = new ApplicationConfig(); + application.setName("demo-provider"); + application.setVersion("1.0"); + + RegistryConfig registryConfig = new RegistryConfig(); + registryConfig.setAddress("multicast://224.1.1.1:9090"); + + ServiceConfig service = new ServiceConfig<>(); + service.setApplication(application); + service.setRegistry(registryConfig); + service.setInterface(GreetingsService.class); + service.setRef(new GreetingsServiceImpl()); + + service.export(); + } + + @Test + public void givenProviderConsumer_whenSayHi_thenGotResponse() { + ApplicationConfig application = new ApplicationConfig(); + application.setName("demo-consumer"); + application.setVersion("1.0"); + + RegistryConfig registryConfig = new RegistryConfig(); + registryConfig.setAddress("multicast://224.1.1.1:9090"); + + ReferenceConfig reference = new ReferenceConfig<>(); + reference.setApplication(application); + reference.setRegistry(registryConfig); + reference.setInterface(GreetingsService.class); + + GreetingsService greetingsService = reference.get(); + String hiMessage = greetingsService.sayHi("baeldung"); + + assertEquals("hi, baeldung", hiMessage); + } + +} diff --git a/dubbo/src/test/java/com/baeldung/dubbo/ClusterDynamicLoadBalanceLiveTest.java b/dubbo/src/test/java/com/baeldung/dubbo/ClusterDynamicLoadBalanceLiveTest.java new file mode 100644 index 0000000000..408d5af368 --- /dev/null +++ b/dubbo/src/test/java/com/baeldung/dubbo/ClusterDynamicLoadBalanceLiveTest.java @@ -0,0 +1,70 @@ +package com.baeldung.dubbo; + +import com.baeldung.dubbo.remote.GreetingsService; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import java.util.ArrayList; +import java.util.List; +import java.util.OptionalDouble; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * @author aiet + */ +public class ClusterDynamicLoadBalanceLiveTest { + + private ExecutorService executorService; + + @Before + public void initRemote() { + executorService = Executors.newFixedThreadPool(2); + executorService.submit(() -> { + ClassPathXmlApplicationContext remoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-default.xml"); + remoteContext.start(); + }); + executorService.submit(() -> { + SECONDS.sleep(2); + ClassPathXmlApplicationContext backupRemoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-special.xml"); + backupRemoteContext.start(); + return null; + }); + } + + @Test + public void givenProviderCluster_whenConsumerSaysHi_thenResponseBalanced() throws InterruptedException { + ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("cluster/consumer-app-lb.xml"); + localContext.start(); + GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService"); + List elapseList = new ArrayList<>(6); + for (int i = 0; i < 6; i++) { + long current = System.currentTimeMillis(); + String hiMessage = greetingsService.sayHi("baeldung"); + assertNotNull(hiMessage); + elapseList.add(System.currentTimeMillis() - current); + SECONDS.sleep(1); + } + + OptionalDouble avgElapse = elapseList + .stream() + .mapToLong(e -> e) + .average(); + assertTrue(avgElapse.isPresent()); + assertTrue(avgElapse.getAsDouble() > 1666.0); + + } + + @After + public void destroy() { + executorService.shutdown(); + } + +} diff --git a/dubbo/src/test/java/com/baeldung/dubbo/ClusterFailoverLiveTest.java b/dubbo/src/test/java/com/baeldung/dubbo/ClusterFailoverLiveTest.java new file mode 100644 index 0000000000..721363d3d1 --- /dev/null +++ b/dubbo/src/test/java/com/baeldung/dubbo/ClusterFailoverLiveTest.java @@ -0,0 +1,52 @@ +package com.baeldung.dubbo; + +import com.baeldung.dubbo.remote.GreetingsService; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * @author aiet + */ +public class ClusterFailoverLiveTest { + + private ExecutorService executorService; + + @Before + public void initRemote() { + executorService = Executors.newFixedThreadPool(2); + executorService.submit(() -> { + ClassPathXmlApplicationContext backupRemoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-special.xml"); + backupRemoteContext.start(); + }); + executorService.submit(() -> { + ClassPathXmlApplicationContext remoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-failover.xml"); + remoteContext.start(); + }); + + } + + @Test + public void givenProviderCluster_whenConsumerSaysHi_thenGotFailoverResponse() { + ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("cluster/consumer-app-failtest.xml"); + localContext.start(); + GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService"); + String hiMessage = greetingsService.sayHi("baeldung"); + + assertNotNull(hiMessage); + assertEquals("hi, failover baeldung", hiMessage); + } + + @After + public void destroy() { + executorService.shutdown(); + } + +} diff --git a/dubbo/src/test/java/com/baeldung/dubbo/ClusterFailsafeLiveTest.java b/dubbo/src/test/java/com/baeldung/dubbo/ClusterFailsafeLiveTest.java new file mode 100644 index 0000000000..29a10fa20a --- /dev/null +++ b/dubbo/src/test/java/com/baeldung/dubbo/ClusterFailsafeLiveTest.java @@ -0,0 +1,47 @@ +package com.baeldung.dubbo; + +import com.baeldung.dubbo.remote.GreetingsService; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +/** + * @author aiet + */ +public class ClusterFailsafeLiveTest { + + private ExecutorService executorService; + + @Before + public void initRemote() { + executorService = Executors.newFixedThreadPool(1); + executorService.submit(() -> { + ClassPathXmlApplicationContext remoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-special-failsafe.xml"); + remoteContext.start(); + }); + } + + @Test + public void givenProviderCluster_whenConsumerSaysHi_thenGotFailsafeResponse() { + ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("cluster/consumer-app-failtest.xml"); + localContext.start(); + GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService"); + String hiMessage = greetingsService.sayHi("baeldung"); + + assertNull(hiMessage); + } + + @After + public void destroy() { + executorService.shutdown(); + } + +} diff --git a/dubbo/src/test/java/com/baeldung/dubbo/ClusterLoadBalanceLiveTest.java b/dubbo/src/test/java/com/baeldung/dubbo/ClusterLoadBalanceLiveTest.java new file mode 100644 index 0000000000..b880dfe843 --- /dev/null +++ b/dubbo/src/test/java/com/baeldung/dubbo/ClusterLoadBalanceLiveTest.java @@ -0,0 +1,66 @@ +package com.baeldung.dubbo; + +import com.baeldung.dubbo.remote.GreetingsService; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import java.util.ArrayList; +import java.util.List; +import java.util.OptionalDouble; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * @author aiet + */ +public class ClusterLoadBalanceLiveTest { + + private ExecutorService executorService; + + @Before + public void initRemote() { + executorService = Executors.newFixedThreadPool(2); + executorService.submit(() -> { + ClassPathXmlApplicationContext remoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-default.xml"); + remoteContext.start(); + }); + executorService.submit(() -> { + ClassPathXmlApplicationContext backupRemoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-special.xml"); + backupRemoteContext.start(); + }); + } + + @Test + public void givenProviderCluster_whenConsumerSaysHi_thenResponseBalanced() { + ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("cluster/consumer-app-lb.xml"); + localContext.start(); + GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService"); + List elapseList = new ArrayList<>(6); + for (int i = 0; i < 6; i++) { + long current = System.currentTimeMillis(); + String hiMessage = greetingsService.sayHi("baeldung"); + assertNotNull(hiMessage); + elapseList.add(System.currentTimeMillis() - current); + } + + OptionalDouble avgElapse = elapseList + .stream() + .mapToLong(e -> e) + .average(); + assertTrue(avgElapse.isPresent()); + System.out.println(avgElapse.getAsDouble()); + assertTrue(avgElapse.getAsDouble() > 2500.0); + + } + + @After + public void destroy() { + executorService.shutdown(); + } + +} diff --git a/dubbo/src/test/java/com/baeldung/dubbo/MulticastRegistryLiveTest.java b/dubbo/src/test/java/com/baeldung/dubbo/MulticastRegistryLiveTest.java new file mode 100644 index 0000000000..13dc5d3f1e --- /dev/null +++ b/dubbo/src/test/java/com/baeldung/dubbo/MulticastRegistryLiveTest.java @@ -0,0 +1,36 @@ +package com.baeldung.dubbo; + +import com.baeldung.dubbo.remote.GreetingsService; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * @author aiet + */ +public class MulticastRegistryLiveTest { + + private ClassPathXmlApplicationContext remoteContext; + + @Before + public void initRemote() { + remoteContext = new ClassPathXmlApplicationContext("multicast/provider-app.xml"); + remoteContext.start(); + } + + @Test + public void givenProvider_whenConsumerSaysHi_thenGotResponse() { + ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("multicast/consumer-app.xml"); + localContext.start(); + GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService"); + String hiMessage = greetingsService.sayHi("baeldung"); + + assertNotNull(hiMessage); + assertEquals("hi, baeldung", hiMessage); + } + +} diff --git a/dubbo/src/test/java/com/baeldung/dubbo/ResultCacheLiveTest.java b/dubbo/src/test/java/com/baeldung/dubbo/ResultCacheLiveTest.java new file mode 100644 index 0000000000..401ebc9b94 --- /dev/null +++ b/dubbo/src/test/java/com/baeldung/dubbo/ResultCacheLiveTest.java @@ -0,0 +1,47 @@ +package com.baeldung.dubbo; + +import com.baeldung.dubbo.remote.GreetingsService; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import static org.junit.Assert.*; + +/** + * @author aiet + */ +public class ResultCacheLiveTest { + + private ClassPathXmlApplicationContext remoteContext; + + @Before + public void initRemote() { + remoteContext = new ClassPathXmlApplicationContext("multicast/provider-app-special.xml"); + remoteContext.start(); + } + + @Test + public void givenProvider_whenConsumerSaysHi_thenGotResponse() { + ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("multicast/consumer-app.xml"); + localContext.start(); + GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService"); + + long before = System.currentTimeMillis(); + String hiMessage = greetingsService.sayHi("baeldung"); + + long timeElapsed = System.currentTimeMillis() - before; + assertTrue(timeElapsed > 5000); + assertNotNull(hiMessage); + assertEquals("hi, baeldung", hiMessage); + + + before = System.currentTimeMillis(); + hiMessage = greetingsService.sayHi("baeldung"); + timeElapsed = System.currentTimeMillis() - before; + assertTrue(timeElapsed < 1000); + assertNotNull(hiMessage); + assertEquals("hi, baeldung", hiMessage); + } + +} diff --git a/dubbo/src/test/java/com/baeldung/dubbo/SimpleRegistryLiveTest.java b/dubbo/src/test/java/com/baeldung/dubbo/SimpleRegistryLiveTest.java new file mode 100644 index 0000000000..72f15cf7ec --- /dev/null +++ b/dubbo/src/test/java/com/baeldung/dubbo/SimpleRegistryLiveTest.java @@ -0,0 +1,39 @@ +package com.baeldung.dubbo; + +import com.baeldung.dubbo.remote.GreetingsService; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * @author aiet + */ +public class SimpleRegistryLiveTest { + + private ClassPathXmlApplicationContext remoteContext; + private ClassPathXmlApplicationContext registryContext; + + @Before + public void initRemote() { + registryContext = new ClassPathXmlApplicationContext("simple/registry.xml"); + registryContext.start(); + + remoteContext = new ClassPathXmlApplicationContext("simple/provider-app.xml"); + remoteContext.start(); + } + + @Test + public void givenProvider_whenConsumerSaysHi_thenGotResponse() { + ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("simple/consumer-app.xml"); + localContext.start(); + GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService"); + String hiMessage = greetingsService.sayHi("baeldung"); + + assertNotNull(hiMessage); + assertEquals("hi, baeldung", hiMessage); + } + +} diff --git a/dubbo/src/test/resources/cluster/consumer-app-failtest.xml b/dubbo/src/test/resources/cluster/consumer-app-failtest.xml new file mode 100644 index 0000000000..beb982db22 --- /dev/null +++ b/dubbo/src/test/resources/cluster/consumer-app-failtest.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo/src/test/resources/cluster/consumer-app-lb.xml b/dubbo/src/test/resources/cluster/consumer-app-lb.xml new file mode 100644 index 0000000000..268e21b902 --- /dev/null +++ b/dubbo/src/test/resources/cluster/consumer-app-lb.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo/src/test/resources/cluster/provider-app-default.xml b/dubbo/src/test/resources/cluster/provider-app-default.xml new file mode 100644 index 0000000000..cb51bc1771 --- /dev/null +++ b/dubbo/src/test/resources/cluster/provider-app-default.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo/src/test/resources/cluster/provider-app-failover.xml b/dubbo/src/test/resources/cluster/provider-app-failover.xml new file mode 100644 index 0000000000..95cbee1f90 --- /dev/null +++ b/dubbo/src/test/resources/cluster/provider-app-failover.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo/src/test/resources/cluster/provider-app-special-failsafe.xml b/dubbo/src/test/resources/cluster/provider-app-special-failsafe.xml new file mode 100644 index 0000000000..7a7a139bb3 --- /dev/null +++ b/dubbo/src/test/resources/cluster/provider-app-special-failsafe.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo/src/test/resources/cluster/provider-app-special.xml b/dubbo/src/test/resources/cluster/provider-app-special.xml new file mode 100644 index 0000000000..8e5dc07d61 --- /dev/null +++ b/dubbo/src/test/resources/cluster/provider-app-special.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo/src/test/resources/log4j.properties b/dubbo/src/test/resources/log4j.properties new file mode 100644 index 0000000000..4c15f1b4e0 --- /dev/null +++ b/dubbo/src/test/resources/log4j.properties @@ -0,0 +1,6 @@ +log4j.rootLogger=INFO, stdout + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/dubbo/src/test/resources/multicast/consumer-app.xml b/dubbo/src/test/resources/multicast/consumer-app.xml new file mode 100644 index 0000000000..da9a41fd61 --- /dev/null +++ b/dubbo/src/test/resources/multicast/consumer-app.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo/src/test/resources/multicast/provider-app-special.xml b/dubbo/src/test/resources/multicast/provider-app-special.xml new file mode 100644 index 0000000000..4b22b5aace --- /dev/null +++ b/dubbo/src/test/resources/multicast/provider-app-special.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo/src/test/resources/multicast/provider-app.xml b/dubbo/src/test/resources/multicast/provider-app.xml new file mode 100644 index 0000000000..065d5ddad8 --- /dev/null +++ b/dubbo/src/test/resources/multicast/provider-app.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo/src/test/resources/simple/consumer-app.xml b/dubbo/src/test/resources/simple/consumer-app.xml new file mode 100644 index 0000000000..91f7a666e4 --- /dev/null +++ b/dubbo/src/test/resources/simple/consumer-app.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo/src/test/resources/simple/provider-app.xml b/dubbo/src/test/resources/simple/provider-app.xml new file mode 100644 index 0000000000..9880172249 --- /dev/null +++ b/dubbo/src/test/resources/simple/provider-app.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo/src/test/resources/simple/registry.xml b/dubbo/src/test/resources/simple/registry.xml new file mode 100644 index 0000000000..9d1372da10 --- /dev/null +++ b/dubbo/src/test/resources/simple/registry.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/flyway/pom.xml b/flyway/pom.xml index 2774602654..5cb8fabe67 100644 --- a/flyway/pom.xml +++ b/flyway/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.baeldung flyway 1.0 flyway + pom A sample project to demonstrate Flyway migrations @@ -13,6 +13,10 @@ 1.0.0-SNAPSHOT + + spring-flyway + + mysql @@ -20,6 +24,17 @@ ${mysql.version} + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + @@ -32,5 +47,6 @@ 6.0.5 4.0.3 + 1.5.8.RELEASE \ No newline at end of file diff --git a/flyway/spring-flyway/.gitignore b/flyway/spring-flyway/.gitignore new file mode 100644 index 0000000000..2af7cefb0a --- /dev/null +++ b/flyway/spring-flyway/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/flyway/spring-flyway/pom.xml b/flyway/spring-flyway/pom.xml new file mode 100644 index 0000000000..cf5703cfab --- /dev/null +++ b/flyway/spring-flyway/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + spring-flyway + 0.0.1-SNAPSHOT + jar + + spring-flyway + Spring Boot Test Flyway Migrations + + + flyway + com.baeldung + 1.0 + ../../flyway + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.flywaydb + flyway-core + + + org.projectlombok + lombok + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/SpringFlywayApplication.java b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/SpringFlywayApplication.java new file mode 100644 index 0000000000..9218fbc88d --- /dev/null +++ b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/SpringFlywayApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.springflyway; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringFlywayApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringFlywayApplication.class, args); + } +} diff --git a/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/entities/Customer.java b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/entities/Customer.java new file mode 100644 index 0000000000..194b961d2d --- /dev/null +++ b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/entities/Customer.java @@ -0,0 +1,28 @@ +package com.baeldung.springflyway.entities; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +@Data +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class Customer { + + @Id + @GeneratedValue + private Long id; + + private String firstName; + private String lastName; + + private String email; + +} diff --git a/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/migration/V2__uk_lastname_customer.java b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/migration/V2__uk_lastname_customer.java new file mode 100644 index 0000000000..52b851546b --- /dev/null +++ b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/migration/V2__uk_lastname_customer.java @@ -0,0 +1,14 @@ +package com.baeldung.springflyway.migration; + +import org.flywaydb.core.api.migration.spring.SpringJdbcMigration; +import org.springframework.jdbc.core.JdbcTemplate; + +public class V2__uk_lastname_customer implements SpringJdbcMigration { + + final String CUSTOMER_LASTNAME_UK = "ALTER TABLE customer ADD CONSTRAINT uk_customer_lastname UNIQUE(last_name);"; + + @Override + public void migrate(final JdbcTemplate jdbcTemplate) throws Exception { + jdbcTemplate.execute(CUSTOMER_LASTNAME_UK); + } +} diff --git a/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/repositories/CustomerRepository.java b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/repositories/CustomerRepository.java new file mode 100644 index 0000000000..0a1fb5a146 --- /dev/null +++ b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/repositories/CustomerRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.springflyway.repositories; + +import com.baeldung.springflyway.entities.Customer; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface CustomerRepository extends JpaRepository { + + Optional findByEmail(String email); +} diff --git a/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryInitialMigrationTest.java b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryInitialMigrationTest.java new file mode 100644 index 0000000000..b3f2cb29e1 --- /dev/null +++ b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryInitialMigrationTest.java @@ -0,0 +1,28 @@ +package com.baeldung.springflyway; + +import com.baeldung.springflyway.entities.Customer; +import com.baeldung.springflyway.repositories.CustomerRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class CustomerRepositoryInitialMigrationTest { + + @Autowired CustomerRepository customerRepository; + + @Test + public void givenSchemaCreationMigration_whenTryingToCreateACustomer_thenSuccess() { + Customer customer = customerRepository.save(Customer + .builder() + .email("customer@email.com") + .build()); + assertNotNull(customer.getId()); + } + +} diff --git a/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryInsertDataMigrationTest.java b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryInsertDataMigrationTest.java new file mode 100644 index 0000000000..369e61d98f --- /dev/null +++ b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryInsertDataMigrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.springflyway; + +import com.baeldung.springflyway.entities.Customer; +import com.baeldung.springflyway.repositories.CustomerRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.*; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class CustomerRepositoryInsertDataMigrationTest { + + @Autowired CustomerRepository customerRepository; + + @Test + public void givenASetInsertData_whenRunningMigrationsWithSuccess_thenASpecificCustomerIsFound() { + Optional customerOptional = customerRepository.findByEmail("email@email.com"); + assertTrue(customerOptional.isPresent()); + } + + @Test + public void givenASetInsertData_whenRunningMigrationsWithSuccess_thenASetOfCustomersIsFound() { + List customers = customerRepository.findAll(); + assertNotNull(customers); + assertEquals(customers.size(), 6); + } + +} diff --git a/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryNotNullConstraintMigrationTest.java b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryNotNullConstraintMigrationTest.java new file mode 100644 index 0000000000..90517c9225 --- /dev/null +++ b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryNotNullConstraintMigrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.springflyway; + +import com.baeldung.springflyway.entities.Customer; +import com.baeldung.springflyway.repositories.CustomerRepository; +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.dao.DataIntegrityViolationException; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class CustomerRepositoryNotNullConstraintMigrationTest { + + @Autowired CustomerRepository customerRepository; + + @Test(expected = DataIntegrityViolationException.class) + public void givenTheNotNullConstraintMigrations_whenInsertingACustomerWithNullEmail_thenThrowException() { + customerRepository.save(Customer + .builder() + .build()); + } + +} diff --git a/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryUniqueConstraintJavaMigrationTest.java b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryUniqueConstraintJavaMigrationTest.java new file mode 100644 index 0000000000..e5ba782fda --- /dev/null +++ b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryUniqueConstraintJavaMigrationTest.java @@ -0,0 +1,29 @@ +package com.baeldung.springflyway; + +import com.baeldung.springflyway.entities.Customer; +import com.baeldung.springflyway.repositories.CustomerRepository; +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.dao.DataIntegrityViolationException; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(properties = { + "flyway.locations[0]=db/migration", "flyway.locations[1]=com/baeldung/springflyway/migration" +}) +public class CustomerRepositoryUniqueConstraintJavaMigrationTest { + + @Autowired CustomerRepository customerRepository; + + @Test(expected = DataIntegrityViolationException.class) + public void givenTheUniqueConstraintMigrations_whenInsertingAnExistingLastNameCustomer_thenThrowException() { + customerRepository.save(Customer + .builder() + .lastName("LastName") + .build()); + + } + +} diff --git a/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryUniqueConstraintMigrationTest.java b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryUniqueConstraintMigrationTest.java new file mode 100644 index 0000000000..9fa2dee42d --- /dev/null +++ b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryUniqueConstraintMigrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.springflyway; + +import com.baeldung.springflyway.entities.Customer; +import com.baeldung.springflyway.repositories.CustomerRepository; +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.dao.DataIntegrityViolationException; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class CustomerRepositoryUniqueConstraintMigrationTest { + + @Autowired CustomerRepository customerRepository; + + @Test(expected = DataIntegrityViolationException.class) + public void givenTheUniqueConstraintMigrations_whenInsertingAnExistingEmailCustomer_thenThrowException() { + customerRepository.save(Customer + .builder() + .email("email@email.com") + .build()); + + } + +} diff --git a/flyway/spring-flyway/src/test/resources/application.properties b/flyway/spring-flyway/src/test/resources/application.properties new file mode 100644 index 0000000000..5656ca79ce --- /dev/null +++ b/flyway/spring-flyway/src/test/resources/application.properties @@ -0,0 +1 @@ +spring.jpa.hibernate.ddl-auto=validate \ No newline at end of file diff --git a/flyway/spring-flyway/src/test/resources/db/migration/V1_0__create_table_customer.sql b/flyway/spring-flyway/src/test/resources/db/migration/V1_0__create_table_customer.sql new file mode 100644 index 0000000000..8c65253ed8 --- /dev/null +++ b/flyway/spring-flyway/src/test/resources/db/migration/V1_0__create_table_customer.sql @@ -0,0 +1,6 @@ +create table if not exists customer ( + id bigint AUTO_INCREMENT not null primary key, + first_name varchar(255) , + last_name varchar(255) , + email varchar(255) +); \ No newline at end of file diff --git a/flyway/spring-flyway/src/test/resources/db/migration/V1_1__insert_customer.sql b/flyway/spring-flyway/src/test/resources/db/migration/V1_1__insert_customer.sql new file mode 100644 index 0000000000..6bba6e00a1 --- /dev/null +++ b/flyway/spring-flyway/src/test/resources/db/migration/V1_1__insert_customer.sql @@ -0,0 +1,6 @@ +insert into customer (first_name, last_name, email) values ('FirstName', 'LastName', 'email@email.com'); +insert into customer (first_name, last_name, email) values ('FirstName1', 'LastName1', 'email1@email.com'); +insert into customer (first_name, last_name, email) values ('FirstName2', 'LastName2', 'email2@email.com'); +insert into customer (first_name, last_name, email) values ('FirstName3', 'LastName3', 'email3@email.com'); +insert into customer (first_name, last_name, email) values ('FirstName4', 'LastName4', 'email4@email.com'); +insert into customer (first_name, last_name, email) values ('FirstName5', 'LastName5', 'email5@email.com'); \ No newline at end of file diff --git a/flyway/spring-flyway/src/test/resources/db/migration/V1_2__make_email_not_null.sql b/flyway/spring-flyway/src/test/resources/db/migration/V1_2__make_email_not_null.sql new file mode 100644 index 0000000000..b1cc396741 --- /dev/null +++ b/flyway/spring-flyway/src/test/resources/db/migration/V1_2__make_email_not_null.sql @@ -0,0 +1 @@ +ALTER TABLE customer ALTER email SET NOT NULL; \ No newline at end of file diff --git a/flyway/spring-flyway/src/test/resources/db/migration/V1_3__make_email_unique.sql b/flyway/spring-flyway/src/test/resources/db/migration/V1_3__make_email_unique.sql new file mode 100644 index 0000000000..19d738fe46 --- /dev/null +++ b/flyway/spring-flyway/src/test/resources/db/migration/V1_3__make_email_unique.sql @@ -0,0 +1 @@ +ALTER TABLE customer ADD CONSTRAINT uk_customer_email UNIQUE(email); \ No newline at end of file diff --git a/gradle/README.md b/gradle/README.md index ff12555376..dd5ea03a18 100644 --- a/gradle/README.md +++ b/gradle/README.md @@ -1 +1,2 @@ ## Relevant articles: +- [Introduction to Gradle](http://www.baeldung.com/gradle) diff --git a/gradle/plugin/build.gradle b/gradle/plugin/build.gradle new file mode 100644 index 0000000000..8d7329c1b0 --- /dev/null +++ b/gradle/plugin/build.gradle @@ -0,0 +1,14 @@ + repositories{ + mavenCentral() + } + apply plugin: 'java' + apply plugin: 'maven' + apply plugin: com.baeldung.GreetingPlugin + dependencies { + compile gradleApi() + } + + greeting { + greeter = "Stranger" + message = "Message from the build script!" + } \ No newline at end of file diff --git a/gradle/plugin/buildSrc/src/main/java/com/baeldung/GreetingPlugin.java b/gradle/plugin/buildSrc/src/main/java/com/baeldung/GreetingPlugin.java new file mode 100644 index 0000000000..ad32ecfe91 --- /dev/null +++ b/gradle/plugin/buildSrc/src/main/java/com/baeldung/GreetingPlugin.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.gradle.api.Plugin; +import org.gradle.api.Project; + +public class GreetingPlugin implements Plugin { + @Override + public void apply(Project project) { + + GreetingPluginExtension extension = project.getExtensions().create("greeting", GreetingPluginExtension.class); + + project.task("hello").doLast(task -> { + System.out.println("Hello, " + extension.getGreeter()); + System.out.println("I have a message for You: " + extension.getMessage()); } + ); + } +} \ No newline at end of file diff --git a/gradle/plugin/buildSrc/src/main/java/com/baeldung/GreetingPluginExtension.java b/gradle/plugin/buildSrc/src/main/java/com/baeldung/GreetingPluginExtension.java new file mode 100644 index 0000000000..2ff64a43f5 --- /dev/null +++ b/gradle/plugin/buildSrc/src/main/java/com/baeldung/GreetingPluginExtension.java @@ -0,0 +1,22 @@ +package com.baeldung; + +public class GreetingPluginExtension { + private String greeter = "Baeldung"; + private String message = "Message from Plugin!"; + + public String getGreeter() { + return greeter; + } + + public void setGreeter(String greeter) { + this.greeter = greeter; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/guest/remote-debugging/README.md b/guest/remote-debugging/README.md new file mode 100644 index 0000000000..cc63e7fd59 --- /dev/null +++ b/guest/remote-debugging/README.md @@ -0,0 +1,16 @@ +## Building + +To build the module, use Maven's `package` goal: + +``` +mvn clean package +``` + +The `war` file will be available at `target/remote-debugging.war` + +## Running + +The `war` application is deployed to Apache Tomcat 8 or any other Java Web or Application server. +To deploy it to the Apache Tomcat 8 server, drop it in the `tomcat/webapps` directory. + +The service then will be accessible at http://localhost:8080/remote-debugging/hello?name=John \ No newline at end of file diff --git a/guest/remote-debugging/pom.xml b/guest/remote-debugging/pom.xml new file mode 100644 index 0000000000..d958d4c681 --- /dev/null +++ b/guest/remote-debugging/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + com.stackify + java-remote-debugging + 0.0.1-SNAPSHOT + war + + + org.springframework.boot + spring-boot-starter-parent + 1.5.8.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + + + remote-debugging + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/guest/remote-debugging/src/main/java/com/stackify/debug/JavaRemoteDebuggingApplication.java b/guest/remote-debugging/src/main/java/com/stackify/debug/JavaRemoteDebuggingApplication.java new file mode 100644 index 0000000000..9d1a632638 --- /dev/null +++ b/guest/remote-debugging/src/main/java/com/stackify/debug/JavaRemoteDebuggingApplication.java @@ -0,0 +1,12 @@ +package com.stackify.debug; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class JavaRemoteDebuggingApplication { + + public static void main(String[] args) { + SpringApplication.run(JavaRemoteDebuggingApplication.class, args); + } +} diff --git a/guest/remote-debugging/src/main/java/com/stackify/debug/config/WebInitializer.java b/guest/remote-debugging/src/main/java/com/stackify/debug/config/WebInitializer.java new file mode 100644 index 0000000000..b69e2b6c77 --- /dev/null +++ b/guest/remote-debugging/src/main/java/com/stackify/debug/config/WebInitializer.java @@ -0,0 +1,12 @@ +package com.stackify.debug.config; + +import com.stackify.debug.JavaRemoteDebuggingApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.support.SpringBootServletInitializer; + +public class WebInitializer extends SpringBootServletInitializer { + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(JavaRemoteDebuggingApplication.class); + } +} diff --git a/guest/remote-debugging/src/main/java/com/stackify/debug/rest/HelloController.java b/guest/remote-debugging/src/main/java/com/stackify/debug/rest/HelloController.java new file mode 100644 index 0000000000..8c614a36ec --- /dev/null +++ b/guest/remote-debugging/src/main/java/com/stackify/debug/rest/HelloController.java @@ -0,0 +1,16 @@ +package com.stackify.debug.rest; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController("/hello") +public class HelloController { + + @GetMapping + public String hello(@RequestParam("name") String name) { + String message = "Hello, " + name; + return message; + } + +} diff --git a/hibernate5/README.md b/hibernate5/README.md index 4690ebbe76..d480a7455c 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -2,3 +2,5 @@ - [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping) - [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers) +- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time) +- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance) diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index f1fc22d29a..25fc0d7b02 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -6,6 +6,7 @@ import com.baeldung.hibernate.pojo.OrderEntry; import com.baeldung.hibernate.pojo.OrderEntryIdClass; import com.baeldung.hibernate.pojo.OrderEntryPK; import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; import com.baeldung.hibernate.pojo.Product; import com.baeldung.hibernate.pojo.Phone; import com.baeldung.hibernate.pojo.TemporalValues; @@ -79,6 +80,7 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(Car.class); metadataSources.addAnnotatedClass(Bag.class); metadataSources.addAnnotatedClass(PointEntity.class); + metadataSources.addAnnotatedClass(PolygonEntity.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder() diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java new file mode 100644 index 0000000000..69208c8cd4 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo; + +import com.vividsolutions.jts.geom.Polygon; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class PolygonEntity { + + @Id + @GeneratedValue + private Long id; + + private Polygon polygon; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Polygon getPolygon() { + return polygon; + } + + public void setPolygon(Polygon polygon) { + this.polygon = polygon; + } + + @Override + public String toString() { + return "PolygonEntity{" + "id=" + id + ", polygon=" + polygon + '}'; + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java index a5c7b329fc..10b5cbef4e 100644 --- a/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java +++ b/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java @@ -1,10 +1,14 @@ package com.baeldung.hibernate; import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; +import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Point; +import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; +import com.vividsolutions.jts.util.GeometricShapeFactory; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.After; @@ -13,6 +17,7 @@ import org.junit.Test; import javax.persistence.Query; import java.io.IOException; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; @@ -82,16 +87,58 @@ public class HibernateSpatialTest { .containsOnly("POINT (1 1)", "POINT (1 2)", "POINT (3 4)"); } + @Test + public void shouldSelectAllPointsWithinRadius() throws ParseException { + insertPoint("POINT (1 1)"); + insertPoint("POINT (1 2)"); + insertPoint("POINT (3 4)"); + insertPoint("POINT (5 6)"); + + Query query = session.createQuery("select p from PointEntity p where within(p.point, :circle) = true", + PointEntity.class); + query.setParameter("circle", createCircle(0.0, 0.0, 5)); + + assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString())) + .containsOnly("POINT (1 1)", "POINT (1 2)"); + } + + @Test + public void shouldSelectAdjacentPolygons() throws ParseException { + insertPolygon("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))"); + insertPolygon("POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))"); + insertPolygon("POLYGON ((2 2, 3 1, 2 5, 4 3, 3 3, 2 2))"); + + Query query = session.createQuery("select p from PolygonEntity p where touches(p.polygon, :polygon) = true", + PolygonEntity.class); + query.setParameter("polygon", wktToGeometry("POLYGON ((5 5, 5 10, 10 10, 10 5, 5 5))")); + assertThat(query.getResultList().stream().map(p -> ((PolygonEntity) p).getPolygon().toString())) + .containsOnly("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))", "POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))"); + } + private void insertPoint(String point) throws ParseException { PointEntity entity = new PointEntity(); entity.setPoint((Point) wktToGeometry(point)); session.persist(entity); } + private void insertPolygon(String polygon) throws ParseException { + PolygonEntity entity = new PolygonEntity(); + entity.setPolygon((Polygon) wktToGeometry(polygon)); + session.persist(entity); + } + private Geometry wktToGeometry(String wellKnownText) throws ParseException { WKTReader fromText = new WKTReader(); Geometry geom = null; geom = fromText.read(wellKnownText); return geom; } + + private static Geometry createCircle(double x, double y, double radius) { + GeometricShapeFactory shapeFactory = new GeometricShapeFactory(); + shapeFactory.setNumPoints(32); + shapeFactory.setCentre(new Coordinate(x, y)); + shapeFactory.setSize(radius * 2); + return shapeFactory.createCircle(); + } } diff --git a/jsonb/README.md b/jsonb/README.md index a638f0355c..9293a44808 100644 --- a/jsonb/README.md +++ b/jsonb/README.md @@ -1 +1,4 @@ ## JSON B + +## Relevant articles: +- [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api) diff --git a/junit5/README.md b/junit5/README.md new file mode 100644 index 0000000000..fb1685fdd5 --- /dev/null +++ b/junit5/README.md @@ -0,0 +1,2 @@ +## Relevant articles: +- [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order) diff --git a/libraries/pom.xml b/libraries/pom.xml index 27d867b68b..eaa2d9d38f 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -630,13 +630,13 @@ com.google.http-client google-http-client-jackson2 - ${googleclient.version} + ${googleclient.version} - com.google.http-client - google-http-client-gson - ${googleclient.version} - + com.google.http-client + google-http-client-gson + ${googleclient.version} + diff --git a/logging-modules/logback/src/main/java/com/baeldung/logback/MapAppender.java b/logging-modules/logback/src/main/java/com/baeldung/logback/MapAppender.java index 99cc6488e5..a25c54b96e 100644 --- a/logging-modules/logback/src/main/java/com/baeldung/logback/MapAppender.java +++ b/logging-modules/logback/src/main/java/com/baeldung/logback/MapAppender.java @@ -3,12 +3,14 @@ package com.baeldung.logback; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; public class MapAppender extends AppenderBase { - private final Map eventMap = new HashMap<>(); + private final ConcurrentMap eventMap + = new ConcurrentHashMap<>(); private String prefix; diff --git a/osgi/readme.md b/osgi/readme.md index ea4a411c7b..e380ae06c3 100644 --- a/osgi/readme.md +++ b/osgi/readme.md @@ -86,6 +86,9 @@ org.eclipse.osgi_3.12.1.v20170821-1548.jar = = NOT GOOD = = + ## Relevant articles: + - [Introduction to OSGi](http://www.baeldung.com/osgi) + diff --git a/patterns/README.md b/patterns/README.md index 67d84154cb..26099ae34f 100644 --- a/patterns/README.md +++ b/patterns/README.md @@ -1,4 +1,5 @@ ###Relevant Articles: - [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern) - [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java) -- [Implementing the Template Method Pattern in Java](http://www.baeldung.com/template-method-pattern-in-java) +- [Implementing the Template Method Pattern in Java](http://www.baeldung.com/java-template-method-pattern) + diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index d93271164c..4bfe2a1d25 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -15,6 +15,7 @@ - [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) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/pom.xml b/pom.xml index 462d70741e..9d8f687c0e 100644 --- a/pom.xml +++ b/pom.xml @@ -203,6 +203,7 @@ spring-rest-query-language spring-rest spring-rest-simple + spring-security-acl spring-security-cache-control spring-security-client/spring-security-jsp-authentication spring-security-client/spring-security-jsp-authorize diff --git a/spring-5/README.md b/spring-5/README.md index 1b65d01811..400e343263 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -11,3 +11,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) - [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans) - [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) +- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) +- [Spring 5 Testing with @EnabledIf Annotation](https://github.com/eugenp/tutorials/tree/master/spring-5) diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 7e30179f07..b6b6f9d370 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.M6 + 2.0.0.M7 diff --git a/spring-aop/README.md b/spring-aop/README.md index 03d5d8f429..af8ab71da0 100644 --- a/spring-aop/README.md +++ b/spring-aop/README.md @@ -2,4 +2,5 @@ - [Implementing a Custom Spring AOP Annotation](http://www.baeldung.com/spring-aop-annotation) - [Intro to AspectJ](http://www.baeldung.com/aspectj) -- [Spring Performance Logging](http://www.baeldung.com/spring-performance-logging) \ No newline at end of file +- [Spring Performance Logging](http://www.baeldung.com/spring-performance-logging) +- [Introduction to Spring AOP](http://www.baeldung.com/spring-aop) diff --git a/spring-boot-keycloak/README.md b/spring-boot-keycloak/README.md new file mode 100644 index 0000000000..cfe82c6cf7 --- /dev/null +++ b/spring-boot-keycloak/README.md @@ -0,0 +1,2 @@ +## Relevant articles: +- [A Quick Guide to Using Keycloak with Spring Boot](http://www.baeldung.com/spring-boot-keycloak) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index f126df00af..7b5fb3c880 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -28,4 +28,4 @@ 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) - +- [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql) diff --git a/spring-cloud-cli/README.md b/spring-cloud-cli/README.md index 5f83ab06fa..7f29be3f07 100644 --- a/spring-cloud-cli/README.md +++ b/spring-cloud-cli/README.md @@ -3,4 +3,4 @@ ## Spring Cloud CLI ### Relevant Articles: -- [Introduction to Spring Cloud CLI](http://www.baeldung.com/introduction-to-spring-cloud-cli/) \ No newline at end of file +- [Introduction to Spring Cloud CLI](http://www.baeldung.com/spring-cloud-cli) diff --git a/spring-cloud/README.md b/spring-cloud/README.md index 1b793144b1..b24e5b0296 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -15,6 +15,7 @@ - [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) - [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) - [Introduction to Spring Cloud Rest Client with Netflix Ribbon](http://www.baeldung.com/spring-cloud-rest-client-with-netflix-ribbon) +- [A Quick Guide to Spring Cloud Consul](http://www.baeldung.com/spring-cloud-consul) ### Relevant Articles: - [Introduction to Spring Cloud Rest Client with Netflix Ribbon](http://www.baeldung.com/spring-cloud-rest-client-with-netflix-ribbon) diff --git a/spring-core/README.md b/spring-core/README.md index 81a7aaa952..dc3bb1c9f0 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -8,3 +8,5 @@ - [Spring YAML Configuration](http://www.baeldung.com/spring-yaml) - [Introduction to Spring’s StreamUtils](http://www.baeldung.com/spring-stream-utils) - [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) +- [Groovy Bean Definitions](http://www.baeldung.com/spring-groovy-beans) +- [XML-Based Injection in Spring](http://www.baeldung.com/spring-xml-injection) diff --git a/spring-hibernate3/README.md b/spring-hibernate3/README.md new file mode 100644 index 0000000000..02928dfb51 --- /dev/null +++ b/spring-hibernate3/README.md @@ -0,0 +1,2 @@ +## Relevant articles: +- [HibernateException: No Hibernate Session Bound to Thread in Hibernate 3](http://www.baeldung.com/no-hibernate-session-bound-to-thread-exception) diff --git a/spring-integration/README.md b/spring-integration/README.md index e5b0f601ce..750ad994eb 100644 --- a/spring-integration/README.md +++ b/spring-integration/README.md @@ -1,2 +1,5 @@ ### Relevant Articles: - [Introduction to Spring Integration](http://www.baeldung.com/spring-integration) + +### Running the Sample +Executing the `mvn exec:java` maven command (either from the command line or from an IDE) will start up the application. Follow the command prompt for further instructions. diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index a162f18b9c..4e210122b0 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -22,7 +22,7 @@ 1.1.4.RELEASE 1.4.7 1.1.1 - + 4.12 2.10 1.5.0 @@ -56,7 +56,7 @@ exec-maven-plugin ${exec-maven-plugin.version} - com.baeldung.samples.Main + com.baeldung.samples.FileCopyConfig @@ -106,6 +106,12 @@ spring-integration-file ${spring.integration.version} + + junit + junit + ${junit.version} + test + diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index f3fdd78ff4..7314785731 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -346,7 +346,7 @@ - 1.3.2 + 1.3.3 4.0.0 1.4 3.1.0 diff --git a/spring-rest-simple/src/main/java/com/baeldung/apachefileupload/UploadController.java b/spring-rest-simple/src/main/java/com/baeldung/apachefileupload/UploadController.java new file mode 100644 index 0000000000..b9b6739898 --- /dev/null +++ b/spring-rest-simple/src/main/java/com/baeldung/apachefileupload/UploadController.java @@ -0,0 +1,73 @@ +package com.baeldung.apachefileupload; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemIterator; +import org.apache.commons.fileupload.FileItemStream; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.fileupload.util.Streams; +import org.apache.commons.io.IOUtils; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UploadController { + + @RequestMapping(value = "/upload", method = RequestMethod.POST) + public String handleUpload(HttpServletRequest request) { + System.out.println(System.getProperty("java.io.tmpdir")); + boolean isMultipart = ServletFileUpload.isMultipartContent(request); + // Create a factory for disk-based file items + DiskFileItemFactory factory = new DiskFileItemFactory(); + factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); + factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); + factory.setFileCleaningTracker(null); + // Configure a repository (to ensure a secure temp location is used) + ServletFileUpload upload = new ServletFileUpload(factory); + try { + // Parse the request + List items = upload.parseRequest(request); + // Process the uploaded items + Iterator iter = items.iterator(); + while (iter.hasNext()) { + FileItem item = iter.next(); + + if (!item.isFormField()) { + try (InputStream uploadedStream = item.getInputStream(); + OutputStream out = new FileOutputStream("file.mov");) { + IOUtils.copy(uploadedStream, out); + out.close(); + } + } + } + // Parse the request with Streaming API + upload = new ServletFileUpload(); + FileItemIterator iterStream = upload.getItemIterator(request); + while (iterStream.hasNext()) { + FileItemStream item = iterStream.next(); + String name = item.getFieldName(); + InputStream stream = item.openStream(); + if (!item.isFormField()) { + //Process the InputStream + } else { + //process form fields + String formFieldValue = Streams.asString(stream); + } + } + return "success!"; + } catch (IOException | FileUploadException ex) { + return "failed: " + ex.getMessage(); + } + } + +} diff --git a/spring-security-acl/README.md b/spring-security-acl/README.md new file mode 100644 index 0000000000..fb3e8160ab --- /dev/null +++ b/spring-security-acl/README.md @@ -0,0 +1,4 @@ +## Spring Security ACL Project + +### Relevant Articles +- [Introduction to Spring Security ACL](http://www.baeldung.com/spring-security-acl) diff --git a/spring-security-acl/pom.xml b/spring-security-acl/pom.xml new file mode 100644 index 0000000000..67197bc2f8 --- /dev/null +++ b/spring-security-acl/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + com.baeldung + spring-security-acl + 0.0.1-SNAPSHOT + war + + spring-security-acl + Spring Security ACL + + + parent-boot-5 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-5 + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + + + + org.springframework + spring-test + test + + + + org.springframework.security + spring-security-test + test + + + + org.springframework.security + spring-security-acl + + + org.springframework.security + spring-security-config + + + org.springframework + spring-context-support + + + net.sf.ehcache + ehcache-core + 2.6.11 + jar + + + + + diff --git a/spring-security-acl/src/main/java/org/baeldung/acl/config/ACLContext.java b/spring-security-acl/src/main/java/org/baeldung/acl/config/ACLContext.java new file mode 100644 index 0000000000..337e745c3c --- /dev/null +++ b/spring-security-acl/src/main/java/org/baeldung/acl/config/ACLContext.java @@ -0,0 +1,80 @@ +package org.baeldung.acl.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.cache.ehcache.EhCacheFactoryBean; +import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; +import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; +import org.springframework.security.acls.AclPermissionCacheOptimizer; +import org.springframework.security.acls.AclPermissionEvaluator; +import org.springframework.security.acls.domain.AclAuthorizationStrategy; +import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl; +import org.springframework.security.acls.domain.ConsoleAuditLogger; +import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy; +import org.springframework.security.acls.domain.EhCacheBasedAclCache; +import org.springframework.security.acls.jdbc.BasicLookupStrategy; +import org.springframework.security.acls.jdbc.JdbcMutableAclService; +import org.springframework.security.acls.jdbc.LookupStrategy; +import org.springframework.security.acls.model.PermissionGrantingStrategy; +import org.springframework.security.core.authority.SimpleGrantedAuthority; + +@Configuration +@EnableAutoConfiguration +public class ACLContext { + + @Autowired + DataSource dataSource; + + @Bean + public EhCacheBasedAclCache aclCache() { + return new EhCacheBasedAclCache(aclEhCacheFactoryBean().getObject(), permissionGrantingStrategy(), aclAuthorizationStrategy()); + } + + @Bean + public EhCacheFactoryBean aclEhCacheFactoryBean() { + EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean(); + ehCacheFactoryBean.setCacheManager(aclCacheManager().getObject()); + ehCacheFactoryBean.setCacheName("aclCache"); + return ehCacheFactoryBean; + } + + @Bean + public EhCacheManagerFactoryBean aclCacheManager() { + return new EhCacheManagerFactoryBean(); + } + + @Bean + public PermissionGrantingStrategy permissionGrantingStrategy() { + return new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()); + } + + @Bean + public AclAuthorizationStrategy aclAuthorizationStrategy() { + return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMIN")); + } + + @Bean + public MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler() { + DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); + AclPermissionEvaluator permissionEvaluator = new AclPermissionEvaluator(aclService()); + expressionHandler.setPermissionEvaluator(permissionEvaluator); + expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService())); + return expressionHandler; + } + + @Bean + public LookupStrategy lookupStrategy() { + return new BasicLookupStrategy(dataSource, aclCache(), aclAuthorizationStrategy(), new ConsoleAuditLogger()); + } + + @Bean + public JdbcMutableAclService aclService() { + return new JdbcMutableAclService(dataSource, lookupStrategy(), aclCache()); + } + +} \ No newline at end of file diff --git a/spring-security-acl/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java b/spring-security-acl/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java new file mode 100644 index 0000000000..e503cb1a41 --- /dev/null +++ b/spring-security-acl/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java @@ -0,0 +1,21 @@ +package org.baeldung.acl.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; +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 AclMethodSecurityConfiguration extends GlobalMethodSecurityConfiguration { + + @Autowired + MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler; + + @Override + protected MethodSecurityExpressionHandler createExpressionHandler() { + return defaultMethodSecurityExpressionHandler; + } + +} diff --git a/spring-security-acl/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java b/spring-security-acl/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java new file mode 100644 index 0000000000..24d170e56c --- /dev/null +++ b/spring-security-acl/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java @@ -0,0 +1,16 @@ +package org.baeldung.acl.config; + +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories(basePackages = "org.baeldung.acl.persistence.dao") +@PropertySource("classpath:org.baeldung.acl.datasource.properties") +@EntityScan(basePackages={ "org.baeldung.acl.persistence.entity" }) +public class JPAPersistenceConfig { + +} diff --git a/spring-security-acl/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java b/spring-security-acl/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java new file mode 100644 index 0000000000..91a2af7d83 --- /dev/null +++ b/spring-security-acl/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java @@ -0,0 +1,24 @@ +package org.baeldung.acl.persistence.dao; + +import java.util.List; + +import org.baeldung.acl.persistence.entity.NoticeMessage; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.security.access.prepost.PostAuthorize; +import org.springframework.security.access.prepost.PostFilter; +import org.springframework.security.access.prepost.PreAuthorize; + +public interface NoticeMessageRepository extends JpaRepository{ + + @PostFilter("hasPermission(filterObject, 'READ')") + List findAll(); + + @PostAuthorize("hasPermission(returnObject, 'READ')") + NoticeMessage findById(Integer id); + + @SuppressWarnings("unchecked") + @PreAuthorize("hasPermission(#noticeMessage, 'WRITE')") + NoticeMessage save(@Param("noticeMessage")NoticeMessage noticeMessage); + +} diff --git a/spring-security-acl/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java b/spring-security-acl/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java new file mode 100644 index 0000000000..bd1e866f83 --- /dev/null +++ b/spring-security-acl/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java @@ -0,0 +1,29 @@ +package org.baeldung.acl.persistence.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="system_message") +public class NoticeMessage { + + @Id + @Column + private Integer id; + @Column + private String content; + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + public String getContent() { + return content; + } + public void setContent(String content) { + this.content = content; + } +} \ No newline at end of file diff --git a/spring-security-acl/src/main/resources/acl-data.sql b/spring-security-acl/src/main/resources/acl-data.sql new file mode 100644 index 0000000000..a4e0011834 --- /dev/null +++ b/spring-security-acl/src/main/resources/acl-data.sql @@ -0,0 +1,26 @@ +INSERT INTO acl_sid (id, principal, sid) VALUES +(1, 1, 'manager'), +(2, 1, 'hr'), +(3, 0, 'ROLE_EDITOR'); + +INSERT INTO acl_class (id, class) VALUES +(1, 'org.baeldung.acl.persistence.entity.NoticeMessage'); + +INSERT INTO system_message(id,content) VALUES +(1,'First Level Message'), +(2,'Second Level Message'), +(3,'Third Level Message'); + +INSERT INTO acl_object_identity (id, object_id_class, object_id_identity, parent_object, owner_sid, entries_inheriting) VALUES +(1, 1, 1, NULL, 3, 0), +(2, 1, 2, NULL, 3, 0), +(3, 1, 3, NULL, 3, 0); + +INSERT INTO acl_entry (id, acl_object_identity, ace_order, sid, mask, granting, audit_success, audit_failure) VALUES +(1, 1, 1, 1, 1, 1, 1, 1), +(2, 1, 2, 1, 2, 1, 1, 1), +(3, 1, 3, 3, 1, 1, 1, 1), +(4, 2, 1, 2, 1, 1, 1, 1), +(5, 2, 2, 3, 1, 1, 1, 1), +(6, 3, 1, 3, 1, 1, 1, 1), +(7, 3, 2, 3, 2, 1, 1, 1); \ No newline at end of file diff --git a/spring-security-acl/src/main/resources/acl-schema.sql b/spring-security-acl/src/main/resources/acl-schema.sql new file mode 100644 index 0000000000..9f74048230 --- /dev/null +++ b/spring-security-acl/src/main/resources/acl-schema.sql @@ -0,0 +1,58 @@ +create table IF NOT EXISTS system_message (id integer not null, content varchar(255), primary key (id)); + +CREATE TABLE IF NOT EXISTS acl_sid ( + id bigint(20) NOT NULL AUTO_INCREMENT, + principal tinyint(1) NOT NULL, + sid varchar(100) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY unique_uk_1 (sid,principal) +); + +CREATE TABLE IF NOT EXISTS acl_class ( + id bigint(20) NOT NULL AUTO_INCREMENT, + class varchar(255) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY unique_uk_2 (class) +); + +CREATE TABLE IF NOT EXISTS acl_entry ( + id bigint(20) NOT NULL AUTO_INCREMENT, + acl_object_identity bigint(20) NOT NULL, + ace_order int(11) NOT NULL, + sid bigint(20) NOT NULL, + mask int(11) NOT NULL, + granting tinyint(1) NOT NULL, + audit_success tinyint(1) NOT NULL, + audit_failure tinyint(1) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY unique_uk_4 (acl_object_identity,ace_order) +); + +CREATE TABLE IF NOT EXISTS acl_object_identity ( + id bigint(20) NOT NULL AUTO_INCREMENT, + object_id_class bigint(20) NOT NULL, + object_id_identity bigint(20) NOT NULL, + parent_object bigint(20) DEFAULT NULL, + owner_sid bigint(20) DEFAULT NULL, + entries_inheriting tinyint(1) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY unique_uk_3 (object_id_class,object_id_identity) +); + +ALTER TABLE acl_entry +ADD FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity(id); + +ALTER TABLE acl_entry +ADD FOREIGN KEY (sid) REFERENCES acl_sid(id); + +-- +-- Constraints for table acl_object_identity +-- +ALTER TABLE acl_object_identity +ADD FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id); + +ALTER TABLE acl_object_identity +ADD FOREIGN KEY (object_id_class) REFERENCES acl_class (id); + +ALTER TABLE acl_object_identity +ADD FOREIGN KEY (owner_sid) REFERENCES acl_sid (id); \ No newline at end of file diff --git a/spring-security-acl/src/main/resources/org.baeldung.acl.datasource.properties b/spring-security-acl/src/main/resources/org.baeldung.acl.datasource.properties new file mode 100644 index 0000000000..40f1e6ef38 --- /dev/null +++ b/spring-security-acl/src/main/resources/org.baeldung.acl.datasource.properties @@ -0,0 +1,12 @@ +spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.username=sa +spring.datasource.password= +spring.datasource.driverClassName=org.h2.Driver +spring.jpa.hibernate.ddl-auto=update +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect + +spring.h2.console.path=/myconsole +spring.h2.console.enabled=true +spring.datasource.initialize=true +spring.datasource.schema=classpath:acl-schema.sql +spring.datasource.data=classpath:acl-data.sql \ No newline at end of file diff --git a/spring-security-acl/src/test/java/org/baeldung/acl/SpringAclTest.java b/spring-security-acl/src/test/java/org/baeldung/acl/SpringAclTest.java new file mode 100644 index 0000000000..b864639d74 --- /dev/null +++ b/spring-security-acl/src/test/java/org/baeldung/acl/SpringAclTest.java @@ -0,0 +1,119 @@ +package org.baeldung.acl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.List; + +import org.baeldung.acl.persistence.dao.NoticeMessageRepository; +import org.baeldung.acl.persistence.entity.NoticeMessage; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import org.springframework.test.context.support.DirtiesContextTestExecutionListener; +import org.springframework.test.context.transaction.TransactionalTestExecutionListener; +import org.springframework.test.context.web.ServletTestExecutionListener; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +@TestExecutionListeners(listeners={ServletTestExecutionListener.class, + DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + TransactionalTestExecutionListener.class, + WithSecurityContextTestExecutionListener.class}) +public class SpringAclTest extends AbstractJUnit4SpringContextTests{ + + private static Integer FIRST_MESSAGE_ID = 1; + private static Integer SECOND_MESSAGE_ID = 2; + private static Integer THIRD_MESSAGE_ID = 3; + private static String EDITTED_CONTENT = "EDITED"; + + @Configuration + @ComponentScan("org.baeldung.acl.*") + public static class SpringConfig { + + } + + @Autowired + NoticeMessageRepository repo; + + @Test + @WithMockUser(username="manager") + public void givenUserManager_whenFindAllMessage_thenReturnFirstMessage(){ + List details = repo.findAll(); + assertNotNull(details); + assertEquals(1,details.size()); + assertEquals(FIRST_MESSAGE_ID,details.get(0).getId()); + } + + @Test + @WithMockUser(username="manager") + public void givenUserManager_whenFind1stMessageByIdAndUpdateItsContent_thenOK(){ + NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID); + assertNotNull(firstMessage); + assertEquals(FIRST_MESSAGE_ID,firstMessage.getId()); + + firstMessage.setContent(EDITTED_CONTENT); + repo.save(firstMessage); + + NoticeMessage editedFirstMessage = repo.findById(FIRST_MESSAGE_ID); + assertNotNull(editedFirstMessage); + assertEquals(FIRST_MESSAGE_ID,editedFirstMessage.getId()); + assertEquals(EDITTED_CONTENT,editedFirstMessage.getContent()); + } + + @Test + @WithMockUser(username="hr") + public void givenUsernameHr_whenFindMessageById2_thenOK(){ + NoticeMessage secondMessage = repo.findById(SECOND_MESSAGE_ID); + assertNotNull(secondMessage); + assertEquals(SECOND_MESSAGE_ID,secondMessage.getId()); + } + + @Test(expected=AccessDeniedException.class) + @WithMockUser(username="hr") + public void givenUsernameHr_whenUpdateMessageWithId2_thenFail(){ + NoticeMessage secondMessage = new NoticeMessage(); + secondMessage.setId(SECOND_MESSAGE_ID); + secondMessage.setContent(EDITTED_CONTENT); + repo.save(secondMessage); + } + + @Test + @WithMockUser(roles={"EDITOR"}) + public void givenRoleEditor_whenFindAllMessage_thenReturn3Message(){ + List details = repo.findAll(); + assertNotNull(details); + assertEquals(3,details.size()); + } + + @Test + @WithMockUser(roles={"EDITOR"}) + public void givenRoleEditor_whenUpdateThirdMessage_thenOK(){ + NoticeMessage thirdMessage = new NoticeMessage(); + thirdMessage.setId(THIRD_MESSAGE_ID); + thirdMessage.setContent(EDITTED_CONTENT); + repo.save(thirdMessage); + } + + @Test(expected=AccessDeniedException.class) + @WithMockUser(roles={"EDITOR"}) + public void givenRoleEditor_whenFind1stMessageByIdAndUpdateContent_thenFail(){ + NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID); + assertNotNull(firstMessage); + assertEquals(FIRST_MESSAGE_ID,firstMessage.getId()); + firstMessage.setContent(EDITTED_CONTENT); + repo.save(firstMessage); + } +} + \ No newline at end of file diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/junit5/bean/NumbersBean.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/bean/NumbersBean.java new file mode 100644 index 0000000000..48730fd844 --- /dev/null +++ b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/bean/NumbersBean.java @@ -0,0 +1,22 @@ +package com.baeldung.junit5.bean; + +/** + * Bean that contains utility methods to work with numbers. + * + * @author Donato Rimenti + * + */ +public class NumbersBean { + + /** + * Returns true if a number is even, false otherwise. + * + * @param number + * the number to check + * @return true if the argument is even, false otherwise + */ + public boolean isNumberEven(int number) { + return number % 2 == 0; + } + +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java new file mode 100644 index 0000000000..0297d010e8 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.junit5.bean.test; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import com.baeldung.junit5.bean.NumbersBean; + +/** + * Test class for {@link NumbersBean}. + * + * @author Donato Rimenti + * + */ +public class NumbersBeanUnitTest { + + /** + * The bean to test. + */ + private NumbersBean bean = new NumbersBean(); + + /** + * Tests that when an even number is passed to + * {@link NumbersBean#isNumberEven(int)}, true is returned. + */ + @Test + void givenEvenNumber_whenCheckingIsNumberEven_thenTrue() { + boolean result = bean.isNumberEven(8); + + Assertions.assertTrue(result); + } + + /** + * Tests that when an odd number is passed to + * {@link NumbersBean#isNumberEven(int)}, false is returned. + */ + @Test + void givenOddNumber_whenCheckingIsNumberEven_thenFalse() { + boolean result = bean.isNumberEven(3); + + Assertions.assertFalse(result); + } + +} diff --git a/testing-modules/mockito-2/README.md b/testing-modules/mockito-2/README.md index 49741c66d1..ee443df81a 100644 --- a/testing-modules/mockito-2/README.md +++ b/testing-modules/mockito-2/README.md @@ -1,6 +1,7 @@ ### Relevant articles - [Mockito’s Java 8 Features](http://www.baeldung.com/mockito-2-java-8) +- [Lazy Verification with Mockito 2](http://www.baeldung.com/mockito-2-lazy-verification) ## Mockito 2 and Java 8 Tips diff --git a/testing-modules/mockito/README.md b/testing-modules/mockito/README.md index 0d6f69a64f..4bbc083d8c 100644 --- a/testing-modules/mockito/README.md +++ b/testing-modules/mockito/README.md @@ -12,3 +12,5 @@ - [Introduction to PowerMock](http://www.baeldung.com/intro-to-powermock) - [Mocking Exception Throwing using Mockito](http://www.baeldung.com/mockito-exceptions) - [Mocking Void Methods with Mockito](http://www.baeldung.com/mockito-void-methods) +- [Mocking of Private Methods Using PowerMock](http://www.baeldung.com/powermock-private-method) +- [Mock Final Classes and Methods with Mockito](http://www.baeldung.com/mockito-final) diff --git a/testing-modules/testing/pom.xml b/testing-modules/testing/pom.xml index 7aff0a93e0..1fd6357b87 100644 --- a/testing-modules/testing/pom.xml +++ b/testing-modules/testing/pom.xml @@ -94,6 +94,11 @@ 1.5 test + + org.javalite + javalite-common + ${javalite.version} + @@ -162,5 +167,6 @@ 0.32 1.1.0 0.12 + 1.4.13 diff --git a/testing-modules/testing/src/main/java/com/baeldung/jspec/Animal.java b/testing-modules/testing/src/main/java/com/baeldung/jspec/Animal.java new file mode 100644 index 0000000000..efb4c62bde --- /dev/null +++ b/testing-modules/testing/src/main/java/com/baeldung/jspec/Animal.java @@ -0,0 +1,41 @@ +package com.baeldung.jspec; + +public abstract class Animal { + + protected String name; + + public Animal(String name) { + this.name = name; + } + + public String getName() { + return 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(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Animal other = (Animal) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + +} diff --git a/testing-modules/testing/src/main/java/com/baeldung/jspec/Cage.java b/testing-modules/testing/src/main/java/com/baeldung/jspec/Cage.java new file mode 100644 index 0000000000..73ea343600 --- /dev/null +++ b/testing-modules/testing/src/main/java/com/baeldung/jspec/Cage.java @@ -0,0 +1,48 @@ +package com.baeldung.jspec; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class Cage { + + private Set animals = new HashSet<>(); + + public void put(Animal animal) { + animals.add(animal); + } + + public void put(Animal... animals) { + this.animals.addAll(Arrays.asList(animals)); + } + + public Animal release(Animal animal) { + return animals.remove(animal) ? animal : null; + } + + public void open() { + animals.clear(); + } + + public boolean hasAnimals() { + return animals.size() > 0; + } + + public boolean isEmpty() { + return animals.isEmpty(); + } + + public Set getAnimals() { + return this.animals; + } + + public int size() { + return animals.size(); + } + + @Override + public String toString() { + return "Cage [animals=" + animals + "]"; + } + +} diff --git a/testing-modules/testing/src/main/java/com/baeldung/jspec/Cat.java b/testing-modules/testing/src/main/java/com/baeldung/jspec/Cat.java new file mode 100644 index 0000000000..5021a1481c --- /dev/null +++ b/testing-modules/testing/src/main/java/com/baeldung/jspec/Cat.java @@ -0,0 +1,14 @@ +package com.baeldung.jspec; + +public class Cat extends Animal { + + public Cat(String name) { + super(name); + } + + @Override + public String toString() { + return "Cat [name=" + name + "]"; + } + +} diff --git a/testing-modules/testing/src/main/java/com/baeldung/jspec/Dog.java b/testing-modules/testing/src/main/java/com/baeldung/jspec/Dog.java new file mode 100644 index 0000000000..43626941e3 --- /dev/null +++ b/testing-modules/testing/src/main/java/com/baeldung/jspec/Dog.java @@ -0,0 +1,14 @@ +package com.baeldung.jspec; + +public class Dog extends Animal { + + public Dog(String name) { + super(name); + } + + @Override + public String toString() { + return "Dog [name=" + name + "]"; + } + +} diff --git a/testing-modules/testing/src/test/java/com/baeldung/jspec/CageUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/jspec/CageUnitTest.java new file mode 100644 index 0000000000..33ef986588 --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/jspec/CageUnitTest.java @@ -0,0 +1,126 @@ +package com.baeldung.jspec; + +import static org.javalite.test.jspec.JSpec.$; +import static org.javalite.test.jspec.JSpec.expect; +import static org.javalite.test.jspec.JSpec.the; + +import java.util.Set; + +import org.javalite.test.jspec.DifferenceExpectation; +import org.junit.Test; + +public class CageUnitTest { + + Cat tomCat = new Cat("Tom"); + Cat felixCat = new Cat("Felix"); + Dog boltDog = new Dog("Bolt"); + Cage cage = new Cage(); + + + @Test + public void puttingAnimals_shouldIncreaseCageSize() { + // When + cage.put(tomCat, boltDog); + + // Then + the(cage.size()).shouldEqual(2); + } + + @Test + public void releasingAnimals_shouldDecreaseCageSize() { + // When + cage.put(tomCat, boltDog); + cage.release(tomCat); + + // Then + the(cage.size()).shouldEqual(1); + } + + @Test + public void puttingAnimals_shouldLeaveThemInsideTheCage() { + // When + cage.put(tomCat, boltDog); + + // Then + the(cage).shouldHave("animals"); + } + + @Test + public void openingTheCage_shouldReleaseAllAnimals() { + // When + cage.put(tomCat, boltDog); + + // Then + the(cage).shouldNotBe("empty"); + + // When + cage.open(); + + // Then + the(cage).shouldBe("empty"); + the(cage.isEmpty()).shouldBeTrue(); + } + + @Test + public void comparingTwoDogs() { + // When + Dog firstDog = new Dog("Rex"); + Dog secondDog = new Dog("Rex"); + + // Then + $(firstDog).shouldEqual(secondDog); + $(firstDog).shouldNotBeTheSameAs(secondDog); + } + + @Test + public void puttingCatsOnly_shouldLetCageAnimalsToContainCats() { + // When + cage.put(tomCat, felixCat); + + // Then + Set animals = cage.getAnimals(); + the(animals).shouldContain(tomCat); + the(animals).shouldContain(felixCat); + the(animals).shouldNotContain(boltDog); + } + + @Test + public void puttingCatsOnly_shouldLetCageToContainCats() { + // When + cage.put(tomCat, felixCat); + + // Then + // Check with toString of the tested objects + the(cage).shouldContain(tomCat); + the(cage).shouldContain(felixCat); + the(cage).shouldNotContain(boltDog); + } + + @Test + public void puttingMoreAnimals_shouldChangeSize() { + // When + cage.put(tomCat, boltDog); + + // Then + expect( new DifferenceExpectation(cage.size()) { + + @Override + public Integer exec() { + cage.release(tomCat); + return cage.size(); + } + } ); + } + + + @Test + public void releasingTheDog_shouldReleaseAnAnimalOfDogType() { + // When + cage.put(boltDog); + Animal releasedAnimal = cage.release(boltDog); + + // Then + the(releasedAnimal).shouldNotBeNull(); + the(releasedAnimal).shouldBeA(Dog.class); + } +} diff --git a/testing-modules/testing/src/test/java/com/baeldung/jspec/JSpecUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/jspec/JSpecUnitTest.java new file mode 100644 index 0000000000..0e35e26728 --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/jspec/JSpecUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.jspec; + +import static org.javalite.test.jspec.JSpec.$; +import static org.javalite.test.jspec.JSpec.a; +import static org.javalite.test.jspec.JSpec.expect; +import static org.javalite.test.jspec.JSpec.it; +import static org.javalite.test.jspec.JSpec.the; + +import java.util.Arrays; +import java.util.List; + +import org.javalite.test.jspec.ExceptionExpectation; +import org.junit.Test; + +public class JSpecUnitTest { + + @Test + public void onePlusTwo_shouldEqualThree() { + $(1 + 2).shouldEqual(3); + a(1 + 2).shouldEqual(3); + the(1 + 2).shouldEqual(3); + it(1 + 2).shouldEqual(3); + } + + @Test + public void messageShouldContainJSpec() { + String message = "Welcome to JSpec demo"; + // The message should not be empty + the(message).shouldNotBe("empty"); + // The message should contain JSpec + the(message).shouldContain("JSpec"); + } + + public void colorsListShouldContainRed() { + List colorsList = Arrays.asList("red", "green", "blue"); + $(colorsList).shouldContain("red"); + } + + public void guessedNumberShouldEqualHiddenNumber() { + Integer guessedNumber = 11; + Integer hiddenNumber = 11; + + $(guessedNumber).shouldEqual(hiddenNumber); + $(guessedNumber).shouldNotBeTheSameAs(hiddenNumber); + } + + @Test + public void dividingByThero_shouldThrowArithmeticException() { + expect(new ExceptionExpectation(ArithmeticException.class) { + @Override + public void exec() throws ArithmeticException { + System.out.println(1 / 0); + } + } ); + } + +} diff --git a/vavr/src/main/java/com/baeldung/vavr/future/Util.java b/vavr/src/main/java/com/baeldung/vavr/future/Util.java new file mode 100644 index 0000000000..790ef2bf88 --- /dev/null +++ b/vavr/src/main/java/com/baeldung/vavr/future/Util.java @@ -0,0 +1,20 @@ +package com.baeldung.vavr.future; + +public class Util { + + public static String appendData(String initial) { + return initial + "Baeldung!"; + } + + public static int divideByZero(int num) { + return num / 0; + } + + public static String getSubstringMinusOne(String s) { + return s.substring(-1); + } + + public static String getSubstringMinusTwo(String s) { + return s.substring(-2); + } +} diff --git a/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java b/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java new file mode 100644 index 0000000000..1f2a3761eb --- /dev/null +++ b/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java @@ -0,0 +1,177 @@ +package com.baeldung.vavr.future; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; + +import org.junit.Test; + +import io.vavr.Tuple; +import io.vavr.Tuple2; +import io.vavr.concurrent.Future; +import io.vavr.control.Option; +import io.vavr.control.Try; + +public class FutureTest { + + @Test + public void whenChangeExecutorService_thenCorrect() { + String initialValue = "Welcome to "; + Future resultFuture = Future.of( + Executors.newSingleThreadExecutor(), + () -> Util.appendData(initialValue)); + String result = resultFuture.get(); + + assertThat(result).isEqualTo("Welcome to Baeldung!"); + } + + @Test + public void whenAppendData_thenCorrect1() { + String initialValue = "Welcome to "; + Future resultFuture = Future.of(() -> Util.appendData(initialValue)); + String result = resultFuture.get(); + + assertThat(result).isEqualTo("Welcome to Baeldung!"); + } + + @Test + public void whenAppendData_thenCorrect2() { + String initialValue = "Welcome to "; + Future resultFuture = Future.of(() -> Util.appendData(initialValue)); + resultFuture.await(); + Option> futureOption = resultFuture.getValue(); + Try futureTry = futureOption.get(); + String result = futureTry.get(); + + assertThat(result).isEqualTo("Welcome to Baeldung!"); + } + + @Test + public void whenAppendData_thenSuccess() { + String initialValue = "Welcome to "; + Future resultFuture = Future.of(() -> Util.appendData(initialValue)) + .onSuccess(finalResult -> System.out.println("Successfully Completed - Result: " + finalResult)) + .onFailure(finalResult -> System.out.println("Failed - Result: " + finalResult)); + String result = resultFuture.get(); + + assertThat(result).isEqualTo("Welcome to Baeldung!"); + } + + @Test + public void whenChainingCallbacks_thenCorrect() { + String initialValue = "Welcome to "; + Future resultFuture = Future.of(() -> Util.appendData(initialValue)) + .andThen(finalResult -> System.out.println("Completed - 1: " + finalResult)) + .andThen(finalResult -> System.out.println("Completed - 2: " + finalResult)); + String result = resultFuture.get(); + + assertThat(result).isEqualTo("Welcome to Baeldung!"); + } + + @Test + public void whenCallAwait_thenCorrect() { + String initialValue = "Welcome to "; + Future resultFuture = Future.of(() -> Util.appendData(initialValue)); + resultFuture = resultFuture.await(); + String result = resultFuture.get(); + + assertThat(result).isEqualTo("Welcome to Baeldung!"); + } + + @Test + public void whenDivideByZero_thenGetThrowable1() { + Future resultFuture = Future.of(() -> Util.divideByZero(10)); + Future throwableFuture = resultFuture.failed(); + Throwable throwable = throwableFuture.get(); + + assertThat(throwable.getMessage()).isEqualTo("/ by zero"); + } + + @Test + public void whenDivideByZero_thenGetThrowable2() { + Future resultFuture = Future.of(() -> Util.divideByZero(10)); + resultFuture.await(); + Option throwableOption = resultFuture.getCause(); + Throwable throwable = throwableOption.get(); + + assertThat(throwable.getMessage()).isEqualTo("/ by zero"); + } + + @Test + public void whenDivideByZero_thenCorrect() throws InterruptedException { + Future resultFuture = Future.of(() -> Util.divideByZero(10)); + resultFuture.await(); + + assertThat(resultFuture.isCompleted()).isTrue(); + assertThat(resultFuture.isSuccess()).isFalse(); + assertThat(resultFuture.isFailure()).isTrue(); + } + + @Test + public void whenAppendData_thenFutureNotEmpty() { + String initialValue = "Welcome to "; + Future resultFuture = Future.of(() -> Util.appendData(initialValue)); + resultFuture.await(); + + assertThat(resultFuture.isEmpty()).isFalse(); + } + + @Test + public void whenCallZip_thenCorrect() { + Future> future = Future.of(() -> "John") + .zip(Future.of(() -> new Integer(5))); + future.await(); + + assertThat(future.get()).isEqualTo(Tuple.of("John", new Integer(5))); + } + + @Test + public void whenConvertToCompletableFuture_thenCorrect() throws InterruptedException, ExecutionException { + String initialValue = "Welcome to "; + Future resultFuture = Future.of(() -> Util.appendData(initialValue)); + CompletableFuture convertedFuture = resultFuture.toCompletableFuture(); + + assertThat(convertedFuture.get()).isEqualTo("Welcome to Baeldung!"); + } + + @Test + public void whenCallMap_thenCorrect() { + Future futureResult = Future.of(() -> new StringBuilder("from Baeldung")) + .map(a -> "Hello " + a); + futureResult.await(); + + assertThat(futureResult.get()).isEqualTo("Hello from Baeldung"); + } + + @Test + public void whenFutureFails_thenGetErrorMessage() { + Future resultFuture = Future.of(() -> Util.getSubstringMinusOne("Hello")); + Future errorMessageFuture = resultFuture.recover(Throwable::getMessage); + String errorMessage = errorMessageFuture.get(); + + assertThat(errorMessage).isEqualTo("String index out of range: -1"); + } + + @Test + public void whenFutureFails_thenGetAnotherFuture() { + Future resultFuture = Future.of(() -> Util.getSubstringMinusOne("Hello")); + Future errorMessageFuture = resultFuture.recoverWith(a -> Future.of(a::getMessage)); + String errorMessage = errorMessageFuture.get(); + + assertThat(errorMessage).isEqualTo("String index out of range: -1"); + } + + @Test + public void whenBothFuturesFail_thenGetErrorMessage() { + Future future1 = Future.of(() -> Util.getSubstringMinusOne("Hello")); + Future future2 = Future.of(() -> Util.getSubstringMinusTwo("Hello")); + Future errorMessageFuture = future1.fallbackTo(future2); + Future errorMessage = errorMessageFuture.failed(); + + assertThat( + errorMessage.get().getMessage()) + .isEqualTo("String index out of range: -1"); + } +} diff --git a/vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java deleted file mode 100644 index 437742c964..0000000000 --- a/vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java +++ /dev/null @@ -1,289 +0,0 @@ -package com.baeldung.vavr.future; - -import static io.vavr.API.$; -import static io.vavr.API.Case; -import static io.vavr.API.Match; -import static io.vavr.Predicates.exists; -import static io.vavr.Predicates.forAll; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.concurrent.CancellationException; -import java.util.function.Consumer; -import java.util.function.Predicate; - -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.internal.verification.VerificationModeFactory; -import org.mockito.verification.Timeout; - -import io.vavr.Tuple; -import io.vavr.Tuple2; -import io.vavr.collection.List; -import io.vavr.concurrent.Future; -import io.vavr.control.Try; - -public class FutureUnitTest { - - private final String SUCCESS = "Success"; - private final String FAILURE = "Failure"; - - @Test - public void givenFunctionReturnInteger_WhenCallWithFuture_ShouldReturnFunctionValue() { - Future future = Future.of(() -> 1); - - assertEquals(1, future.get().intValue()); - } - - @Test - public void givenFunctionGetRemoteHttpResourceAsString_WhenCallSuccessWithFuture_ShouldReturnContentValueAsString() { - String url = "http://resource"; - String content = "Content from " + url; - Future future = Future.of(() -> getResource(url)); - - assertEquals(content, future.get()); - } - - @Test - public void givenFunctionThrowException_WhenCallWithFuture_ShouldReturnFailure() { - Future future = Future.of(() -> getResourceThrowException("")); - future.await(); - - assertTrue(future.isFailure()); - } - - @Test - public void givenAFutureReturnZero_WhenCheckFutureWithExistEvenValue_ShouldReturnRight() { - Future future = Future.of(() -> 2); - boolean result = future.exists(i -> i % 2 == 0); - - assertTrue(result); - } - - @Test - public void givenFunction_WhenCallWithFutureAndRegisterConsumerForSuccess_ShouldCallConsumerToStoreValue() { - Future future = Future.of(() -> 1); - MockConsumer consumer = Mockito.mock(MockConsumer.class); - future.onSuccess(consumer); - Mockito.verify(consumer, new Timeout(1000, VerificationModeFactory.times(1))).accept(1); - } - - @Test - public void givenFunctionThrowException_WhenCallWithFutureAndRegisterConsumerForFailer_ShouldCallConsumerToStoreException() { - Future future = Future.of(() -> getResourceThrowException("")); - MockThrowableConsumer consumer = Mockito.mock(MockThrowableConsumer.class); - future.onFailure(consumer); - Mockito.verify(consumer, new Timeout(1000, VerificationModeFactory.times(1))).accept(Mockito.any()); - } - - @Test - public void givenAFuture_WhenAddAndThenConsumer_ShouldCallConsumerWithResultOfFutureAction() { - MockTryConsumer consumer1 = Mockito.mock(MockTryConsumer.class); - MockTryConsumer consumer2 = Mockito.mock(MockTryConsumer.class); - Future future = Future.of(() -> 1); - Future andThenFuture = future.andThen(consumer1).andThen(consumer2); - andThenFuture.await(); - Mockito.verify(consumer1, VerificationModeFactory.times(1)).accept(Try.success(1)); - Mockito.verify(consumer2, VerificationModeFactory.times(1)).accept(Try.success(1)); - } - - @Test - public void givenAFailureFuture_WhenCallOrElseFunction_ShouldReturnNewFuture() { - Future future = Future.failed(new RuntimeException()); - Future future2 = future.orElse(Future.of(() -> 2)); - - assertEquals(2, future2.get().intValue()); - } - - @Test(expected = CancellationException.class) - public void givenAFuture_WhenCallCancel_ShouldReturnCancellationException() { - long waitTime = 1000; - Future future = Future.of(() -> { - Thread.sleep(waitTime); - return 1; - }); - future.cancel(); - future.await(); - future.get(); - } - - @Test - public void givenAFuture_WhenCallFallBackWithSuccessFuture_ShouldReturnFutureResult() { - String expectedResult = "take this"; - Future future = Future.of(() -> expectedResult); - Future secondFuture = Future.of(() -> "take that"); - Future futureResult = future.fallbackTo(secondFuture); - futureResult.await(); - - assertEquals(expectedResult, futureResult.get()); - } - - @Test - public void givenAFuture_WhenCallFallBackWithFailureFuture_ShouldReturnValueOfFallBackFuture() { - String expectedResult = "take that"; - Future future = Future.failed(new RuntimeException()); - Future fallbackFuture = Future.of(() -> expectedResult); - Future futureResult = future.fallbackTo(fallbackFuture); - - assertEquals(expectedResult, futureResult.get()); - } - - @Test - public void givenAFuture_WhenTransformByAddingOne_ShouldReturn() { - Future future = Future.of(() -> 1).transformValue(f -> Try.of(() -> "Hello: " + f.get())); - - assertEquals("Hello: 1", future.get()); - } - - @Test - public void givenAFutureOfInt_WhenMapToString_ShouldCombineAndReturn() { - Future future = Future.of(()->1).map(i -> "Hello: " + i); - - assertEquals("Hello: 1", future.get()); - } - - @Test - public void givenAFutureOfInt_WhenFlatMapToString_ShouldCombineAndReturn() { - Future futureMap = Future.of(() -> 1).flatMap((i) -> Future.of(() -> "Hello: " + i)); - - assertEquals("Hello: 1", futureMap.get()); - } - - @Test - public void givenAFutureOf2String_WhenZip_ShouldReturnTupleOf2String() { - Future> future = Future.of(() -> "hello").zip(Future.of(() -> "world")); - - assertEquals(Tuple.of("hello", "world"), future.get()); - } - - @Test - public void givenGetResourceWithFuture_WhenWaitAndMatchWithPredicate_ShouldReturnSuccess() { - String url = "http://resource"; - Future future = Future.of(() -> getResource(url)); - future.await(); - String s = Match(future).of( - Case($(future0 -> future0.isSuccess()), SUCCESS), - Case($(), FAILURE)); - - assertEquals(SUCCESS, s); - } - - @Test - public void givenAFailedFuture_WhenWaitAndMatchWithPredicateCheckSuccess_ShouldReturnFailed() { - Future future = Future.failed(new RuntimeException()); - future.await(); - String s = Match(future).of( - Case($(future0 -> future0.isSuccess()), SUCCESS), - Case($(), FAILURE)); - - assertEquals(FAILURE, s); - } - - @Test - public void givenAFuture_WhenMatchWithFuturePredicate_ShouldReturnSuccess() { - Future future = Future.of(() -> { - Thread.sleep(10); - return 1; - }); - Predicate> predicate = f -> f.exists(i -> i % 2 == 1); - - String s = Match(future).of( - Case($(predicate), "Even"), - Case($(), "Odd")); - - assertEquals("Even", s); - } - - @Test - public void givenAListOfFutureReturnFist3Integers_WhenMatchWithExistEvenNumberPredicate_ShouldReturnSuccess() { - List> futures = getFutureOfFirst3Number(); - Predicate> predicate0 = future -> future.exists(i -> i % 2 == 0); - String s = Match(futures).of( - Case($(exists(predicate0)), "Even"), - Case($(), "Odd")); - - assertEquals("Even", s); - } - - @Test - public void givenAListOfFutureReturnFist3Integers_WhenMatchWithForAllNumberBiggerThanZeroPredicate_ShouldReturnSuccess() { - List> futures = getFutureOfFirst3Number(); - Predicate> predicate0 = future -> future.exists(i -> i > 0); - String s = Match(futures).of( - Case($(forAll(predicate0)), "Positive numbers"), - Case($(), "None")); - - assertEquals("Positive numbers", s); - } - - @Test - public void givenAListOfFutureReturnFist3Integers_WhenMatchWithForAllNumberSmallerThanZeroPredicate_ShouldReturnFailed() { - List> futures = getFutureOfFirst3Number(); - Predicate> predicate0 = future -> future.exists(i -> i < 0); - String s = Match(futures).of( - Case($(forAll(predicate0)), "Negative numbers"), - Case($(), "None")); - - assertEquals("None", s); - } - - private String getResource(String url) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - return "Content from " + url; - } - - private String getResourceThrowException(String url) { - throw new RuntimeException("Exception when get resource " + url); - } - - private List> getFutureOfFirst3Number() { - List> futures = List.of(Future.of(() -> 1), Future.of(() -> 2), Future.of(() -> 3)); - return futures; - } - - private static void checkOnSuccessFunction() { - Future future = Future.of(() -> 1); - future.onSuccess(i -> System.out.println("Future finish with result: " + i)); - } - - private static void checkOnFailureFunction() { - Future future = Future.of(() -> {throw new RuntimeException("Failed");}); - future.onFailure(t -> System.out.println("Future failures with exception: " + t)); - } - - private static void runAndThenConsumer() { - Future future = Future.of(() -> 1); - future.andThen(i -> System.out.println("Do side-effect action 1 with input: " + i.get())). - andThen((i) -> System.out.println("Do side-effect action 2 with input: " + i.get())); - } - - public static void main(String[] args) throws InterruptedException { - checkOnSuccessFunction(); - checkOnFailureFunction(); - runAndThenConsumer(); - Thread.sleep(1000); - } -} - - -class MockConsumer implements Consumer { - @Override - public void accept(Integer t) { - } -} - -class MockTryConsumer implements Consumer> { - @Override - public void accept(Try t) { - } -} - -class MockThrowableConsumer implements Consumer { - @Override - public void accept(Throwable t) { - } -}